e258ec617e69e6274ed7a91c59deca71e4a44eeb
[mat/samba.git] / source3 / utils / net_rpc.c
1 /*
2    Samba Unix/Linux SMB client library
3    Distributed SMB/CIFS Server Management Utility
4    Copyright (C) 2001 Andrew Bartlett (abartlet@samba.org)
5    Copyright (C) 2002 Jim McDonough (jmcd@us.ibm.com)
6    Copyright (C) 2004,2008 Guenther Deschner (gd@samba.org)
7    Copyright (C) 2005 Jeremy Allison (jra@samba.org)
8    Copyright (C) 2006 Jelmer Vernooij (jelmer@samba.org)
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 #include "includes.h"
24 #include "utils/net.h"
25 #include "rpc_client/cli_pipe.h"
26 #include "../libcli/auth/libcli_auth.h"
27 #include "../librpc/gen_ndr/ndr_samr_c.h"
28 #include "rpc_client/cli_samr.h"
29 #include "rpc_client/init_samr.h"
30 #include "../librpc/gen_ndr/ndr_lsa_c.h"
31 #include "rpc_client/cli_lsarpc.h"
32 #include "../librpc/gen_ndr/ndr_netlogon_c.h"
33 #include "../librpc/gen_ndr/ndr_srvsvc_c.h"
34 #include "../librpc/gen_ndr/ndr_spoolss.h"
35 #include "../librpc/gen_ndr/ndr_initshutdown_c.h"
36 #include "../librpc/gen_ndr/ndr_winreg_c.h"
37 #include "secrets.h"
38 #include "lib/netapi/netapi.h"
39 #include "lib/netapi/netapi_net.h"
40 #include "librpc/gen_ndr/libnet_join.h"
41 #include "libnet/libnet_join.h"
42 #include "rpc_client/init_lsa.h"
43 #include "../libcli/security/security.h"
44 #include "libsmb/libsmb.h"
45 #include "libsmb/clirap.h"
46 #include "nsswitch/libwbclient/wbclient.h"
47 #include "passdb.h"
48 #include "../libcli/smb/smbXcli_base.h"
49
50 static int net_mode_share;
51 static NTSTATUS sync_files(struct copy_clistate *cp_clistate, const char *mask);
52
53 /**
54  * @file net_rpc.c
55  *
56  * @brief RPC based subcommands for the 'net' utility.
57  *
58  * This file should contain much of the functionality that used to
59  * be found in rpcclient, execpt that the commands should change
60  * less often, and the fucntionality should be sane (the user is not
61  * expected to know a rid/sid before they conduct an operation etc.)
62  *
63  * @todo Perhaps eventually these should be split out into a number
64  * of files, as this could get quite big.
65  **/
66
67
68 /**
69  * Many of the RPC functions need the domain sid.  This function gets
70  *  it at the start of every run
71  *
72  * @param cli A cli_state already connected to the remote machine
73  *
74  * @return The Domain SID of the remote machine.
75  **/
76
77 NTSTATUS net_get_remote_domain_sid(struct cli_state *cli, TALLOC_CTX *mem_ctx,
78                                    struct dom_sid **domain_sid,
79                                    const char **domain_name)
80 {
81         struct rpc_pipe_client *lsa_pipe = NULL;
82         struct policy_handle pol;
83         NTSTATUS status, result;
84         union lsa_PolicyInformation *info = NULL;
85         struct dcerpc_binding_handle *b;
86
87         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
88                                           &lsa_pipe);
89         if (!NT_STATUS_IS_OK(status)) {
90                 d_fprintf(stderr, _("Could not initialise lsa pipe\n"));
91                 return status;
92         }
93
94         b = lsa_pipe->binding_handle;
95
96         status = rpccli_lsa_open_policy(lsa_pipe, mem_ctx, false,
97                                      SEC_FLAG_MAXIMUM_ALLOWED,
98                                      &pol);
99         if (!NT_STATUS_IS_OK(status)) {
100                 d_fprintf(stderr, "open_policy %s: %s\n",
101                           _("failed"),
102                           nt_errstr(status));
103                 return status;
104         }
105
106         status = dcerpc_lsa_QueryInfoPolicy(b, mem_ctx,
107                                             &pol,
108                                             LSA_POLICY_INFO_ACCOUNT_DOMAIN,
109                                             &info,
110                                             &result);
111         if (!NT_STATUS_IS_OK(status)) {
112                 d_fprintf(stderr, "lsaquery %s: %s\n",
113                           _("failed"),
114                           nt_errstr(status));
115                 return status;
116         }
117         if (!NT_STATUS_IS_OK(result)) {
118                 d_fprintf(stderr, "lsaquery %s: %s\n",
119                           _("failed"),
120                           nt_errstr(result));
121                 return result;
122         }
123
124         *domain_name = info->account_domain.name.string;
125         *domain_sid = info->account_domain.sid;
126
127         dcerpc_lsa_Close(b, mem_ctx, &pol, &result);
128         TALLOC_FREE(lsa_pipe);
129
130         return NT_STATUS_OK;
131 }
132
133 /**
134  * Run a single RPC command, from start to finish.
135  *
136  * @param pipe_name the pipe to connect to (usually a PIPE_ constant)
137  * @param conn_flag a NET_FLAG_ combination.  Passed to
138  *                   net_make_ipc_connection.
139  * @param argc  Standard main() style argc.
140  * @param argv  Standard main() style argv. Initial components are already
141  *              stripped.
142  * @return A shell status integer (0 for success).
143  */
144
145 int run_rpc_command(struct net_context *c,
146                         struct cli_state *cli_arg,
147                         const struct ndr_interface_table *table,
148                         int conn_flags,
149                         rpc_command_fn fn,
150                         int argc,
151                         const char **argv)
152 {
153         struct cli_state *cli = NULL;
154         struct rpc_pipe_client *pipe_hnd = NULL;
155         TALLOC_CTX *mem_ctx;
156         NTSTATUS nt_status;
157         struct dom_sid *domain_sid;
158         const char *domain_name;
159         int ret = -1;
160
161         /* make use of cli_state handed over as an argument, if possible */
162         if (!cli_arg) {
163                 nt_status = net_make_ipc_connection(c, conn_flags, &cli);
164                 if (!NT_STATUS_IS_OK(nt_status)) {
165                         DEBUG(1, ("failed to make ipc connection: %s\n",
166                                   nt_errstr(nt_status)));
167                         return -1;
168                 }
169         } else {
170                 cli = cli_arg;
171         }
172
173         if (!cli) {
174                 return -1;
175         }
176
177         /* Create mem_ctx */
178
179         if (!(mem_ctx = talloc_init("run_rpc_command"))) {
180                 DEBUG(0, ("talloc_init() failed\n"));
181                 goto fail;
182         }
183
184         nt_status = net_get_remote_domain_sid(cli, mem_ctx, &domain_sid,
185                                               &domain_name);
186         if (!NT_STATUS_IS_OK(nt_status)) {
187                 goto fail;
188         }
189
190         if (!(conn_flags & NET_FLAGS_NO_PIPE)) {
191                 if (lp_client_schannel()
192                     && (ndr_syntax_id_equal(&table->syntax_id,
193                                             &ndr_table_netlogon.syntax_id))) {
194                         /* Always try and create an schannel netlogon pipe. */
195                         nt_status = cli_rpc_pipe_open_schannel(
196                                 cli, table, NCACN_NP,
197                                 DCERPC_AUTH_LEVEL_PRIVACY, domain_name,
198                                 &pipe_hnd);
199                         if (!NT_STATUS_IS_OK(nt_status)) {
200                                 DEBUG(0, ("Could not initialise schannel netlogon pipe. Error was %s\n",
201                                         nt_errstr(nt_status) ));
202                                 goto fail;
203                         }
204                 } else {
205                         if (conn_flags & NET_FLAGS_SEAL) {
206                                 nt_status = cli_rpc_pipe_open_generic_auth(
207                                         cli, table,
208                                         (conn_flags & NET_FLAGS_TCP) ?
209                                         NCACN_IP_TCP : NCACN_NP,
210                                         DCERPC_AUTH_TYPE_NTLMSSP,
211                                         DCERPC_AUTH_LEVEL_PRIVACY,
212                                         smbXcli_conn_remote_name(cli->conn),
213                                         lp_workgroup(), c->opt_user_name,
214                                         c->opt_password, &pipe_hnd);
215                         } else {
216                                 nt_status = cli_rpc_pipe_open_noauth(
217                                         cli, table,
218                                         &pipe_hnd);
219                         }
220                         if (!NT_STATUS_IS_OK(nt_status)) {
221                                 DEBUG(0, ("Could not initialise pipe %s. Error was %s\n",
222                                           table->name,
223                                         nt_errstr(nt_status) ));
224                                 goto fail;
225                         }
226                 }
227         }
228
229         nt_status = fn(c, domain_sid, domain_name, cli, pipe_hnd, mem_ctx, argc, argv);
230
231         if (!NT_STATUS_IS_OK(nt_status)) {
232                 DEBUG(1, ("rpc command function failed! (%s)\n", nt_errstr(nt_status)));
233         } else {
234                 ret = 0;
235                 DEBUG(5, ("rpc command function succedded\n"));
236         }
237
238         if (!(conn_flags & NET_FLAGS_NO_PIPE)) {
239                 if (pipe_hnd) {
240                         TALLOC_FREE(pipe_hnd);
241                 }
242         }
243
244 fail:
245         /* close the connection only if it was opened here */
246         if (!cli_arg) {
247                 cli_shutdown(cli);
248         }
249
250         talloc_destroy(mem_ctx);
251         return ret;
252 }
253
254 /**
255  * Force a change of the trust acccount password.
256  *
257  * All parameters are provided by the run_rpc_command function, except for
258  * argc, argv which are passed through.
259  *
260  * @param domain_sid The domain sid acquired from the remote server.
261  * @param cli A cli_state connected to the server.
262  * @param mem_ctx Talloc context, destroyed on completion of the function.
263  * @param argc  Standard main() style argc.
264  * @param argv  Standard main() style argv. Initial components are already
265  *              stripped.
266  *
267  * @return Normal NTSTATUS return.
268  **/
269
270 static NTSTATUS rpc_changetrustpw_internals(struct net_context *c,
271                                         const struct dom_sid *domain_sid,
272                                         const char *domain_name,
273                                         struct cli_state *cli,
274                                         struct rpc_pipe_client *pipe_hnd,
275                                         TALLOC_CTX *mem_ctx,
276                                         int argc,
277                                         const char **argv)
278 {
279         NTSTATUS status;
280
281         status = trust_pw_find_change_and_store_it(pipe_hnd, mem_ctx, c->opt_target_workgroup);
282         if (!NT_STATUS_IS_OK(status)) {
283                 d_fprintf(stderr, _("Failed to change machine account password: %s\n"),
284                         nt_errstr(status));
285                 return status;
286         }
287
288         return NT_STATUS_OK;
289 }
290
291 /**
292  * Force a change of the trust acccount password.
293  *
294  * @param argc  Standard main() style argc.
295  * @param argv  Standard main() style argv. Initial components are already
296  *              stripped.
297  *
298  * @return A shell status integer (0 for success).
299  **/
300
301 int net_rpc_changetrustpw(struct net_context *c, int argc, const char **argv)
302 {
303         if (c->display_usage) {
304                 d_printf(  "%s\n"
305                            "net rpc changetrustpw\n"
306                            "    %s\n",
307                          _("Usage:"),
308                          _("Change the machine trust password"));
309                 return 0;
310         }
311
312         return run_rpc_command(c, NULL, &ndr_table_netlogon,
313                                NET_FLAGS_ANONYMOUS | NET_FLAGS_PDC,
314                                rpc_changetrustpw_internals,
315                                argc, argv);
316 }
317
318 /**
319  * Join a domain, the old way.  This function exists to allow
320  * the message to be displayed when oldjoin was explicitly
321  * requested, but not when it was implied by "net rpc join".
322  *
323  * This uses 'machinename' as the inital password, and changes it.
324  *
325  * The password should be created with 'server manager' or equiv first.
326  *
327  * @param argc  Standard main() style argc.
328  * @param argv  Standard main() style argv. Initial components are already
329  *              stripped.
330  *
331  * @return A shell status integer (0 for success).
332  **/
333
334 static int net_rpc_oldjoin(struct net_context *c, int argc, const char **argv)
335 {
336         struct libnet_JoinCtx *r = NULL;
337         TALLOC_CTX *mem_ctx;
338         WERROR werr;
339         const char *domain = lp_workgroup(); /* FIXME */
340         bool modify_config = lp_config_backend_is_registry();
341         enum netr_SchannelType sec_chan_type;
342         char *pw = NULL;
343
344         if (c->display_usage) {
345                 d_printf("Usage:\n"
346                          "net rpc oldjoin\n"
347                          "    Join a domain the old way\n");
348                 return 0;
349         }
350
351         mem_ctx = talloc_init("net_rpc_oldjoin");
352         if (!mem_ctx) {
353                 return -1;
354         }
355
356         werr = libnet_init_JoinCtx(mem_ctx, &r);
357         if (!W_ERROR_IS_OK(werr)) {
358                 goto fail;
359         }
360
361         /*
362            check what type of join - if the user want's to join as
363            a BDC, the server must agree that we are a BDC.
364         */
365         if (argc >= 0) {
366                 sec_chan_type = get_sec_channel_type(argv[0]);
367         } else {
368                 sec_chan_type = get_sec_channel_type(NULL);
369         }
370
371         if (!c->msg_ctx) {
372                 d_fprintf(stderr, _("Could not initialise message context. "
373                         "Try running as root\n"));
374                 werr = WERR_ACCESS_DENIED;
375                 goto fail;
376         }
377
378         pw = talloc_strndup(r, lp_netbios_name(), 14);
379         if (pw == NULL) {
380                 werr = WERR_NOMEM;
381                 goto fail;
382         }
383
384         r->in.msg_ctx                   = c->msg_ctx;
385         r->in.domain_name               = domain;
386         r->in.secure_channel_type       = sec_chan_type;
387         r->in.dc_name                   = c->opt_host;
388         r->in.admin_account             = "";
389         r->in.admin_password            = strlower_talloc(r, pw);
390         if (r->in.admin_password == NULL) {
391                 werr = WERR_NOMEM;
392                 goto fail;
393         }
394         r->in.debug                     = true;
395         r->in.modify_config             = modify_config;
396         r->in.join_flags                = WKSSVC_JOIN_FLAGS_JOIN_TYPE |
397                                           WKSSVC_JOIN_FLAGS_JOIN_UNSECURE |
398                                           WKSSVC_JOIN_FLAGS_MACHINE_PWD_PASSED;
399
400         werr = libnet_Join(mem_ctx, r);
401         if (!W_ERROR_IS_OK(werr)) {
402                 goto fail;
403         }
404
405         /* Check the short name of the domain */
406
407         if (!modify_config && !strequal(lp_workgroup(), r->out.netbios_domain_name)) {
408                 d_printf("The workgroup in %s does not match the short\n", get_dyn_CONFIGFILE());
409                 d_printf("domain name obtained from the server.\n");
410                 d_printf("Using the name [%s] from the server.\n", r->out.netbios_domain_name);
411                 d_printf("You should set \"workgroup = %s\" in %s.\n",
412                          r->out.netbios_domain_name, get_dyn_CONFIGFILE());
413         }
414
415         d_printf("Using short domain name -- %s\n", r->out.netbios_domain_name);
416
417         if (r->out.dns_domain_name) {
418                 d_printf("Joined '%s' to realm '%s'\n", r->in.machine_name,
419                         r->out.dns_domain_name);
420         } else {
421                 d_printf("Joined '%s' to domain '%s'\n", r->in.machine_name,
422                         r->out.netbios_domain_name);
423         }
424
425         TALLOC_FREE(mem_ctx);
426
427         return 0;
428
429 fail:
430         if (c->opt_flags & NET_FLAGS_EXPECT_FALLBACK) {
431                 goto cleanup;
432         }
433
434         /* issue an overall failure message at the end. */
435         d_fprintf(stderr, _("Failed to join domain: %s\n"),
436                 r && r->out.error_string ? r->out.error_string :
437                 get_friendly_werror_msg(werr));
438
439 cleanup:
440         TALLOC_FREE(mem_ctx);
441
442         return -1;
443 }
444
445 /**
446  * check that a join is OK
447  *
448  * @return A shell status integer (0 for success)
449  *
450  **/
451 int net_rpc_testjoin(struct net_context *c, int argc, const char **argv)
452 {
453         NTSTATUS status;
454         TALLOC_CTX *mem_ctx;
455         const char *domain = c->opt_target_workgroup;
456         const char *dc = c->opt_host;
457
458         if (c->display_usage) {
459                 d_printf("Usage\n"
460                          "net rpc testjoin\n"
461                          "    Test if a join is OK\n");
462                 return 0;
463         }
464
465         mem_ctx = talloc_init("net_rpc_testjoin");
466         if (!mem_ctx) {
467                 return -1;
468         }
469
470         if (!dc) {
471                 struct netr_DsRGetDCNameInfo *info;
472
473                 if (!c->msg_ctx) {
474                         d_fprintf(stderr, _("Could not initialise message context. "
475                                 "Try running as root\n"));
476                         talloc_destroy(mem_ctx);
477                         return -1;
478                 }
479
480                 status = dsgetdcname(mem_ctx,
481                                      c->msg_ctx,
482                                      domain,
483                                      NULL,
484                                      NULL,
485                                      DS_RETURN_DNS_NAME,
486                                      &info);
487                 if (!NT_STATUS_IS_OK(status)) {
488                         talloc_destroy(mem_ctx);
489                         return -1;
490                 }
491
492                 dc = strip_hostname(info->dc_unc);
493         }
494
495         /* Display success or failure */
496         status = libnet_join_ok(c->opt_workgroup, lp_netbios_name(), dc,
497                                 c->opt_kerberos);
498         if (!NT_STATUS_IS_OK(status)) {
499                 fprintf(stderr,"Join to domain '%s' is not valid: %s\n",
500                         domain, nt_errstr(status));
501                 talloc_destroy(mem_ctx);
502                 return -1;
503         }
504
505         printf("Join to '%s' is OK\n",domain);
506         talloc_destroy(mem_ctx);
507
508         return 0;
509 }
510
511 /**
512  * Join a domain using the administrator username and password
513  *
514  * @param argc  Standard main() style argc
515  * @param argc  Standard main() style argv.  Initial components are already
516  *              stripped.  Currently not used.
517  * @return A shell status integer (0 for success)
518  *
519  **/
520
521 static int net_rpc_join_newstyle(struct net_context *c, int argc, const char **argv)
522 {
523         struct libnet_JoinCtx *r = NULL;
524         TALLOC_CTX *mem_ctx;
525         WERROR werr;
526         const char *domain = lp_workgroup(); /* FIXME */
527         bool modify_config = lp_config_backend_is_registry();
528         enum netr_SchannelType sec_chan_type;
529
530         if (c->display_usage) {
531                 d_printf("Usage:\n"
532                          "net rpc join\n"
533                          "    Join a domain the new way\n");
534                 return 0;
535         }
536
537         mem_ctx = talloc_init("net_rpc_join_newstyle");
538         if (!mem_ctx) {
539                 return -1;
540         }
541
542         werr = libnet_init_JoinCtx(mem_ctx, &r);
543         if (!W_ERROR_IS_OK(werr)) {
544                 goto fail;
545         }
546
547         /*
548            check what type of join - if the user want's to join as
549            a BDC, the server must agree that we are a BDC.
550         */
551         if (argc >= 0) {
552                 sec_chan_type = get_sec_channel_type(argv[0]);
553         } else {
554                 sec_chan_type = get_sec_channel_type(NULL);
555         }
556
557         if (!c->msg_ctx) {
558                 d_fprintf(stderr, _("Could not initialise message context. "
559                         "Try running as root\n"));
560                 werr = WERR_ACCESS_DENIED;
561                 goto fail;
562         }
563
564         r->in.msg_ctx                   = c->msg_ctx;
565         r->in.domain_name               = domain;
566         r->in.secure_channel_type       = sec_chan_type;
567         r->in.dc_name                   = c->opt_host;
568         r->in.admin_account             = c->opt_user_name;
569         r->in.admin_password            = net_prompt_pass(c, c->opt_user_name);
570         r->in.debug                     = true;
571         r->in.use_kerberos              = c->opt_kerberos;
572         r->in.modify_config             = modify_config;
573         r->in.join_flags                = WKSSVC_JOIN_FLAGS_JOIN_TYPE |
574                                           WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE |
575                                           WKSSVC_JOIN_FLAGS_DOMAIN_JOIN_IF_JOINED;
576
577         werr = libnet_Join(mem_ctx, r);
578         if (!W_ERROR_IS_OK(werr)) {
579                 goto fail;
580         }
581
582         /* Check the short name of the domain */
583
584         if (!modify_config && !strequal(lp_workgroup(), r->out.netbios_domain_name)) {
585                 d_printf("The workgroup in %s does not match the short\n", get_dyn_CONFIGFILE());
586                 d_printf("domain name obtained from the server.\n");
587                 d_printf("Using the name [%s] from the server.\n", r->out.netbios_domain_name);
588                 d_printf("You should set \"workgroup = %s\" in %s.\n",
589                          r->out.netbios_domain_name, get_dyn_CONFIGFILE());
590         }
591
592         d_printf("Using short domain name -- %s\n", r->out.netbios_domain_name);
593
594         if (r->out.dns_domain_name) {
595                 d_printf("Joined '%s' to realm '%s'\n", r->in.machine_name,
596                         r->out.dns_domain_name);
597         } else {
598                 d_printf("Joined '%s' to domain '%s'\n", r->in.machine_name,
599                         r->out.netbios_domain_name);
600         }
601
602         TALLOC_FREE(mem_ctx);
603
604         return 0;
605
606 fail:
607         /* issue an overall failure message at the end. */
608         d_printf("Failed to join domain: %s\n",
609                 r && r->out.error_string ? r->out.error_string :
610                 get_friendly_werror_msg(werr));
611
612         TALLOC_FREE(mem_ctx);
613
614         return -1;
615 }
616
617 /**
618  * 'net rpc join' entrypoint.
619  * @param argc  Standard main() style argc.
620  * @param argv  Standard main() style argv. Initial components are already
621  *              stripped
622  *
623  * Main 'net_rpc_join()' (where the admin username/password is used) is
624  * in net_rpc_join.c.
625  * Try to just change the password, but if that doesn't work, use/prompt
626  * for a username/password.
627  **/
628
629 int net_rpc_join(struct net_context *c, int argc, const char **argv)
630 {
631         int ret;
632
633         if (c->display_usage) {
634                 d_printf("%s\n%s",
635                          _("Usage:"),
636                          _("net rpc join -U <username>[%%password] <type>\n"
637                            "  Join a domain\n"
638                            "    username\tName of the admin user"
639                            "    password\tPassword of the admin user, will "
640                            "prompt if not specified\n"
641                            "    type\tCan be one of the following:\n"
642                            "\t\tMEMBER\tJoin as member server (default)\n"
643                            "\t\tBDC\tJoin as BDC\n"
644                            "\t\tPDC\tJoin as PDC\n"));
645                 return 0;
646         }
647
648         if (lp_server_role() == ROLE_STANDALONE) {
649                 d_printf(_("cannot join as standalone machine\n"));
650                 return -1;
651         }
652
653         if (strlen(lp_netbios_name()) > 15) {
654                 d_printf(_("Our netbios name can be at most 15 chars long, "
655                            "\"%s\" is %u chars long\n"),
656                          lp_netbios_name(), (unsigned int)strlen(lp_netbios_name()));
657                 return -1;
658         }
659
660         c->opt_flags |= NET_FLAGS_EXPECT_FALLBACK;
661         ret = net_rpc_oldjoin(c, argc, argv);
662         c->opt_flags &= ~NET_FLAGS_EXPECT_FALLBACK;
663         if (ret == 0) {
664                 return 0;
665         }
666
667         return net_rpc_join_newstyle(c, argc, argv);
668 }
669
670 /**
671  * display info about a rpc domain
672  *
673  * All parameters are provided by the run_rpc_command function, except for
674  * argc, argv which are passed through.
675  *
676  * @param domain_sid The domain sid acquired from the remote server
677  * @param cli A cli_state connected to the server.
678  * @param mem_ctx Talloc context, destroyed on completion of the function.
679  * @param argc  Standard main() style argc.
680  * @param argv  Standard main() style argv. Initial components are already
681  *              stripped.
682  *
683  * @return Normal NTSTATUS return.
684  **/
685
686 NTSTATUS rpc_info_internals(struct net_context *c,
687                         const struct dom_sid *domain_sid,
688                         const char *domain_name,
689                         struct cli_state *cli,
690                         struct rpc_pipe_client *pipe_hnd,
691                         TALLOC_CTX *mem_ctx,
692                         int argc,
693                         const char **argv)
694 {
695         struct policy_handle connect_pol, domain_pol;
696         NTSTATUS status, result;
697         union samr_DomainInfo *info = NULL;
698         fstring sid_str;
699         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
700
701         sid_to_fstring(sid_str, domain_sid);
702
703         /* Get sam policy handle */
704         status = dcerpc_samr_Connect2(b, mem_ctx,
705                                       pipe_hnd->desthost,
706                                       MAXIMUM_ALLOWED_ACCESS,
707                                       &connect_pol,
708                                       &result);
709         if (!NT_STATUS_IS_OK(status)) {
710                 d_fprintf(stderr, _("Could not connect to SAM: %s\n"),
711                           nt_errstr(status));
712                 goto done;
713         }
714
715         if (!NT_STATUS_IS_OK(result)) {
716                 status = result;
717                 d_fprintf(stderr, _("Could not connect to SAM: %s\n"),
718                           nt_errstr(result));
719                 goto done;
720         }
721
722         /* Get domain policy handle */
723         status = dcerpc_samr_OpenDomain(b, mem_ctx,
724                                         &connect_pol,
725                                         MAXIMUM_ALLOWED_ACCESS,
726                                         discard_const_p(struct dom_sid2, domain_sid),
727                                         &domain_pol,
728                                         &result);
729         if (!NT_STATUS_IS_OK(status)) {
730                 d_fprintf(stderr, _("Could not open domain: %s\n"),
731                           nt_errstr(status));
732                 goto done;
733         }
734         if (!NT_STATUS_IS_OK(result)) {
735                 status = result;
736                 d_fprintf(stderr, _("Could not open domain: %s\n"),
737                           nt_errstr(result));
738                 goto done;
739         }
740
741         status = dcerpc_samr_QueryDomainInfo(b, mem_ctx,
742                                              &domain_pol,
743                                              2,
744                                              &info,
745                                              &result);
746         if (!NT_STATUS_IS_OK(status)) {
747                 goto done;
748         }
749         status = result;
750         if (NT_STATUS_IS_OK(result)) {
751                 d_printf(_("Domain Name: %s\n"),
752                          info->general.domain_name.string);
753                 d_printf(_("Domain SID: %s\n"), sid_str);
754                 d_printf(_("Sequence number: %llu\n"),
755                         (unsigned long long)info->general.sequence_num);
756                 d_printf(_("Num users: %u\n"), info->general.num_users);
757                 d_printf(_("Num domain groups: %u\n"),info->general.num_groups);
758                 d_printf(_("Num local groups: %u\n"),info->general.num_aliases);
759         }
760
761  done:
762         return status;
763 }
764
765 /**
766  * 'net rpc info' entrypoint.
767  * @param argc  Standard main() style argc.
768  * @param argv  Standard main() style argv. Initial components are already
769  *              stripped.
770  **/
771
772 int net_rpc_info(struct net_context *c, int argc, const char **argv)
773 {
774         if (c->display_usage) {
775                 d_printf(  "%s\n"
776                            "net rpc info\n"
777                            "  %s\n",
778                          _("Usage:"),
779                          _("Display information about the domain"));
780                 return 0;
781         }
782
783         return run_rpc_command(c, NULL, &ndr_table_samr,
784                                NET_FLAGS_PDC, rpc_info_internals,
785                                argc, argv);
786 }
787
788 /**
789  * Fetch domain SID into the local secrets.tdb.
790  *
791  * All parameters are provided by the run_rpc_command function, except for
792  * argc, argv which are passed through.
793  *
794  * @param domain_sid The domain sid acquired from the remote server.
795  * @param cli A cli_state connected to the server.
796  * @param mem_ctx Talloc context, destroyed on completion of the function.
797  * @param argc  Standard main() style argc.
798  * @param argv  Standard main() style argv. Initial components are already
799  *              stripped.
800  *
801  * @return Normal NTSTATUS return.
802  **/
803
804 static NTSTATUS rpc_getsid_internals(struct net_context *c,
805                         const struct dom_sid *domain_sid,
806                         const char *domain_name,
807                         struct cli_state *cli,
808                         struct rpc_pipe_client *pipe_hnd,
809                         TALLOC_CTX *mem_ctx,
810                         int argc,
811                         const char **argv)
812 {
813         fstring sid_str;
814
815         sid_to_fstring(sid_str, domain_sid);
816         d_printf(_("Storing SID %s for Domain %s in secrets.tdb\n"),
817                  sid_str, domain_name);
818
819         if (!secrets_store_domain_sid(domain_name, domain_sid)) {
820                 DEBUG(0,("Can't store domain SID\n"));
821                 return NT_STATUS_UNSUCCESSFUL;
822         }
823
824         return NT_STATUS_OK;
825 }
826
827 /**
828  * 'net rpc getsid' entrypoint.
829  * @param argc  Standard main() style argc.
830  * @param argv  Standard main() style argv. Initial components are already
831  *              stripped.
832  **/
833
834 int net_rpc_getsid(struct net_context *c, int argc, const char **argv)
835 {
836         int conn_flags = NET_FLAGS_PDC;
837
838         if (!c->opt_user_specified) {
839                 conn_flags |= NET_FLAGS_ANONYMOUS;
840         }
841
842         if (c->display_usage) {
843                 d_printf(  "%s\n"
844                            "net rpc getsid\n"
845                            "    %s\n",
846                          _("Usage:"),
847                          _("Fetch domain SID into local secrets.tdb"));
848                 return 0;
849         }
850
851         return run_rpc_command(c, NULL, &ndr_table_samr,
852                                conn_flags,
853                                rpc_getsid_internals,
854                                argc, argv);
855 }
856
857 /****************************************************************************/
858
859 /**
860  * Basic usage function for 'net rpc user'.
861  * @param argc  Standard main() style argc.
862  * @param argv  Standard main() style argv. Initial components are already
863  *              stripped.
864  **/
865
866 static int rpc_user_usage(struct net_context *c, int argc, const char **argv)
867 {
868         return net_user_usage(c, argc, argv);
869 }
870
871 /**
872  * Add a new user to a remote RPC server.
873  *
874  * @param argc  Standard main() style argc.
875  * @param argv  Standard main() style argv. Initial components are already
876  *              stripped.
877  *
878  * @return A shell status integer (0 for success).
879  **/
880
881 static int rpc_user_add(struct net_context *c, int argc, const char **argv)
882 {
883         NET_API_STATUS status;
884         struct USER_INFO_1 info1;
885         uint32_t parm_error = 0;
886
887         if (argc < 1 || c->display_usage) {
888                 rpc_user_usage(c, argc, argv);
889                 return 0;
890         }
891
892         ZERO_STRUCT(info1);
893
894         info1.usri1_name = argv[0];
895         if (argc == 2) {
896                 info1.usri1_password = argv[1];
897         }
898
899         status = NetUserAdd(c->opt_host, 1, (uint8_t *)&info1, &parm_error);
900
901         if (status != 0) {
902                 d_fprintf(stderr,_("Failed to add user '%s' with error: %s.\n"),
903                         argv[0], libnetapi_get_error_string(c->netapi_ctx,
904                                                             status));
905                 return -1;
906         } else {
907                 d_printf(_("Added user '%s'.\n"), argv[0]);
908         }
909
910         return 0;
911 }
912
913 /**
914  * Rename a user on a remote RPC server.
915  *
916  * @param argc  Standard main() style argc.
917  * @param argv  Standard main() style argv. Initial components are already
918  *              stripped.
919  *
920  * @return A shell status integer (0 for success).
921  **/
922
923 static int rpc_user_rename(struct net_context *c, int argc, const char **argv)
924 {
925         NET_API_STATUS status;
926         struct USER_INFO_0 u0;
927         uint32_t parm_err = 0;
928
929         if (argc != 2 || c->display_usage) {
930                 rpc_user_usage(c, argc, argv);
931                 return 0;
932         }
933
934         u0.usri0_name = argv[1];
935
936         status = NetUserSetInfo(c->opt_host, argv[0],
937                                 0, (uint8_t *)&u0, &parm_err);
938         if (status) {
939                 d_fprintf(stderr,
940                           _("Failed to rename user from %s to %s - %s\n"),
941                           argv[0], argv[1],
942                           libnetapi_get_error_string(c->netapi_ctx, status));
943         } else {
944                 d_printf(_("Renamed user from %s to %s\n"), argv[0], argv[1]);
945         }
946
947         return status;
948 }
949
950 /**
951  * Set a user's primary group
952  *
953  * @param argc  Standard main() style argc.
954  * @param argv  Standard main() style argv. Initial components are already
955  *              stripped.
956  *
957  * @return A shell status integer (0 for success).
958  **/
959
960 static int rpc_user_setprimarygroup(struct net_context *c, int argc,
961                                     const char **argv)
962 {
963         NET_API_STATUS status;
964         uint8_t *buffer;
965         struct GROUP_INFO_2 *g2;
966         struct USER_INFO_1051 u1051;
967         uint32_t parm_err = 0;
968
969         if (argc != 2 || c->display_usage) {
970                 rpc_user_usage(c, argc, argv);
971                 return 0;
972         }
973
974         status = NetGroupGetInfo(c->opt_host, argv[1], 2, &buffer);
975         if (status) {
976                 d_fprintf(stderr, _("Failed to find group name %s -- %s\n"),
977                           argv[1],
978                           libnetapi_get_error_string(c->netapi_ctx, status));
979                 return status;
980         }
981         g2 = (struct GROUP_INFO_2 *)buffer;
982
983         u1051.usri1051_primary_group_id = g2->grpi2_group_id;
984
985         NetApiBufferFree(buffer);
986
987         status = NetUserSetInfo(c->opt_host, argv[0], 1051,
988                                 (uint8_t *)&u1051, &parm_err);
989         if (status) {
990                 d_fprintf(stderr,
991                           _("Failed to set user's primary group %s to %s - "
992                             "%s\n"), argv[0], argv[1],
993                           libnetapi_get_error_string(c->netapi_ctx, status));
994         } else {
995                 d_printf(_("Set primary group of user %s to %s\n"), argv[0],
996                          argv[1]);
997         }
998         return status;
999 }
1000
1001 /**
1002  * Delete a user from a remote RPC server.
1003  *
1004  * @param argc  Standard main() style argc.
1005  * @param argv  Standard main() style argv. Initial components are already
1006  *              stripped.
1007  *
1008  * @return A shell status integer (0 for success).
1009  **/
1010
1011 static int rpc_user_delete(struct net_context *c, int argc, const char **argv)
1012 {
1013         NET_API_STATUS status;
1014
1015         if (argc < 1 || c->display_usage) {
1016                 rpc_user_usage(c, argc, argv);
1017                 return 0;
1018         }
1019
1020         status = NetUserDel(c->opt_host, argv[0]);
1021
1022         if (status != 0) {
1023                 d_fprintf(stderr, _("Failed to delete user '%s' with: %s.\n"),
1024                           argv[0],
1025                           libnetapi_get_error_string(c->netapi_ctx, status));
1026                 return -1;
1027         } else {
1028                 d_printf(_("Deleted user '%s'.\n"), argv[0]);
1029         }
1030
1031         return 0;
1032 }
1033
1034 /**
1035  * Set a user's password on a remote RPC server.
1036  *
1037  * @param argc  Standard main() style argc.
1038  * @param argv  Standard main() style argv. Initial components are already
1039  *              stripped.
1040  *
1041  * @return A shell status integer (0 for success).
1042  **/
1043
1044 static int rpc_user_password(struct net_context *c, int argc, const char **argv)
1045 {
1046         NET_API_STATUS status;
1047         char *prompt = NULL;
1048         struct USER_INFO_1003 u1003;
1049         uint32_t parm_err = 0;
1050         int ret;
1051
1052         if (argc < 1 || c->display_usage) {
1053                 rpc_user_usage(c, argc, argv);
1054                 return 0;
1055         }
1056
1057         if (argv[1]) {
1058                 u1003.usri1003_password = argv[1];
1059         } else {
1060                 char pwd[256] = {0};
1061                 ret = asprintf(&prompt, _("Enter new password for %s:"),
1062                                argv[0]);
1063                 if (ret == -1) {
1064                         return -1;
1065                 }
1066
1067                 ret = samba_getpass(prompt, pwd, sizeof(pwd), false, false);
1068                 SAFE_FREE(prompt);
1069                 if (ret < 0) {
1070                         return -1;
1071                 }
1072
1073                 u1003.usri1003_password = talloc_strdup(c, pwd);
1074                 if (u1003.usri1003_password == NULL) {
1075                         return -1;
1076                 }
1077         }
1078
1079         status = NetUserSetInfo(c->opt_host, argv[0], 1003, (uint8_t *)&u1003, &parm_err);
1080
1081         /* Display results */
1082         if (status != 0) {
1083                 d_fprintf(stderr,
1084                         _("Failed to set password for '%s' with error: %s.\n"),
1085                         argv[0], libnetapi_get_error_string(c->netapi_ctx,
1086                                                             status));
1087                 return -1;
1088         }
1089
1090         return 0;
1091 }
1092
1093 /**
1094  * List a user's groups from a remote RPC server.
1095  *
1096  * @param argc  Standard main() style argc.
1097  * @param argv  Standard main() style argv. Initial components are already
1098  *              stripped.
1099  *
1100  * @return A shell status integer (0 for success)
1101  **/
1102
1103 static int rpc_user_info(struct net_context *c, int argc, const char **argv)
1104
1105 {
1106         NET_API_STATUS status;
1107         struct GROUP_USERS_INFO_0 *u0 = NULL;
1108         uint32_t entries_read = 0;
1109         uint32_t total_entries = 0;
1110         int i;
1111
1112
1113         if (argc < 1 || c->display_usage) {
1114                 rpc_user_usage(c, argc, argv);
1115                 return 0;
1116         }
1117
1118         status = NetUserGetGroups(c->opt_host,
1119                                   argv[0],
1120                                   0,
1121                                   (uint8_t **)(void *)&u0,
1122                                   (uint32_t)-1,
1123                                   &entries_read,
1124                                   &total_entries);
1125         if (status != 0) {
1126                 d_fprintf(stderr,
1127                         _("Failed to get groups for '%s' with error: %s.\n"),
1128                         argv[0], libnetapi_get_error_string(c->netapi_ctx,
1129                                                             status));
1130                 return -1;
1131         }
1132
1133         for (i=0; i < entries_read; i++) {
1134                 printf("%s\n", u0->grui0_name);
1135                 u0++;
1136         }
1137
1138         return 0;
1139 }
1140
1141 /**
1142  * List users on a remote RPC server.
1143  *
1144  * All parameters are provided by the run_rpc_command function, except for
1145  * argc, argv which are passed through.
1146  *
1147  * @param domain_sid The domain sid acquired from the remote server.
1148  * @param cli A cli_state connected to the server.
1149  * @param mem_ctx Talloc context, destroyed on completion of the function.
1150  * @param argc  Standard main() style argc.
1151  * @param argv  Standard main() style argv. Initial components are already
1152  *              stripped.
1153  *
1154  * @return Normal NTSTATUS return.
1155  **/
1156
1157 static int rpc_user_list(struct net_context *c, int argc, const char **argv)
1158 {
1159         NET_API_STATUS status;
1160         uint32_t start_idx=0, num_entries, i, loop_count = 0;
1161         struct NET_DISPLAY_USER *info = NULL;
1162         void *buffer = NULL;
1163
1164         /* Query domain users */
1165         if (c->opt_long_list_entries)
1166                 d_printf(_("\nUser name             Comment"
1167                            "\n-----------------------------\n"));
1168         do {
1169                 uint32_t max_entries, max_size;
1170
1171                 dcerpc_get_query_dispinfo_params(
1172                         loop_count, &max_entries, &max_size);
1173
1174                 status = NetQueryDisplayInformation(c->opt_host,
1175                                                     1,
1176                                                     start_idx,
1177                                                     max_entries,
1178                                                     max_size,
1179                                                     &num_entries,
1180                                                     &buffer);
1181                 if (status != 0 && status != ERROR_MORE_DATA) {
1182                         return status;
1183                 }
1184
1185                 info = (struct NET_DISPLAY_USER *)buffer;
1186
1187                 for (i = 0; i < num_entries; i++) {
1188
1189                         if (c->opt_long_list_entries)
1190                                 printf("%-21.21s %s\n", info->usri1_name,
1191                                         info->usri1_comment);
1192                         else
1193                                 printf("%s\n", info->usri1_name);
1194                         info++;
1195                 }
1196
1197                 NetApiBufferFree(buffer);
1198
1199                 loop_count++;
1200                 start_idx += num_entries;
1201
1202         } while (status == ERROR_MORE_DATA);
1203
1204         return status;
1205 }
1206
1207 /**
1208  * 'net rpc user' entrypoint.
1209  * @param argc  Standard main() style argc.
1210  * @param argv  Standard main() style argv. Initial components are already
1211  *              stripped.
1212  **/
1213
1214 int net_rpc_user(struct net_context *c, int argc, const char **argv)
1215 {
1216         NET_API_STATUS status;
1217
1218         struct functable func[] = {
1219                 {
1220                         "add",
1221                         rpc_user_add,
1222                         NET_TRANSPORT_RPC,
1223                         N_("Add specified user"),
1224                         N_("net rpc user add\n"
1225                            "    Add specified user")
1226                 },
1227                 {
1228                         "info",
1229                         rpc_user_info,
1230                         NET_TRANSPORT_RPC,
1231                         N_("List domain groups of user"),
1232                         N_("net rpc user info\n"
1233                            "    List domain groups of user")
1234                 },
1235                 {
1236                         "delete",
1237                         rpc_user_delete,
1238                         NET_TRANSPORT_RPC,
1239                         N_("Remove specified user"),
1240                         N_("net rpc user delete\n"
1241                            "    Remove specified user")
1242                 },
1243                 {
1244                         "password",
1245                         rpc_user_password,
1246                         NET_TRANSPORT_RPC,
1247                         N_("Change user password"),
1248                         N_("net rpc user password\n"
1249                            "    Change user password")
1250                 },
1251                 {
1252                         "rename",
1253                         rpc_user_rename,
1254                         NET_TRANSPORT_RPC,
1255                         N_("Rename specified user"),
1256                         N_("net rpc user rename\n"
1257                            "    Rename specified user")
1258                 },
1259                 {
1260                         "setprimarygroup",
1261                         rpc_user_setprimarygroup,
1262                         NET_TRANSPORT_RPC,
1263                         "Set a user's primary group",
1264                         "net rpc user setprimarygroup\n"
1265                         "    Set a user's primary group"
1266                 },
1267                 {NULL, NULL, 0, NULL, NULL}
1268         };
1269
1270         status = libnetapi_net_init(&c->netapi_ctx);
1271         if (status != 0) {
1272                 return -1;
1273         }
1274         libnetapi_set_username(c->netapi_ctx, c->opt_user_name);
1275         libnetapi_set_password(c->netapi_ctx, c->opt_password);
1276         if (c->opt_kerberos) {
1277                 libnetapi_set_use_kerberos(c->netapi_ctx);
1278         }
1279
1280         if (argc == 0) {
1281                 if (c->display_usage) {
1282                         d_printf(  "%s\n"
1283                                    "net rpc user\n"
1284                                    "    %s\n",
1285                                  _("Usage:"),
1286                                  _("List all users"));
1287                         net_display_usage_from_functable(func);
1288                         return 0;
1289                 }
1290
1291                 return rpc_user_list(c, argc, argv);
1292         }
1293
1294         return net_run_function(c, argc, argv, "net rpc user", func);
1295 }
1296
1297 static NTSTATUS rpc_sh_user_list(struct net_context *c,
1298                                  TALLOC_CTX *mem_ctx,
1299                                  struct rpc_sh_ctx *ctx,
1300                                  struct rpc_pipe_client *pipe_hnd,
1301                                  int argc, const char **argv)
1302 {
1303         return werror_to_ntstatus(W_ERROR(rpc_user_list(c, argc, argv)));
1304 }
1305
1306 static NTSTATUS rpc_sh_user_info(struct net_context *c,
1307                                  TALLOC_CTX *mem_ctx,
1308                                  struct rpc_sh_ctx *ctx,
1309                                  struct rpc_pipe_client *pipe_hnd,
1310                                  int argc, const char **argv)
1311 {
1312         return werror_to_ntstatus(W_ERROR(rpc_user_info(c, argc, argv)));
1313 }
1314
1315 static NTSTATUS rpc_sh_handle_user(struct net_context *c,
1316                                    TALLOC_CTX *mem_ctx,
1317                                    struct rpc_sh_ctx *ctx,
1318                                    struct rpc_pipe_client *pipe_hnd,
1319                                    int argc, const char **argv,
1320                                    NTSTATUS (*fn)(
1321                                            struct net_context *c,
1322                                            TALLOC_CTX *mem_ctx,
1323                                            struct rpc_sh_ctx *ctx,
1324                                            struct rpc_pipe_client *pipe_hnd,
1325                                            struct policy_handle *user_hnd,
1326                                            int argc, const char **argv))
1327 {
1328         struct policy_handle connect_pol, domain_pol, user_pol;
1329         NTSTATUS status, result;
1330         struct dom_sid sid;
1331         uint32 rid;
1332         enum lsa_SidType type;
1333         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
1334
1335         if (argc == 0) {
1336                 d_fprintf(stderr, "%s %s <username>\n", _("Usage:"),
1337                           ctx->whoami);
1338                 return NT_STATUS_INVALID_PARAMETER;
1339         }
1340
1341         ZERO_STRUCT(connect_pol);
1342         ZERO_STRUCT(domain_pol);
1343         ZERO_STRUCT(user_pol);
1344
1345         status = net_rpc_lookup_name(c, mem_ctx, rpc_pipe_np_smb_conn(pipe_hnd),
1346                                      argv[0], NULL, NULL, &sid, &type);
1347         if (!NT_STATUS_IS_OK(status)) {
1348                 d_fprintf(stderr, _("Could not lookup %s: %s\n"), argv[0],
1349                           nt_errstr(status));
1350                 goto done;
1351         }
1352
1353         if (type != SID_NAME_USER) {
1354                 d_fprintf(stderr, _("%s is a %s, not a user\n"), argv[0],
1355                           sid_type_lookup(type));
1356                 status = NT_STATUS_NO_SUCH_USER;
1357                 goto done;
1358         }
1359
1360         if (!sid_peek_check_rid(ctx->domain_sid, &sid, &rid)) {
1361                 d_fprintf(stderr, _("%s is not in our domain\n"), argv[0]);
1362                 status = NT_STATUS_NO_SUCH_USER;
1363                 goto done;
1364         }
1365
1366         status = dcerpc_samr_Connect2(b, mem_ctx,
1367                                       pipe_hnd->desthost,
1368                                       MAXIMUM_ALLOWED_ACCESS,
1369                                       &connect_pol,
1370                                       &result);
1371         if (!NT_STATUS_IS_OK(status)) {
1372                 goto done;
1373         }
1374         if (!NT_STATUS_IS_OK(result)) {
1375                 status = result;
1376                 goto done;
1377         }
1378
1379         status = dcerpc_samr_OpenDomain(b, mem_ctx,
1380                                         &connect_pol,
1381                                         MAXIMUM_ALLOWED_ACCESS,
1382                                         ctx->domain_sid,
1383                                         &domain_pol,
1384                                         &result);
1385         if (!NT_STATUS_IS_OK(status)) {
1386                 goto done;
1387         }
1388         if (!NT_STATUS_IS_OK(result)) {
1389                 status = result;
1390                 goto done;
1391         }
1392
1393         status = dcerpc_samr_OpenUser(b, mem_ctx,
1394                                       &domain_pol,
1395                                       MAXIMUM_ALLOWED_ACCESS,
1396                                       rid,
1397                                       &user_pol,
1398                                       &result);
1399         if (!NT_STATUS_IS_OK(status)) {
1400                 goto done;
1401         }
1402         if (!NT_STATUS_IS_OK(result)) {
1403                 status = result;
1404                 goto done;
1405         }
1406
1407         status = fn(c, mem_ctx, ctx, pipe_hnd, &user_pol, argc-1, argv+1);
1408
1409  done:
1410         if (is_valid_policy_hnd(&user_pol)) {
1411                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1412         }
1413         if (is_valid_policy_hnd(&domain_pol)) {
1414                 dcerpc_samr_Close(b, mem_ctx, &domain_pol, &result);
1415         }
1416         if (is_valid_policy_hnd(&connect_pol)) {
1417                 dcerpc_samr_Close(b, mem_ctx, &connect_pol, &result);
1418         }
1419         return status;
1420 }
1421
1422 static NTSTATUS rpc_sh_user_show_internals(struct net_context *c,
1423                                            TALLOC_CTX *mem_ctx,
1424                                            struct rpc_sh_ctx *ctx,
1425                                            struct rpc_pipe_client *pipe_hnd,
1426                                            struct policy_handle *user_hnd,
1427                                            int argc, const char **argv)
1428 {
1429         NTSTATUS status, result;
1430         union samr_UserInfo *info = NULL;
1431         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
1432
1433         if (argc != 0) {
1434                 d_fprintf(stderr, "%s %s show <username>\n", _("Usage:"),
1435                           ctx->whoami);
1436                 return NT_STATUS_INVALID_PARAMETER;
1437         }
1438
1439         status = dcerpc_samr_QueryUserInfo(b, mem_ctx,
1440                                            user_hnd,
1441                                            21,
1442                                            &info,
1443                                            &result);
1444         if (!NT_STATUS_IS_OK(status)) {
1445                 return status;
1446         }
1447         if (!NT_STATUS_IS_OK(result)) {
1448                 return result;
1449         }
1450
1451         d_printf(_("user rid: %d, group rid: %d\n"),
1452                 info->info21.rid,
1453                 info->info21.primary_gid);
1454
1455         return result;
1456 }
1457
1458 static NTSTATUS rpc_sh_user_show(struct net_context *c,
1459                                  TALLOC_CTX *mem_ctx,
1460                                  struct rpc_sh_ctx *ctx,
1461                                  struct rpc_pipe_client *pipe_hnd,
1462                                  int argc, const char **argv)
1463 {
1464         return rpc_sh_handle_user(c, mem_ctx, ctx, pipe_hnd, argc, argv,
1465                                   rpc_sh_user_show_internals);
1466 }
1467
1468 #define FETCHSTR(name, rec) \
1469 do { if (strequal(ctx->thiscmd, name)) { \
1470         oldval = talloc_strdup(mem_ctx, info->info21.rec.string); } \
1471 } while (0);
1472
1473 #define SETSTR(name, rec, flag) \
1474 do { if (strequal(ctx->thiscmd, name)) { \
1475         init_lsa_String(&(info->info21.rec), argv[0]); \
1476         info->info21.fields_present |= SAMR_FIELD_##flag; } \
1477 } while (0);
1478
1479 static NTSTATUS rpc_sh_user_str_edit_internals(struct net_context *c,
1480                                                TALLOC_CTX *mem_ctx,
1481                                                struct rpc_sh_ctx *ctx,
1482                                                struct rpc_pipe_client *pipe_hnd,
1483                                                struct policy_handle *user_hnd,
1484                                                int argc, const char **argv)
1485 {
1486         NTSTATUS status, result;
1487         const char *username;
1488         const char *oldval = "";
1489         union samr_UserInfo *info = NULL;
1490         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
1491
1492         if (argc > 1) {
1493                 d_fprintf(stderr, "%s %s <username> [new value|NULL]\n",
1494                           _("Usage:"), ctx->whoami);
1495                 return NT_STATUS_INVALID_PARAMETER;
1496         }
1497
1498         status = dcerpc_samr_QueryUserInfo(b, mem_ctx,
1499                                            user_hnd,
1500                                            21,
1501                                            &info,
1502                                            &result);
1503         if (!NT_STATUS_IS_OK(status)) {
1504                 return status;
1505         }
1506         if (!NT_STATUS_IS_OK(result)) {
1507                 return result;
1508         }
1509
1510         username = talloc_strdup(mem_ctx, info->info21.account_name.string);
1511
1512         FETCHSTR("fullname", full_name);
1513         FETCHSTR("homedir", home_directory);
1514         FETCHSTR("homedrive", home_drive);
1515         FETCHSTR("logonscript", logon_script);
1516         FETCHSTR("profilepath", profile_path);
1517         FETCHSTR("description", description);
1518
1519         if (argc == 0) {
1520                 d_printf(_("%s's %s: [%s]\n"), username, ctx->thiscmd, oldval);
1521                 goto done;
1522         }
1523
1524         if (strcmp(argv[0], "NULL") == 0) {
1525                 argv[0] = "";
1526         }
1527
1528         ZERO_STRUCT(info->info21);
1529
1530         SETSTR("fullname", full_name, FULL_NAME);
1531         SETSTR("homedir", home_directory, HOME_DIRECTORY);
1532         SETSTR("homedrive", home_drive, HOME_DRIVE);
1533         SETSTR("logonscript", logon_script, LOGON_SCRIPT);
1534         SETSTR("profilepath", profile_path, PROFILE_PATH);
1535         SETSTR("description", description, DESCRIPTION);
1536
1537         status = dcerpc_samr_SetUserInfo(b, mem_ctx,
1538                                          user_hnd,
1539                                          21,
1540                                          info,
1541                                          &result);
1542         if (!NT_STATUS_IS_OK(status)) {
1543                 return status;
1544         }
1545
1546         status = result;
1547
1548         d_printf(_("Set %s's %s from [%s] to [%s]\n"), username,
1549                  ctx->thiscmd, oldval, argv[0]);
1550
1551  done:
1552
1553         return status;
1554 }
1555
1556 #define HANDLEFLG(name, rec) \
1557 do { if (strequal(ctx->thiscmd, name)) { \
1558         oldval = (oldflags & ACB_##rec) ? "yes" : "no"; \
1559         if (newval) { \
1560                 newflags = oldflags | ACB_##rec; \
1561         } else { \
1562                 newflags = oldflags & ~ACB_##rec; \
1563         } } } while (0);
1564
1565 static NTSTATUS rpc_sh_user_str_edit(struct net_context *c,
1566                                      TALLOC_CTX *mem_ctx,
1567                                      struct rpc_sh_ctx *ctx,
1568                                      struct rpc_pipe_client *pipe_hnd,
1569                                      int argc, const char **argv)
1570 {
1571         return rpc_sh_handle_user(c, mem_ctx, ctx, pipe_hnd, argc, argv,
1572                                   rpc_sh_user_str_edit_internals);
1573 }
1574
1575 static NTSTATUS rpc_sh_user_flag_edit_internals(struct net_context *c,
1576                                                 TALLOC_CTX *mem_ctx,
1577                                                 struct rpc_sh_ctx *ctx,
1578                                                 struct rpc_pipe_client *pipe_hnd,
1579                                                 struct policy_handle *user_hnd,
1580                                                 int argc, const char **argv)
1581 {
1582         NTSTATUS status, result;
1583         const char *username;
1584         const char *oldval = "unknown";
1585         uint32 oldflags, newflags;
1586         bool newval;
1587         union samr_UserInfo *info = NULL;
1588         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
1589
1590         if ((argc > 1) ||
1591             ((argc == 1) && !strequal(argv[0], "yes") &&
1592              !strequal(argv[0], "no"))) {
1593                 /* TRANSATORS: The yes|no here are program keywords. Please do
1594                    not translate. */
1595                 d_fprintf(stderr, _("Usage: %s <username> [yes|no]\n"),
1596                           ctx->whoami);
1597                 return NT_STATUS_INVALID_PARAMETER;
1598         }
1599
1600         newval = strequal(argv[0], "yes");
1601
1602         status = dcerpc_samr_QueryUserInfo(b, mem_ctx,
1603                                            user_hnd,
1604                                            21,
1605                                            &info,
1606                                            &result);
1607         if (!NT_STATUS_IS_OK(status)) {
1608                 return status;
1609         }
1610         if (!NT_STATUS_IS_OK(result)) {
1611                 return result;
1612         }
1613
1614         username = talloc_strdup(mem_ctx, info->info21.account_name.string);
1615         oldflags = info->info21.acct_flags;
1616         newflags = info->info21.acct_flags;
1617
1618         HANDLEFLG("disabled", DISABLED);
1619         HANDLEFLG("pwnotreq", PWNOTREQ);
1620         HANDLEFLG("autolock", AUTOLOCK);
1621         HANDLEFLG("pwnoexp", PWNOEXP);
1622
1623         if (argc == 0) {
1624                 d_printf(_("%s's %s flag: %s\n"), username, ctx->thiscmd,
1625                          oldval);
1626                 goto done;
1627         }
1628
1629         ZERO_STRUCT(info->info21);
1630
1631         info->info21.acct_flags = newflags;
1632         info->info21.fields_present = SAMR_FIELD_ACCT_FLAGS;
1633
1634         status = dcerpc_samr_SetUserInfo(b, mem_ctx,
1635                                          user_hnd,
1636                                          21,
1637                                          info,
1638                                          &result);
1639         if (!NT_STATUS_IS_OK(status)) {
1640                 goto done;
1641         }
1642         status = result;
1643         if (NT_STATUS_IS_OK(result)) {
1644                 d_printf(_("Set %s's %s flag from [%s] to [%s]\n"), username,
1645                          ctx->thiscmd, oldval, argv[0]);
1646         }
1647
1648  done:
1649
1650         return status;
1651 }
1652
1653 static NTSTATUS rpc_sh_user_flag_edit(struct net_context *c,
1654                                       TALLOC_CTX *mem_ctx,
1655                                       struct rpc_sh_ctx *ctx,
1656                                       struct rpc_pipe_client *pipe_hnd,
1657                                       int argc, const char **argv)
1658 {
1659         return rpc_sh_handle_user(c, mem_ctx, ctx, pipe_hnd, argc, argv,
1660                                   rpc_sh_user_flag_edit_internals);
1661 }
1662
1663 struct rpc_sh_cmd *net_rpc_user_edit_cmds(struct net_context *c,
1664                                           TALLOC_CTX *mem_ctx,
1665                                           struct rpc_sh_ctx *ctx)
1666 {
1667         static struct rpc_sh_cmd cmds[] = {
1668
1669                 { "fullname", NULL, &ndr_table_samr, rpc_sh_user_str_edit,
1670                   N_("Show/Set a user's full name") },
1671
1672                 { "homedir", NULL, &ndr_table_samr, rpc_sh_user_str_edit,
1673                   N_("Show/Set a user's home directory") },
1674
1675                 { "homedrive", NULL, &ndr_table_samr, rpc_sh_user_str_edit,
1676                   N_("Show/Set a user's home drive") },
1677
1678                 { "logonscript", NULL, &ndr_table_samr, rpc_sh_user_str_edit,
1679                   N_("Show/Set a user's logon script") },
1680
1681                 { "profilepath", NULL, &ndr_table_samr, rpc_sh_user_str_edit,
1682                   N_("Show/Set a user's profile path") },
1683
1684                 { "description", NULL, &ndr_table_samr, rpc_sh_user_str_edit,
1685                   N_("Show/Set a user's description") },
1686
1687                 { "disabled", NULL, &ndr_table_samr, rpc_sh_user_flag_edit,
1688                   N_("Show/Set whether a user is disabled") },
1689
1690                 { "autolock", NULL, &ndr_table_samr, rpc_sh_user_flag_edit,
1691                   N_("Show/Set whether a user locked out") },
1692
1693                 { "pwnotreq", NULL, &ndr_table_samr, rpc_sh_user_flag_edit,
1694                   N_("Show/Set whether a user does not need a password") },
1695
1696                 { "pwnoexp", NULL, &ndr_table_samr, rpc_sh_user_flag_edit,
1697                   N_("Show/Set whether a user's password does not expire") },
1698
1699                 { NULL, NULL, 0, NULL, NULL }
1700         };
1701
1702         return cmds;
1703 }
1704
1705 struct rpc_sh_cmd *net_rpc_user_cmds(struct net_context *c,
1706                                      TALLOC_CTX *mem_ctx,
1707                                      struct rpc_sh_ctx *ctx)
1708 {
1709         static struct rpc_sh_cmd cmds[] = {
1710
1711                 { "list", NULL, &ndr_table_samr, rpc_sh_user_list,
1712                   N_("List available users") },
1713
1714                 { "info", NULL, &ndr_table_samr, rpc_sh_user_info,
1715                   N_("List the domain groups a user is member of") },
1716
1717                 { "show", NULL, &ndr_table_samr, rpc_sh_user_show,
1718                   N_("Show info about a user") },
1719
1720                 { "edit", net_rpc_user_edit_cmds, 0, NULL,
1721                   N_("Show/Modify a user's fields") },
1722
1723                 { NULL, NULL, 0, NULL, NULL }
1724         };
1725
1726         return cmds;
1727 }
1728
1729 /****************************************************************************/
1730
1731 /**
1732  * Basic usage function for 'net rpc group'.
1733  * @param argc  Standard main() style argc.
1734  * @param argv  Standard main() style argv. Initial components are already
1735  *              stripped.
1736  **/
1737
1738 static int rpc_group_usage(struct net_context *c, int argc, const char **argv)
1739 {
1740         return net_group_usage(c, argc, argv);
1741 }
1742
1743 /**
1744  * Delete group on a remote RPC server.
1745  *
1746  * All parameters are provided by the run_rpc_command function, except for
1747  * argc, argv which are passed through.
1748  *
1749  * @param domain_sid The domain sid acquired from the remote server.
1750  * @param cli A cli_state connected to the server.
1751  * @param mem_ctx Talloc context, destroyed on completion of the function.
1752  * @param argc  Standard main() style argc.
1753  * @param argv  Standard main() style argv. Initial components are already
1754  *              stripped.
1755  *
1756  * @return Normal NTSTATUS return.
1757  **/
1758
1759 static NTSTATUS rpc_group_delete_internals(struct net_context *c,
1760                                         const struct dom_sid *domain_sid,
1761                                         const char *domain_name,
1762                                         struct cli_state *cli,
1763                                         struct rpc_pipe_client *pipe_hnd,
1764                                         TALLOC_CTX *mem_ctx,
1765                                         int argc,
1766                                         const char **argv)
1767 {
1768         struct policy_handle connect_pol, domain_pol, group_pol, user_pol;
1769         bool group_is_primary = false;
1770         NTSTATUS status, result;
1771         uint32_t group_rid;
1772         struct samr_RidAttrArray *rids = NULL;
1773         /* char **names; */
1774         int i;
1775         /* struct samr_RidWithAttribute *user_gids; */
1776         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
1777
1778         struct samr_Ids group_rids, name_types;
1779         struct lsa_String lsa_acct_name;
1780         union samr_UserInfo *info = NULL;
1781
1782         if (argc < 1 || c->display_usage) {
1783                 rpc_group_usage(c, argc,argv);
1784                 return NT_STATUS_OK; /* ok? */
1785         }
1786
1787         status = dcerpc_samr_Connect2(b, mem_ctx,
1788                                       pipe_hnd->desthost,
1789                                       MAXIMUM_ALLOWED_ACCESS,
1790                                       &connect_pol,
1791                                       &result);
1792         if (!NT_STATUS_IS_OK(status)) {
1793                 d_fprintf(stderr, _("Request samr_Connect2 failed\n"));
1794                 goto done;
1795         }
1796
1797         if (!NT_STATUS_IS_OK(result)) {
1798                 status = result;
1799                 d_fprintf(stderr, _("Request samr_Connect2 failed\n"));
1800                 goto done;
1801         }
1802
1803         status = dcerpc_samr_OpenDomain(b, mem_ctx,
1804                                         &connect_pol,
1805                                         MAXIMUM_ALLOWED_ACCESS,
1806                                         discard_const_p(struct dom_sid2, domain_sid),
1807                                         &domain_pol,
1808                                         &result);
1809         if (!NT_STATUS_IS_OK(status)) {
1810                 d_fprintf(stderr, _("Request open_domain failed\n"));
1811                 goto done;
1812         }
1813
1814         if (!NT_STATUS_IS_OK(result)) {
1815                 status = result;
1816                 d_fprintf(stderr, _("Request open_domain failed\n"));
1817                 goto done;
1818         }
1819
1820         init_lsa_String(&lsa_acct_name, argv[0]);
1821
1822         status = dcerpc_samr_LookupNames(b, mem_ctx,
1823                                          &domain_pol,
1824                                          1,
1825                                          &lsa_acct_name,
1826                                          &group_rids,
1827                                          &name_types,
1828                                          &result);
1829         if (!NT_STATUS_IS_OK(status)) {
1830                 d_fprintf(stderr, _("Lookup of '%s' failed\n"),argv[0]);
1831                 goto done;
1832         }
1833
1834         if (!NT_STATUS_IS_OK(result)) {
1835                 status = result;
1836                 d_fprintf(stderr, _("Lookup of '%s' failed\n"),argv[0]);
1837                 goto done;
1838         }
1839
1840         switch (name_types.ids[0])
1841         {
1842         case SID_NAME_DOM_GRP:
1843                 status = dcerpc_samr_OpenGroup(b, mem_ctx,
1844                                                &domain_pol,
1845                                                MAXIMUM_ALLOWED_ACCESS,
1846                                                group_rids.ids[0],
1847                                                &group_pol,
1848                                                &result);
1849                 if (!NT_STATUS_IS_OK(status)) {
1850                         d_fprintf(stderr, _("Request open_group failed"));
1851                         goto done;
1852                 }
1853
1854                 if (!NT_STATUS_IS_OK(result)) {
1855                         status = result;
1856                         d_fprintf(stderr, _("Request open_group failed"));
1857                         goto done;
1858                 }
1859
1860                 group_rid = group_rids.ids[0];
1861
1862                 status = dcerpc_samr_QueryGroupMember(b, mem_ctx,
1863                                                       &group_pol,
1864                                                       &rids,
1865                                                       &result);
1866                 if (!NT_STATUS_IS_OK(status)) {
1867                         d_fprintf(stderr,
1868                                   _("Unable to query group members of %s"),
1869                                   argv[0]);
1870                         goto done;
1871                 }
1872
1873                 if (!NT_STATUS_IS_OK(result)) {
1874                         status = result;
1875                         d_fprintf(stderr,
1876                                   _("Unable to query group members of %s"),
1877                                   argv[0]);
1878                         goto done;
1879                 }
1880
1881                 if (c->opt_verbose) {
1882                         d_printf(
1883                                 _("Domain Group %s (rid: %d) has %d members\n"),
1884                                 argv[0],group_rid, rids->count);
1885                 }
1886
1887                 /* Check if group is anyone's primary group */
1888                 for (i = 0; i < rids->count; i++)
1889                 {
1890                         status = dcerpc_samr_OpenUser(b, mem_ctx,
1891                                                       &domain_pol,
1892                                                       MAXIMUM_ALLOWED_ACCESS,
1893                                                       rids->rids[i],
1894                                                       &user_pol,
1895                                                       &result);
1896                         if (!NT_STATUS_IS_OK(status)) {
1897                                 d_fprintf(stderr,
1898                                         _("Unable to open group member %d\n"),
1899                                         rids->rids[i]);
1900                                 goto done;
1901                         }
1902
1903                         if (!NT_STATUS_IS_OK(result)) {
1904                                 status = result;
1905                                 d_fprintf(stderr,
1906                                         _("Unable to open group member %d\n"),
1907                                         rids->rids[i]);
1908                                 goto done;
1909                         }
1910
1911                         status = dcerpc_samr_QueryUserInfo(b, mem_ctx,
1912                                                            &user_pol,
1913                                                            21,
1914                                                            &info,
1915                                                            &result);
1916                         if (!NT_STATUS_IS_OK(status)) {
1917                                 d_fprintf(stderr,
1918                                         _("Unable to lookup userinfo for group "
1919                                           "member %d\n"),
1920                                         rids->rids[i]);
1921                                 goto done;
1922                         }
1923
1924                         if (!NT_STATUS_IS_OK(result)) {
1925                                 status = result;
1926                                 d_fprintf(stderr,
1927                                         _("Unable to lookup userinfo for group "
1928                                           "member %d\n"),
1929                                         rids->rids[i]);
1930                                 goto done;
1931                         }
1932
1933                         if (info->info21.primary_gid == group_rid) {
1934                                 if (c->opt_verbose) {
1935                                         d_printf(_("Group is primary group "
1936                                                    "of %s\n"),
1937                                                 info->info21.account_name.string);
1938                                 }
1939                                 group_is_primary = true;
1940                         }
1941
1942                         dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1943                 }
1944
1945                 if (group_is_primary) {
1946                         d_fprintf(stderr, _("Unable to delete group because "
1947                                  "some of it's members have it as primary "
1948                                  "group\n"));
1949                         status = NT_STATUS_MEMBERS_PRIMARY_GROUP;
1950                         goto done;
1951                 }
1952
1953                 /* remove all group members */
1954                 for (i = 0; i < rids->count; i++)
1955                 {
1956                         if (c->opt_verbose)
1957                                 d_printf(_("Remove group member %d..."),
1958                                         rids->rids[i]);
1959                         status = dcerpc_samr_DeleteGroupMember(b, mem_ctx,
1960                                                                &group_pol,
1961                                                                rids->rids[i],
1962                                                                &result);
1963                         if (!NT_STATUS_IS_OK(status)) {
1964                                 goto done;
1965                         }
1966                         status = result;
1967                         if (NT_STATUS_IS_OK(result)) {
1968                                 if (c->opt_verbose)
1969                                         d_printf(_("ok\n"));
1970                         } else {
1971                                 if (c->opt_verbose)
1972                                         d_printf("%s\n", _("failed"));
1973                                 goto done;
1974                         }
1975                 }
1976
1977                 status = dcerpc_samr_DeleteDomainGroup(b, mem_ctx,
1978                                                        &group_pol,
1979                                                        &result);
1980                 if (!NT_STATUS_IS_OK(status)) {
1981                         break;
1982                 }
1983
1984                 status = result;
1985
1986                 break;
1987         /* removing a local group is easier... */
1988         case SID_NAME_ALIAS:
1989                 status = dcerpc_samr_OpenAlias(b, mem_ctx,
1990                                                &domain_pol,
1991                                                MAXIMUM_ALLOWED_ACCESS,
1992                                                group_rids.ids[0],
1993                                                &group_pol,
1994                                                &result);
1995                 if (!NT_STATUS_IS_OK(status)) {
1996                         d_fprintf(stderr, _("Request open_alias failed\n"));
1997                         goto done;
1998                 }
1999                 if (!NT_STATUS_IS_OK(result)) {
2000                         status = result;
2001                         d_fprintf(stderr, _("Request open_alias failed\n"));
2002                         goto done;
2003                 }
2004
2005                 status = dcerpc_samr_DeleteDomAlias(b, mem_ctx,
2006                                                     &group_pol,
2007                                                     &result);
2008                 if (!NT_STATUS_IS_OK(status)) {
2009                         break;
2010                 }
2011
2012                 status = result;
2013
2014                 break;
2015         default:
2016                 d_fprintf(stderr, _("%s is of type %s. This command is only "
2017                                     "for deleting local or global groups\n"),
2018                         argv[0],sid_type_lookup(name_types.ids[0]));
2019                 status = NT_STATUS_UNSUCCESSFUL;
2020                 goto done;
2021         }
2022
2023         if (NT_STATUS_IS_OK(status)) {
2024                 if (c->opt_verbose)
2025                         d_printf(_("Deleted %s '%s'\n"),
2026                                  sid_type_lookup(name_types.ids[0]), argv[0]);
2027         } else {
2028                 d_fprintf(stderr, _("Deleting of %s failed: %s\n"), argv[0],
2029                         get_friendly_nt_error_msg(status));
2030         }
2031
2032  done:
2033         return status;
2034
2035 }
2036
2037 static int rpc_group_delete(struct net_context *c, int argc, const char **argv)
2038 {
2039         return run_rpc_command(c, NULL, &ndr_table_samr, 0,
2040                                rpc_group_delete_internals, argc,argv);
2041 }
2042
2043 static int rpc_group_add_internals(struct net_context *c, int argc, const char **argv)
2044 {
2045         NET_API_STATUS status;
2046         struct GROUP_INFO_1 info1;
2047         uint32_t parm_error = 0;
2048
2049         if (argc != 1 || c->display_usage) {
2050                 rpc_group_usage(c, argc, argv);
2051                 return 0;
2052         }
2053
2054         ZERO_STRUCT(info1);
2055
2056         info1.grpi1_name = argv[0];
2057         if (c->opt_comment && strlen(c->opt_comment) > 0) {
2058                 info1.grpi1_comment = c->opt_comment;
2059         }
2060
2061         status = NetGroupAdd(c->opt_host, 1, (uint8_t *)&info1, &parm_error);
2062
2063         if (status != 0) {
2064                 d_fprintf(stderr,
2065                         _("Failed to add group '%s' with error: %s.\n"),
2066                         argv[0], libnetapi_get_error_string(c->netapi_ctx,
2067                                                             status));
2068                 return -1;
2069         } else {
2070                 d_printf(_("Added group '%s'.\n"), argv[0]);
2071         }
2072
2073         return 0;
2074 }
2075
2076 static int rpc_alias_add_internals(struct net_context *c, int argc, const char **argv)
2077 {
2078         NET_API_STATUS status;
2079         struct LOCALGROUP_INFO_1 info1;
2080         uint32_t parm_error = 0;
2081
2082         if (argc != 1 || c->display_usage) {
2083                 rpc_group_usage(c, argc, argv);
2084                 return 0;
2085         }
2086
2087         ZERO_STRUCT(info1);
2088
2089         info1.lgrpi1_name = argv[0];
2090         if (c->opt_comment && strlen(c->opt_comment) > 0) {
2091                 info1.lgrpi1_comment = c->opt_comment;
2092         }
2093
2094         status = NetLocalGroupAdd(c->opt_host, 1, (uint8_t *)&info1, &parm_error);
2095
2096         if (status != 0) {
2097                 d_fprintf(stderr,
2098                         _("Failed to add alias '%s' with error: %s.\n"),
2099                         argv[0], libnetapi_get_error_string(c->netapi_ctx,
2100                                                             status));
2101                 return -1;
2102         } else {
2103                 d_printf(_("Added alias '%s'.\n"), argv[0]);
2104         }
2105
2106         return 0;
2107 }
2108
2109 static int rpc_group_add(struct net_context *c, int argc, const char **argv)
2110 {
2111         if (c->opt_localgroup)
2112                 return rpc_alias_add_internals(c, argc, argv);
2113
2114         return rpc_group_add_internals(c, argc, argv);
2115 }
2116
2117 static NTSTATUS get_sid_from_name(struct cli_state *cli,
2118                                 TALLOC_CTX *mem_ctx,
2119                                 const char *name,
2120                                 struct dom_sid *sid,
2121                                 enum lsa_SidType *type)
2122 {
2123         struct dom_sid *sids = NULL;
2124         enum lsa_SidType *types = NULL;
2125         struct rpc_pipe_client *pipe_hnd = NULL;
2126         struct policy_handle lsa_pol;
2127         NTSTATUS status, result;
2128         struct dcerpc_binding_handle *b;
2129
2130         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
2131                                           &pipe_hnd);
2132         if (!NT_STATUS_IS_OK(status)) {
2133                 goto done;
2134         }
2135
2136         b = pipe_hnd->binding_handle;
2137
2138         status = rpccli_lsa_open_policy(pipe_hnd, mem_ctx, false,
2139                                      SEC_FLAG_MAXIMUM_ALLOWED, &lsa_pol);
2140
2141         if (!NT_STATUS_IS_OK(status)) {
2142                 goto done;
2143         }
2144
2145         status = rpccli_lsa_lookup_names(pipe_hnd, mem_ctx, &lsa_pol, 1,
2146                                       &name, NULL, 1, &sids, &types);
2147
2148         if (NT_STATUS_IS_OK(status)) {
2149                 sid_copy(sid, &sids[0]);
2150                 *type = types[0];
2151         }
2152
2153         dcerpc_lsa_Close(b, mem_ctx, &lsa_pol, &result);
2154
2155  done:
2156         if (pipe_hnd) {
2157                 TALLOC_FREE(pipe_hnd);
2158         }
2159
2160         if (!NT_STATUS_IS_OK(status) && (strncasecmp_m(name, "S-", 2) == 0)) {
2161
2162                 /* Try as S-1-5-whatever */
2163
2164                 struct dom_sid tmp_sid;
2165
2166                 if (string_to_sid(&tmp_sid, name)) {
2167                         sid_copy(sid, &tmp_sid);
2168                         *type = SID_NAME_UNKNOWN;
2169                         status = NT_STATUS_OK;
2170                 }
2171         }
2172
2173         return status;
2174 }
2175
2176 static NTSTATUS rpc_add_groupmem(struct rpc_pipe_client *pipe_hnd,
2177                                 TALLOC_CTX *mem_ctx,
2178                                 const struct dom_sid *group_sid,
2179                                 const char *member)
2180 {
2181         struct policy_handle connect_pol, domain_pol;
2182         NTSTATUS status, result;
2183         uint32 group_rid;
2184         struct policy_handle group_pol;
2185         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
2186
2187         struct samr_Ids rids, rid_types;
2188         struct lsa_String lsa_acct_name;
2189
2190         struct dom_sid sid;
2191
2192         sid_copy(&sid, group_sid);
2193
2194         if (!sid_split_rid(&sid, &group_rid)) {
2195                 return NT_STATUS_UNSUCCESSFUL;
2196         }
2197
2198         /* Get sam policy handle */
2199         status = dcerpc_samr_Connect2(b, mem_ctx,
2200                                       pipe_hnd->desthost,
2201                                       MAXIMUM_ALLOWED_ACCESS,
2202                                       &connect_pol,
2203                                       &result);
2204         if (!NT_STATUS_IS_OK(status)) {
2205                 return status;
2206         }
2207         if (!NT_STATUS_IS_OK(result)) {
2208                 return result;
2209         }
2210
2211         /* Get domain policy handle */
2212         status = dcerpc_samr_OpenDomain(b, mem_ctx,
2213                                         &connect_pol,
2214                                         MAXIMUM_ALLOWED_ACCESS,
2215                                         &sid,
2216                                         &domain_pol,
2217                                         &result);
2218         if (!NT_STATUS_IS_OK(status)) {
2219                 return status;
2220         }
2221         if (!NT_STATUS_IS_OK(result)) {
2222                 return result;
2223         }
2224
2225         init_lsa_String(&lsa_acct_name, member);
2226
2227         status = dcerpc_samr_LookupNames(b, mem_ctx,
2228                                          &domain_pol,
2229                                          1,
2230                                          &lsa_acct_name,
2231                                          &rids,
2232                                          &rid_types,
2233                                          &result);
2234         if (!NT_STATUS_IS_OK(status)) {
2235                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
2236                           member);
2237                 goto done;
2238         }
2239
2240         if (!NT_STATUS_IS_OK(result)) {
2241                 status = result;
2242                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
2243                           member);
2244                 goto done;
2245         }
2246
2247         status = dcerpc_samr_OpenGroup(b, mem_ctx,
2248                                        &domain_pol,
2249                                        MAXIMUM_ALLOWED_ACCESS,
2250                                        group_rid,
2251                                        &group_pol,
2252                                        &result);
2253         if (!NT_STATUS_IS_OK(status)) {
2254                 goto done;
2255         }
2256
2257         if (!NT_STATUS_IS_OK(result)) {
2258                 status = result;
2259                 goto done;
2260         }
2261
2262         status = dcerpc_samr_AddGroupMember(b, mem_ctx,
2263                                             &group_pol,
2264                                             rids.ids[0],
2265                                             0x0005, /* unknown flags */
2266                                             &result);
2267         if (!NT_STATUS_IS_OK(status)) {
2268                 goto done;
2269         }
2270
2271         status = result;
2272
2273  done:
2274         dcerpc_samr_Close(b, mem_ctx, &connect_pol, &result);
2275         return status;
2276 }
2277
2278 static NTSTATUS rpc_add_aliasmem(struct rpc_pipe_client *pipe_hnd,
2279                                 TALLOC_CTX *mem_ctx,
2280                                 const struct dom_sid *alias_sid,
2281                                 const char *member)
2282 {
2283         struct policy_handle connect_pol, domain_pol;
2284         NTSTATUS status, result;
2285         uint32 alias_rid;
2286         struct policy_handle alias_pol;
2287         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
2288
2289         struct dom_sid member_sid;
2290         enum lsa_SidType member_type;
2291
2292         struct dom_sid sid;
2293
2294         sid_copy(&sid, alias_sid);
2295
2296         if (!sid_split_rid(&sid, &alias_rid)) {
2297                 return NT_STATUS_UNSUCCESSFUL;
2298         }
2299
2300         result = get_sid_from_name(rpc_pipe_np_smb_conn(pipe_hnd), mem_ctx,
2301                                    member, &member_sid, &member_type);
2302
2303         if (!NT_STATUS_IS_OK(result)) {
2304                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
2305                           member);
2306                 return result;
2307         }
2308
2309         /* Get sam policy handle */
2310         status = dcerpc_samr_Connect2(b, mem_ctx,
2311                                       pipe_hnd->desthost,
2312                                       MAXIMUM_ALLOWED_ACCESS,
2313                                       &connect_pol,
2314                                       &result);
2315         if (!NT_STATUS_IS_OK(status)) {
2316                 goto done;
2317         }
2318         if (!NT_STATUS_IS_OK(result)) {
2319                 status = result;
2320                 goto done;
2321         }
2322
2323         /* Get domain policy handle */
2324         status = dcerpc_samr_OpenDomain(b, mem_ctx,
2325                                         &connect_pol,
2326                                         MAXIMUM_ALLOWED_ACCESS,
2327                                         &sid,
2328                                         &domain_pol,
2329                                         &result);
2330         if (!NT_STATUS_IS_OK(status)) {
2331                 goto done;
2332         }
2333         if (!NT_STATUS_IS_OK(result)) {
2334                 status = result;
2335                 goto done;
2336         }
2337
2338         status = dcerpc_samr_OpenAlias(b, mem_ctx,
2339                                        &domain_pol,
2340                                        MAXIMUM_ALLOWED_ACCESS,
2341                                        alias_rid,
2342                                        &alias_pol,
2343                                        &result);
2344         if (!NT_STATUS_IS_OK(status)) {
2345                 return status;
2346         }
2347         if (!NT_STATUS_IS_OK(result)) {
2348                 return result;
2349         }
2350
2351         status = dcerpc_samr_AddAliasMember(b, mem_ctx,
2352                                             &alias_pol,
2353                                             &member_sid,
2354                                             &result);
2355         if (!NT_STATUS_IS_OK(status)) {
2356                 return status;
2357         }
2358
2359         status = result;
2360
2361  done:
2362         dcerpc_samr_Close(b, mem_ctx, &connect_pol, &result);
2363         return status;
2364 }
2365
2366 static NTSTATUS rpc_group_addmem_internals(struct net_context *c,
2367                                         const struct dom_sid *domain_sid,
2368                                         const char *domain_name,
2369                                         struct cli_state *cli,
2370                                         struct rpc_pipe_client *pipe_hnd,
2371                                         TALLOC_CTX *mem_ctx,
2372                                         int argc,
2373                                         const char **argv)
2374 {
2375         struct dom_sid group_sid;
2376         enum lsa_SidType group_type;
2377
2378         if (argc != 2 || c->display_usage) {
2379                 d_printf("%s\n%s",
2380                          _("Usage:"),
2381                          _("net rpc group addmem <group> <member>\n"
2382                            "  Add a member to a group\n"
2383                            "    group\tGroup to add member to\n"
2384                            "    member\tMember to add to group\n"));
2385                 return NT_STATUS_UNSUCCESSFUL;
2386         }
2387
2388         if (!NT_STATUS_IS_OK(get_sid_from_name(cli, mem_ctx, argv[0],
2389                                                &group_sid, &group_type))) {
2390                 d_fprintf(stderr, _("Could not lookup group name %s\n"),
2391                           argv[0]);
2392                 return NT_STATUS_UNSUCCESSFUL;
2393         }
2394
2395         if (group_type == SID_NAME_DOM_GRP) {
2396                 NTSTATUS result = rpc_add_groupmem(pipe_hnd, mem_ctx,
2397                                                    &group_sid, argv[1]);
2398
2399                 if (!NT_STATUS_IS_OK(result)) {
2400                         d_fprintf(stderr, _("Could not add %s to %s: %s\n"),
2401                                  argv[1], argv[0], nt_errstr(result));
2402                 }
2403                 return result;
2404         }
2405
2406         if (group_type == SID_NAME_ALIAS) {
2407                 NTSTATUS result = rpc_add_aliasmem(pipe_hnd, mem_ctx,
2408                                                    &group_sid, argv[1]);
2409
2410                 if (!NT_STATUS_IS_OK(result)) {
2411                         d_fprintf(stderr, _("Could not add %s to %s: %s\n"),
2412                                  argv[1], argv[0], nt_errstr(result));
2413                 }
2414                 return result;
2415         }
2416
2417         d_fprintf(stderr, _("Can only add members to global or local groups "
2418                  "which %s is not\n"), argv[0]);
2419
2420         return NT_STATUS_UNSUCCESSFUL;
2421 }
2422
2423 static int rpc_group_addmem(struct net_context *c, int argc, const char **argv)
2424 {
2425         return run_rpc_command(c, NULL, &ndr_table_samr, 0,
2426                                rpc_group_addmem_internals,
2427                                argc, argv);
2428 }
2429
2430 static NTSTATUS rpc_del_groupmem(struct net_context *c,
2431                                 struct rpc_pipe_client *pipe_hnd,
2432                                 TALLOC_CTX *mem_ctx,
2433                                 const struct dom_sid *group_sid,
2434                                 const char *member)
2435 {
2436         struct policy_handle connect_pol, domain_pol;
2437         NTSTATUS status, result;
2438         uint32 group_rid;
2439         struct policy_handle group_pol;
2440         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
2441
2442         struct samr_Ids rids, rid_types;
2443         struct lsa_String lsa_acct_name;
2444
2445         struct dom_sid sid;
2446
2447         sid_copy(&sid, group_sid);
2448
2449         if (!sid_split_rid(&sid, &group_rid))
2450                 return NT_STATUS_UNSUCCESSFUL;
2451
2452         /* Get sam policy handle */
2453         status = dcerpc_samr_Connect2(b, mem_ctx,
2454                                       pipe_hnd->desthost,
2455                                       MAXIMUM_ALLOWED_ACCESS,
2456                                       &connect_pol,
2457                                       &result);
2458         if (!NT_STATUS_IS_OK(status)) {
2459                 return status;
2460         }
2461         if (!NT_STATUS_IS_OK(result)) {
2462                 return result;
2463         }
2464
2465
2466         /* Get domain policy handle */
2467         status = dcerpc_samr_OpenDomain(b, mem_ctx,
2468                                         &connect_pol,
2469                                         MAXIMUM_ALLOWED_ACCESS,
2470                                         &sid,
2471                                         &domain_pol,
2472                                         &result);
2473         if (!NT_STATUS_IS_OK(status)) {
2474                 return status;
2475         }
2476         if (!NT_STATUS_IS_OK(result)) {
2477                 return result;
2478         }
2479
2480         init_lsa_String(&lsa_acct_name, member);
2481
2482         status = dcerpc_samr_LookupNames(b, mem_ctx,
2483                                          &domain_pol,
2484                                          1,
2485                                          &lsa_acct_name,
2486                                          &rids,
2487                                          &rid_types,
2488                                          &result);
2489         if (!NT_STATUS_IS_OK(status)) {
2490                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
2491                           member);
2492                 goto done;
2493         }
2494
2495         if (!NT_STATUS_IS_OK(result)) {
2496                 status = result;
2497                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
2498                           member);
2499                 goto done;
2500         }
2501
2502         status = dcerpc_samr_OpenGroup(b, mem_ctx,
2503                                        &domain_pol,
2504                                        MAXIMUM_ALLOWED_ACCESS,
2505                                        group_rid,
2506                                        &group_pol,
2507                                        &result);
2508         if (!NT_STATUS_IS_OK(status)) {
2509                 goto done;
2510         }
2511         if (!NT_STATUS_IS_OK(result)) {
2512                 status = result;
2513                 goto done;
2514         }
2515
2516         status = dcerpc_samr_DeleteGroupMember(b, mem_ctx,
2517                                                &group_pol,
2518                                                rids.ids[0],
2519                                                &result);
2520         if (!NT_STATUS_IS_OK(status)) {
2521                 goto done;
2522         }
2523
2524         status = result;
2525  done:
2526         dcerpc_samr_Close(b, mem_ctx, &connect_pol, &result);
2527         return status;
2528 }
2529
2530 static NTSTATUS rpc_del_aliasmem(struct rpc_pipe_client *pipe_hnd,
2531                                 TALLOC_CTX *mem_ctx,
2532                                 const struct dom_sid *alias_sid,
2533                                 const char *member)
2534 {
2535         struct policy_handle connect_pol, domain_pol;
2536         NTSTATUS status, result;
2537         uint32 alias_rid;
2538         struct policy_handle alias_pol;
2539         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
2540
2541         struct dom_sid member_sid;
2542         enum lsa_SidType member_type;
2543
2544         struct dom_sid sid;
2545
2546         sid_copy(&sid, alias_sid);
2547
2548         if (!sid_split_rid(&sid, &alias_rid))
2549                 return NT_STATUS_UNSUCCESSFUL;
2550
2551         result = get_sid_from_name(rpc_pipe_np_smb_conn(pipe_hnd), mem_ctx,
2552                                    member, &member_sid, &member_type);
2553
2554         if (!NT_STATUS_IS_OK(result)) {
2555                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
2556                           member);
2557                 return result;
2558         }
2559
2560         /* Get sam policy handle */
2561         status = dcerpc_samr_Connect2(b, mem_ctx,
2562                                       pipe_hnd->desthost,
2563                                       MAXIMUM_ALLOWED_ACCESS,
2564                                       &connect_pol,
2565                                       &result);
2566         if (!NT_STATUS_IS_OK(status)) {
2567                 goto done;
2568         }
2569         if (!NT_STATUS_IS_OK(result)) {
2570                 status = result;
2571                 goto done;
2572         }
2573
2574         /* Get domain policy handle */
2575         status = dcerpc_samr_OpenDomain(b, mem_ctx,
2576                                         &connect_pol,
2577                                         MAXIMUM_ALLOWED_ACCESS,
2578                                         &sid,
2579                                         &domain_pol,
2580                                         &result);
2581         if (!NT_STATUS_IS_OK(status)) {
2582                 goto done;
2583         }
2584         if (!NT_STATUS_IS_OK(result)) {
2585                 status = result;
2586                 goto done;
2587         }
2588
2589         status = dcerpc_samr_OpenAlias(b, mem_ctx,
2590                                        &domain_pol,
2591                                        MAXIMUM_ALLOWED_ACCESS,
2592                                        alias_rid,
2593                                        &alias_pol,
2594                                        &result);
2595         if (!NT_STATUS_IS_OK(status)) {
2596                 return status;
2597         }
2598
2599         if (!NT_STATUS_IS_OK(result)) {
2600                 return result;
2601         }
2602
2603         status = dcerpc_samr_DeleteAliasMember(b, mem_ctx,
2604                                                &alias_pol,
2605                                                &member_sid,
2606                                                &result);
2607
2608         if (!NT_STATUS_IS_OK(status)) {
2609                 return status;
2610         }
2611
2612         status = result;
2613
2614  done:
2615         dcerpc_samr_Close(b, mem_ctx, &connect_pol, &result);
2616         return status;
2617 }
2618
2619 static NTSTATUS rpc_group_delmem_internals(struct net_context *c,
2620                                         const struct dom_sid *domain_sid,
2621                                         const char *domain_name,
2622                                         struct cli_state *cli,
2623                                         struct rpc_pipe_client *pipe_hnd,
2624                                         TALLOC_CTX *mem_ctx,
2625                                         int argc,
2626                                         const char **argv)
2627 {
2628         struct dom_sid group_sid;
2629         enum lsa_SidType group_type;
2630
2631         if (argc != 2 || c->display_usage) {
2632                 d_printf("%s\n%s",
2633                          _("Usage:"),
2634                          _("net rpc group delmem <group> <member>\n"
2635                            "  Delete a member from a group\n"
2636                            "    group\tGroup to delete member from\n"
2637                            "    member\tMember to delete from group\n"));
2638                 return NT_STATUS_UNSUCCESSFUL;
2639         }
2640
2641         if (!NT_STATUS_IS_OK(get_sid_from_name(cli, mem_ctx, argv[0],
2642                                                &group_sid, &group_type))) {
2643                 d_fprintf(stderr, _("Could not lookup group name %s\n"),
2644                           argv[0]);
2645                 return NT_STATUS_UNSUCCESSFUL;
2646         }
2647
2648         if (group_type == SID_NAME_DOM_GRP) {
2649                 NTSTATUS result = rpc_del_groupmem(c, pipe_hnd, mem_ctx,
2650                                                    &group_sid, argv[1]);
2651
2652                 if (!NT_STATUS_IS_OK(result)) {
2653                         d_fprintf(stderr, _("Could not del %s from %s: %s\n"),
2654                                  argv[1], argv[0], nt_errstr(result));
2655                 }
2656                 return result;
2657         }
2658
2659         if (group_type == SID_NAME_ALIAS) {
2660                 NTSTATUS result = rpc_del_aliasmem(pipe_hnd, mem_ctx,
2661                                                    &group_sid, argv[1]);
2662
2663                 if (!NT_STATUS_IS_OK(result)) {
2664                         d_fprintf(stderr, _("Could not del %s from %s: %s\n"),
2665                                  argv[1], argv[0], nt_errstr(result));
2666                 }
2667                 return result;
2668         }
2669
2670         d_fprintf(stderr, _("Can only delete members from global or local "
2671                  "groups which %s is not\n"), argv[0]);
2672
2673         return NT_STATUS_UNSUCCESSFUL;
2674 }
2675
2676 static int rpc_group_delmem(struct net_context *c, int argc, const char **argv)
2677 {
2678         return run_rpc_command(c, NULL, &ndr_table_samr, 0,
2679                                rpc_group_delmem_internals,
2680                                argc, argv);
2681 }
2682
2683 /**
2684  * List groups on a remote RPC server.
2685  *
2686  * All parameters are provided by the run_rpc_command function, except for
2687  * argc, argv which are passes through.
2688  *
2689  * @param domain_sid The domain sid acquired from the remote server.
2690  * @param cli A cli_state connected to the server.
2691  * @param mem_ctx Talloc context, destroyed on completion of the function.
2692  * @param argc  Standard main() style argc.
2693  * @param argv  Standard main() style argv. Initial components are already
2694  *              stripped.
2695  *
2696  * @return Normal NTSTATUS return.
2697  **/
2698
2699 static NTSTATUS rpc_group_list_internals(struct net_context *c,
2700                                         const struct dom_sid *domain_sid,
2701                                         const char *domain_name,
2702                                         struct cli_state *cli,
2703                                         struct rpc_pipe_client *pipe_hnd,
2704                                         TALLOC_CTX *mem_ctx,
2705                                         int argc,
2706                                         const char **argv)
2707 {
2708         struct policy_handle connect_pol, domain_pol;
2709         NTSTATUS status, result;
2710         uint32 start_idx=0, max_entries=250, num_entries, i, loop_count = 0;
2711         struct samr_SamArray *groups = NULL;
2712         bool global = false;
2713         bool local = false;
2714         bool builtin = false;
2715         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
2716
2717         if (c->display_usage) {
2718                 d_printf("%s\n%s",
2719                          _("Usage:"),
2720                          _("net rpc group list [global] [local] [builtin]\n"
2721                            "  List groups on RPC server\n"
2722                            "    global\tList global groups\n"
2723                            "    local\tList local groups\n"
2724                            "    builtin\tList builtin groups\n"
2725                            "    If none of global, local or builtin is "
2726                            "specified, all three options are considered "
2727                            "set\n"));
2728                 return NT_STATUS_OK;
2729         }
2730
2731         if (argc == 0) {
2732                 global = true;
2733                 local = true;
2734                 builtin = true;
2735         }
2736
2737         for (i=0; i<argc; i++) {
2738                 if (strequal(argv[i], "global"))
2739                         global = true;
2740
2741                 if (strequal(argv[i], "local"))
2742                         local = true;
2743
2744                 if (strequal(argv[i], "builtin"))
2745                         builtin = true;
2746         }
2747
2748         /* Get sam policy handle */
2749
2750         status = dcerpc_samr_Connect2(b, mem_ctx,
2751                                       pipe_hnd->desthost,
2752                                       MAXIMUM_ALLOWED_ACCESS,
2753                                       &connect_pol,
2754                                       &result);
2755         if (!NT_STATUS_IS_OK(status)) {
2756                 goto done;
2757         }
2758         if (!NT_STATUS_IS_OK(result)) {
2759                 status = result;
2760                 goto done;
2761         }
2762
2763         /* Get domain policy handle */
2764
2765         status = dcerpc_samr_OpenDomain(b, mem_ctx,
2766                                         &connect_pol,
2767                                         MAXIMUM_ALLOWED_ACCESS,
2768                                         discard_const_p(struct dom_sid2, domain_sid),
2769                                         &domain_pol,
2770                                         &result);
2771         if (!NT_STATUS_IS_OK(status)) {
2772                 goto done;
2773         }
2774         if (!NT_STATUS_IS_OK(result)) {
2775                 status = result;
2776                 goto done;
2777         }
2778
2779         /* Query domain groups */
2780         if (c->opt_long_list_entries)
2781                 d_printf(_("\nGroup name            Comment"
2782                            "\n-----------------------------\n"));
2783         do {
2784                 uint32_t max_size, total_size, returned_size;
2785                 union samr_DispInfo info;
2786
2787                 if (!global) break;
2788
2789                 dcerpc_get_query_dispinfo_params(
2790                         loop_count, &max_entries, &max_size);
2791
2792                 status = dcerpc_samr_QueryDisplayInfo(b, mem_ctx,
2793                                                       &domain_pol,
2794                                                       3,
2795                                                       start_idx,
2796                                                       max_entries,
2797                                                       max_size,
2798                                                       &total_size,
2799                                                       &returned_size,
2800                                                       &info,
2801                                                       &result);
2802                 if (!NT_STATUS_IS_OK(status)) {
2803                         goto done;
2804                 }
2805                 num_entries = info.info3.count;
2806                 start_idx += info.info3.count;
2807
2808                 if (!NT_STATUS_IS_OK(result) &&
2809                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES))
2810                         break;
2811
2812                 for (i = 0; i < num_entries; i++) {
2813
2814                         const char *group = NULL;
2815                         const char *desc = NULL;
2816
2817                         group = info.info3.entries[i].account_name.string;
2818                         desc = info.info3.entries[i].description.string;
2819
2820                         if (c->opt_long_list_entries)
2821                                 printf("%-21.21s %-50.50s\n",
2822                                        group, desc);
2823                         else
2824                                 printf("%s\n", group);
2825                 }
2826         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
2827         /* query domain aliases */
2828         start_idx = 0;
2829         do {
2830                 if (!local) break;
2831
2832                 status = dcerpc_samr_EnumDomainAliases(b, mem_ctx,
2833                                                        &domain_pol,
2834                                                        &start_idx,
2835                                                        &groups,
2836                                                        0xffff,
2837                                                        &num_entries,
2838                                                        &result);
2839                 if (!NT_STATUS_IS_OK(status)) {
2840                         goto done;
2841                 }
2842                 if (!NT_STATUS_IS_OK(result) &&
2843                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES))
2844                         break;
2845
2846                 for (i = 0; i < num_entries; i++) {
2847
2848                         const char *description = NULL;
2849
2850                         if (c->opt_long_list_entries) {
2851
2852                                 struct policy_handle alias_pol;
2853                                 union samr_AliasInfo *info = NULL;
2854                                 NTSTATUS _result;
2855
2856                                 status = dcerpc_samr_OpenAlias(b, mem_ctx,
2857                                                                &domain_pol,
2858                                                                0x8,
2859                                                                groups->entries[i].idx,
2860                                                                &alias_pol,
2861                                                                &_result);
2862                                 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(_result)) {
2863                                         status = dcerpc_samr_QueryAliasInfo(b, mem_ctx,
2864                                                                             &alias_pol,
2865                                                                             3,
2866                                                                             &info,
2867                                                                             &_result);
2868                                         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(_result)) {
2869                                                 status = dcerpc_samr_Close(b, mem_ctx,
2870                                                                            &alias_pol,
2871                                                                            &_result);
2872                                                 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(_result)) {
2873                                                         description = info->description.string;
2874                                                 }
2875                                         }
2876                                 }
2877                         }
2878
2879                         if (description != NULL) {
2880                                 printf("%-21.21s %-50.50s\n",
2881                                        groups->entries[i].name.string,
2882                                        description);
2883                         } else {
2884                                 printf("%s\n", groups->entries[i].name.string);
2885                         }
2886                 }
2887         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
2888         dcerpc_samr_Close(b, mem_ctx, &domain_pol, &result);
2889         /* Get builtin policy handle */
2890
2891         status = dcerpc_samr_OpenDomain(b, mem_ctx,
2892                                         &connect_pol,
2893                                         MAXIMUM_ALLOWED_ACCESS,
2894                                         discard_const_p(struct dom_sid2, &global_sid_Builtin),
2895                                         &domain_pol,
2896                                         &result);
2897         if (!NT_STATUS_IS_OK(status)) {
2898                 goto done;
2899         }
2900         if (!NT_STATUS_IS_OK(result)) {
2901                 status = result;
2902                 goto done;
2903         }
2904
2905         /* query builtin aliases */
2906         start_idx = 0;
2907         do {
2908                 if (!builtin) break;
2909
2910                 status = dcerpc_samr_EnumDomainAliases(b, mem_ctx,
2911                                                        &domain_pol,
2912                                                        &start_idx,
2913                                                        &groups,
2914                                                        max_entries,
2915                                                        &num_entries,
2916                                                        &result);
2917                 if (!NT_STATUS_IS_OK(status)) {
2918                         break;
2919                 }
2920                 if (!NT_STATUS_IS_OK(result) &&
2921                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES)) {
2922                         status = result;
2923                         break;
2924                 }
2925
2926                 for (i = 0; i < num_entries; i++) {
2927
2928                         const char *description = NULL;
2929
2930                         if (c->opt_long_list_entries) {
2931
2932                                 struct policy_handle alias_pol;
2933                                 union samr_AliasInfo *info = NULL;
2934                                 NTSTATUS _result;
2935
2936                                 status = dcerpc_samr_OpenAlias(b, mem_ctx,
2937                                                                &domain_pol,
2938                                                                0x8,
2939                                                                groups->entries[i].idx,
2940                                                                &alias_pol,
2941                                                                &_result);
2942                                 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(_result)) {
2943                                         status = dcerpc_samr_QueryAliasInfo(b, mem_ctx,
2944                                                                             &alias_pol,
2945                                                                             3,
2946                                                                             &info,
2947                                                                             &_result);
2948                                         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(_result)) {
2949                                                 status = dcerpc_samr_Close(b, mem_ctx,
2950                                                                            &alias_pol,
2951                                                                            &_result);
2952                                                 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(_result)) {
2953                                                         description = info->description.string;
2954                                                 }
2955                                         }
2956                                 }
2957                         }
2958
2959                         if (description != NULL) {
2960                                 printf("%-21.21s %-50.50s\n",
2961                                        groups->entries[i].name.string,
2962                                        description);
2963                         } else {
2964                                 printf("%s\n", groups->entries[i].name.string);
2965                         }
2966                 }
2967         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
2968
2969         status = result;
2970
2971  done:
2972         return status;
2973 }
2974
2975 static int rpc_group_list(struct net_context *c, int argc, const char **argv)
2976 {
2977         return run_rpc_command(c, NULL, &ndr_table_samr, 0,
2978                                rpc_group_list_internals,
2979                                argc, argv);
2980 }
2981
2982 static NTSTATUS rpc_list_group_members(struct net_context *c,
2983                                         struct rpc_pipe_client *pipe_hnd,
2984                                         TALLOC_CTX *mem_ctx,
2985                                         const char *domain_name,
2986                                         const struct dom_sid *domain_sid,
2987                                         struct policy_handle *domain_pol,
2988                                         uint32 rid)
2989 {
2990         NTSTATUS result, status;
2991         struct policy_handle group_pol;
2992         uint32 num_members, *group_rids;
2993         int i;
2994         struct samr_RidAttrArray *rids = NULL;
2995         struct lsa_Strings names;
2996         struct samr_Ids types;
2997         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
2998
2999         fstring sid_str;
3000         sid_to_fstring(sid_str, domain_sid);
3001
3002         status = dcerpc_samr_OpenGroup(b, mem_ctx,
3003                                        domain_pol,
3004                                        MAXIMUM_ALLOWED_ACCESS,
3005                                        rid,
3006                                        &group_pol,
3007                                        &result);
3008         if (!NT_STATUS_IS_OK(status)) {
3009                 return status;
3010         }
3011         if (!NT_STATUS_IS_OK(result)) {
3012                 return result;
3013         }
3014
3015         status = dcerpc_samr_QueryGroupMember(b, mem_ctx,
3016                                               &group_pol,
3017                                               &rids,
3018                                               &result);
3019         if (!NT_STATUS_IS_OK(status)) {
3020                 return status;
3021         }
3022         if (!NT_STATUS_IS_OK(result)) {
3023                 return result;
3024         }
3025
3026         num_members = rids->count;
3027         group_rids = rids->rids;
3028
3029         while (num_members > 0) {
3030                 int this_time = 512;
3031
3032                 if (num_members < this_time)
3033                         this_time = num_members;
3034
3035                 status = dcerpc_samr_LookupRids(b, mem_ctx,
3036                                                 domain_pol,
3037                                                 this_time,
3038                                                 group_rids,
3039                                                 &names,
3040                                                 &types,
3041                                                 &result);
3042                 if (!NT_STATUS_IS_OK(status)) {
3043                         return status;
3044                 }
3045                 if (!NT_STATUS_IS_OK(result)) {
3046                         return result;
3047                 }
3048
3049                 /* We only have users as members, but make the output
3050                    the same as the output of alias members */
3051
3052                 for (i = 0; i < this_time; i++) {
3053
3054                         if (c->opt_long_list_entries) {
3055                                 printf("%s-%d %s\\%s %d\n", sid_str,
3056                                        group_rids[i], domain_name,
3057                                        names.names[i].string,
3058                                        SID_NAME_USER);
3059                         } else {
3060                                 printf("%s\\%s\n", domain_name,
3061                                         names.names[i].string);
3062                         }
3063                 }
3064
3065                 num_members -= this_time;
3066                 group_rids += 512;
3067         }
3068
3069         return NT_STATUS_OK;
3070 }
3071
3072 static NTSTATUS rpc_list_alias_members(struct net_context *c,
3073                                         struct rpc_pipe_client *pipe_hnd,
3074                                         TALLOC_CTX *mem_ctx,
3075                                         struct policy_handle *domain_pol,
3076                                         uint32 rid)
3077 {
3078         NTSTATUS result, status;
3079         struct rpc_pipe_client *lsa_pipe;
3080         struct policy_handle alias_pol, lsa_pol;
3081         uint32 num_members;
3082         struct dom_sid *alias_sids;
3083         char **domains;
3084         char **names;
3085         enum lsa_SidType *types;
3086         int i;
3087         struct lsa_SidArray sid_array;
3088         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
3089
3090         status = dcerpc_samr_OpenAlias(b, mem_ctx,
3091                                        domain_pol,
3092                                        MAXIMUM_ALLOWED_ACCESS,
3093                                        rid,
3094                                        &alias_pol,
3095                                        &result);
3096         if (!NT_STATUS_IS_OK(status)) {
3097                 return status;
3098         }
3099         if (!NT_STATUS_IS_OK(result)) {
3100                 return result;
3101         }
3102
3103         status = dcerpc_samr_GetMembersInAlias(b, mem_ctx,
3104                                                &alias_pol,
3105                                                &sid_array,
3106                                                &result);
3107         if (!NT_STATUS_IS_OK(status)) {
3108                 d_fprintf(stderr, _("Couldn't list alias members\n"));
3109                 return status;
3110         }
3111         if (!NT_STATUS_IS_OK(result)) {
3112                 d_fprintf(stderr, _("Couldn't list alias members\n"));
3113                 return result;
3114         }
3115
3116         num_members = sid_array.num_sids;
3117
3118         if (num_members == 0) {
3119                 return NT_STATUS_OK;
3120         }
3121
3122         result = cli_rpc_pipe_open_noauth(rpc_pipe_np_smb_conn(pipe_hnd),
3123                                           &ndr_table_lsarpc,
3124                                           &lsa_pipe);
3125         if (!NT_STATUS_IS_OK(result)) {
3126                 d_fprintf(stderr, _("Couldn't open LSA pipe. Error was %s\n"),
3127                         nt_errstr(result) );
3128                 return result;
3129         }
3130
3131         result = rpccli_lsa_open_policy(lsa_pipe, mem_ctx, true,
3132                                      SEC_FLAG_MAXIMUM_ALLOWED, &lsa_pol);
3133
3134         if (!NT_STATUS_IS_OK(result)) {
3135                 d_fprintf(stderr, _("Couldn't open LSA policy handle\n"));
3136                 TALLOC_FREE(lsa_pipe);
3137                 return result;
3138         }
3139
3140         alias_sids = talloc_zero_array(mem_ctx, struct dom_sid, num_members);
3141         if (!alias_sids) {
3142                 d_fprintf(stderr, _("Out of memory\n"));
3143                 TALLOC_FREE(lsa_pipe);
3144                 return NT_STATUS_NO_MEMORY;
3145         }
3146
3147         for (i=0; i<num_members; i++) {
3148                 sid_copy(&alias_sids[i], sid_array.sids[i].sid);
3149         }
3150
3151         result = rpccli_lsa_lookup_sids(lsa_pipe, mem_ctx, &lsa_pol,
3152                                      num_members,  alias_sids,
3153                                      &domains, &names, &types);
3154
3155         if (!NT_STATUS_IS_OK(result) &&
3156             !NT_STATUS_EQUAL(result, STATUS_SOME_UNMAPPED)) {
3157                 d_fprintf(stderr, _("Couldn't lookup SIDs\n"));
3158                 TALLOC_FREE(lsa_pipe);
3159                 return result;
3160         }
3161
3162         for (i = 0; i < num_members; i++) {
3163                 fstring sid_str;
3164                 sid_to_fstring(sid_str, &alias_sids[i]);
3165
3166                 if (c->opt_long_list_entries) {
3167                         printf("%s %s\\%s %d\n", sid_str,
3168                                domains[i] ? domains[i] : _("*unknown*"),
3169                                names[i] ? names[i] : _("*unknown*"), types[i]);
3170                 } else {
3171                         if (domains[i])
3172                                 printf("%s\\%s\n", domains[i], names[i]);
3173                         else
3174                                 printf("%s\n", sid_str);
3175                 }
3176         }
3177
3178         TALLOC_FREE(lsa_pipe);
3179         return NT_STATUS_OK;
3180 }
3181
3182 static NTSTATUS rpc_group_members_internals(struct net_context *c,
3183                                         const struct dom_sid *domain_sid,
3184                                         const char *domain_name,
3185                                         struct cli_state *cli,
3186                                         struct rpc_pipe_client *pipe_hnd,
3187                                         TALLOC_CTX *mem_ctx,
3188                                         int argc,
3189                                         const char **argv)
3190 {
3191         NTSTATUS result, status;
3192         struct policy_handle connect_pol, domain_pol;
3193         struct samr_Ids rids, rid_types;
3194         struct lsa_String lsa_acct_name;
3195         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
3196
3197         /* Get sam policy handle */
3198
3199         status = dcerpc_samr_Connect2(b, mem_ctx,
3200                                       pipe_hnd->desthost,
3201                                       MAXIMUM_ALLOWED_ACCESS,
3202                                       &connect_pol,
3203                                       &result);
3204         if (!NT_STATUS_IS_OK(status)) {
3205                 return status;
3206         }
3207         if (!NT_STATUS_IS_OK(result)) {
3208                 return result;
3209         }
3210
3211         /* Get domain policy handle */
3212
3213         status = dcerpc_samr_OpenDomain(b, mem_ctx,
3214                                         &connect_pol,
3215                                         MAXIMUM_ALLOWED_ACCESS,
3216                                         discard_const_p(struct dom_sid2, domain_sid),
3217                                         &domain_pol,
3218                                         &result);
3219         if (!NT_STATUS_IS_OK(status)) {
3220                 return status;
3221         }
3222         if (!NT_STATUS_IS_OK(result)) {
3223                 return result;
3224         }
3225
3226         init_lsa_String(&lsa_acct_name, argv[0]); /* sure? */
3227
3228         status = dcerpc_samr_LookupNames(b, mem_ctx,
3229                                          &domain_pol,
3230                                          1,
3231                                          &lsa_acct_name,
3232                                          &rids,
3233                                          &rid_types,
3234                                          &result);
3235         if (!NT_STATUS_IS_OK(status)) {
3236                 return status;
3237         }
3238
3239         if (!NT_STATUS_IS_OK(result)) {
3240
3241                 /* Ok, did not find it in the global sam, try with builtin */
3242
3243                 struct dom_sid sid_Builtin;
3244
3245                 dcerpc_samr_Close(b, mem_ctx, &domain_pol, &result);
3246
3247                 sid_copy(&sid_Builtin, &global_sid_Builtin);
3248
3249                 status = dcerpc_samr_OpenDomain(b, mem_ctx,
3250                                                 &connect_pol,
3251                                                 MAXIMUM_ALLOWED_ACCESS,
3252                                                 &sid_Builtin,
3253                                                 &domain_pol,
3254                                                 &result);
3255                 if (!NT_STATUS_IS_OK(status)) {
3256                         return status;
3257                 }
3258                 if (!NT_STATUS_IS_OK(result)) {
3259                         d_fprintf(stderr, _("Couldn't find group %s\n"),
3260                                   argv[0]);
3261                         return result;
3262                 }
3263
3264                 status = dcerpc_samr_LookupNames(b, mem_ctx,
3265                                                  &domain_pol,
3266                                                  1,
3267                                                  &lsa_acct_name,
3268                                                  &rids,
3269                                                  &rid_types,
3270                                                  &result);
3271                 if (!NT_STATUS_IS_OK(status)) {
3272                         return status;
3273                 }
3274                 if (!NT_STATUS_IS_OK(result)) {
3275                         d_fprintf(stderr, _("Couldn't find group %s\n"),
3276                                   argv[0]);
3277                         return result;
3278                 }
3279         }
3280
3281         if (rids.count != 1) {
3282                 d_fprintf(stderr, _("Couldn't find group %s\n"),
3283                           argv[0]);
3284                 return result;
3285         }
3286
3287         if (rid_types.ids[0] == SID_NAME_DOM_GRP) {
3288                 return rpc_list_group_members(c, pipe_hnd, mem_ctx, domain_name,
3289                                               domain_sid, &domain_pol,
3290                                               rids.ids[0]);
3291         }
3292
3293         if (rid_types.ids[0] == SID_NAME_ALIAS) {
3294                 return rpc_list_alias_members(c, pipe_hnd, mem_ctx, &domain_pol,
3295                                               rids.ids[0]);
3296         }
3297
3298         return NT_STATUS_NO_SUCH_GROUP;
3299 }
3300
3301 static int rpc_group_members(struct net_context *c, int argc, const char **argv)
3302 {
3303         if (argc != 1 || c->display_usage) {
3304                 return rpc_group_usage(c, argc, argv);
3305         }
3306
3307         return run_rpc_command(c, NULL, &ndr_table_samr, 0,
3308                                rpc_group_members_internals,
3309                                argc, argv);
3310 }
3311
3312 static int rpc_group_rename_internals(struct net_context *c, int argc, const char **argv)
3313 {
3314         NET_API_STATUS status;
3315         struct GROUP_INFO_0 g0;
3316         uint32_t parm_err;
3317
3318         if (argc != 2) {
3319                 d_printf(_("Usage:\n"));
3320                 d_printf("net rpc group rename group newname\n");
3321                 return -1;
3322         }
3323
3324         g0.grpi0_name = argv[1];
3325
3326         status = NetGroupSetInfo(c->opt_host,
3327                                  argv[0],
3328                                  0,
3329                                  (uint8_t *)&g0,
3330                                  &parm_err);
3331
3332         if (status != 0) {
3333                 d_fprintf(stderr, _("Renaming group %s failed with: %s\n"),
3334                         argv[0], libnetapi_get_error_string(c->netapi_ctx,
3335                         status));
3336                 return -1;
3337         }
3338
3339         return 0;
3340 }
3341
3342 static int rpc_group_rename(struct net_context *c, int argc, const char **argv)
3343 {
3344         if (argc != 2 || c->display_usage) {
3345                 return rpc_group_usage(c, argc, argv);
3346         }
3347
3348         return rpc_group_rename_internals(c, argc, argv);
3349 }
3350
3351 /**
3352  * 'net rpc group' entrypoint.
3353  * @param argc  Standard main() style argc.
3354  * @param argv  Standard main() style argv. Initial components are already
3355  *              stripped.
3356  **/
3357
3358 int net_rpc_group(struct net_context *c, int argc, const char **argv)
3359 {
3360         NET_API_STATUS status;
3361
3362         struct functable func[] = {
3363                 {
3364                         "add",
3365                         rpc_group_add,
3366                         NET_TRANSPORT_RPC,
3367                         N_("Create specified group"),
3368                         N_("net rpc group add\n"
3369                            "    Create specified group")
3370                 },
3371                 {
3372                         "delete",
3373                         rpc_group_delete,
3374                         NET_TRANSPORT_RPC,
3375                         N_("Delete specified group"),
3376                         N_("net rpc group delete\n"
3377                            "    Delete specified group")
3378                 },
3379                 {
3380                         "addmem",
3381                         rpc_group_addmem,
3382                         NET_TRANSPORT_RPC,
3383                         N_("Add member to group"),
3384                         N_("net rpc group addmem\n"
3385                            "    Add member to group")
3386                 },
3387                 {
3388                         "delmem",
3389                         rpc_group_delmem,
3390                         NET_TRANSPORT_RPC,
3391                         N_("Remove member from group"),
3392                         N_("net rpc group delmem\n"
3393                            "    Remove member from group")
3394                 },
3395                 {
3396                         "list",
3397                         rpc_group_list,
3398                         NET_TRANSPORT_RPC,
3399                         N_("List groups"),
3400                         N_("net rpc group list\n"
3401                            "    List groups")
3402                 },
3403                 {
3404                         "members",
3405                         rpc_group_members,
3406                         NET_TRANSPORT_RPC,
3407                         N_("List group members"),
3408                         N_("net rpc group members\n"
3409                            "    List group members")
3410                 },
3411                 {
3412                         "rename",
3413                         rpc_group_rename,
3414                         NET_TRANSPORT_RPC,
3415                         N_("Rename group"),
3416                         N_("net rpc group rename\n"
3417                            "    Rename group")
3418                 },
3419                 {NULL, NULL, 0, NULL, NULL}
3420         };
3421
3422         status = libnetapi_net_init(&c->netapi_ctx);
3423         if (status != 0) {
3424                 return -1;
3425         }
3426         libnetapi_set_username(c->netapi_ctx, c->opt_user_name);
3427         libnetapi_set_password(c->netapi_ctx, c->opt_password);
3428         if (c->opt_kerberos) {
3429                 libnetapi_set_use_kerberos(c->netapi_ctx);
3430         }
3431
3432         if (argc == 0) {
3433                 if (c->display_usage) {
3434                         d_printf(_("Usage:\n"));
3435                         d_printf(_("net rpc group\n"
3436                                    "    Alias for net rpc group list global "
3437                                    "local builtin\n"));
3438                         net_display_usage_from_functable(func);
3439                         return 0;
3440                 }
3441
3442                 return run_rpc_command(c, NULL, &ndr_table_samr, 0,
3443                                        rpc_group_list_internals,
3444                                        argc, argv);
3445         }
3446
3447         return net_run_function(c, argc, argv, "net rpc group", func);
3448 }
3449
3450 /****************************************************************************/
3451
3452 static int rpc_share_usage(struct net_context *c, int argc, const char **argv)
3453 {
3454         return net_share_usage(c, argc, argv);
3455 }
3456
3457 /**
3458  * Add a share on a remote RPC server.
3459  *
3460  * @param argc  Standard main() style argc.
3461  * @param argv  Standard main() style argv. Initial components are already
3462  *              stripped.
3463  *
3464  * @return A shell status integer (0 for success).
3465  **/
3466
3467 static int rpc_share_add(struct net_context *c, int argc, const char **argv)
3468 {
3469         NET_API_STATUS status;
3470         char *sharename;
3471         char *path;
3472         uint32 type = STYPE_DISKTREE; /* only allow disk shares to be added */
3473         uint32 num_users=0, perms=0;
3474         char *password=NULL; /* don't allow a share password */
3475         struct SHARE_INFO_2 i2;
3476         uint32_t parm_error = 0;
3477
3478         if ((argc < 1) || !strchr(argv[0], '=') || c->display_usage) {
3479                 return rpc_share_usage(c, argc, argv);
3480         }
3481
3482         if ((sharename = talloc_strdup(c, argv[0])) == NULL) {
3483                 return -1;
3484         }
3485
3486         path = strchr(sharename, '=');
3487         if (!path) {
3488                 return -1;
3489         }
3490
3491         *path++ = '\0';
3492
3493         i2.shi2_netname         = sharename;
3494         i2.shi2_type            = type;
3495         i2.shi2_remark          = c->opt_comment;
3496         i2.shi2_permissions     = perms;
3497         i2.shi2_max_uses        = c->opt_maxusers;
3498         i2.shi2_current_uses    = num_users;
3499         i2.shi2_path            = path;
3500         i2.shi2_passwd          = password;
3501
3502         status = NetShareAdd(c->opt_host,
3503                              2,
3504                              (uint8_t *)&i2,
3505                              &parm_error);
3506         if (status != 0) {
3507                 printf(_("NetShareAdd failed with: %s\n"),
3508                         libnetapi_get_error_string(c->netapi_ctx, status));
3509         }
3510
3511         return status;
3512 }
3513
3514 /**
3515  * Delete a share on a remote RPC server.
3516  *
3517  * @param domain_sid The domain sid acquired from the remote server.
3518  * @param argc  Standard main() style argc.
3519  * @param argv  Standard main() style argv. Initial components are already
3520  *              stripped.
3521  *
3522  * @return A shell status integer (0 for success).
3523  **/
3524 static int rpc_share_delete(struct net_context *c, int argc, const char **argv)
3525 {
3526         if (argc < 1 || c->display_usage) {
3527                 return rpc_share_usage(c, argc, argv);
3528         }
3529
3530         return NetShareDel(c->opt_host, argv[0], 0);
3531 }
3532
3533 /**
3534  * Formatted print of share info
3535  *
3536  * @param r  pointer to SHARE_INFO_1 to format
3537  **/
3538
3539 static void display_share_info_1(struct net_context *c,
3540                                  struct SHARE_INFO_1 *r)
3541 {
3542         if (c->opt_long_list_entries) {
3543                 d_printf("%-12s %-8.8s %-50s\n",
3544                          r->shi1_netname,
3545                          net_share_type_str(r->shi1_type & ~(STYPE_TEMPORARY|STYPE_HIDDEN)),
3546                          r->shi1_remark);
3547         } else {
3548                 d_printf("%s\n", r->shi1_netname);
3549         }
3550 }
3551
3552 static WERROR get_share_info(struct net_context *c,
3553                              struct rpc_pipe_client *pipe_hnd,
3554                              TALLOC_CTX *mem_ctx,
3555                              uint32 level,
3556                              int argc,
3557                              const char **argv,
3558                              struct srvsvc_NetShareInfoCtr *info_ctr)
3559 {
3560         WERROR result;
3561         NTSTATUS status;
3562         union srvsvc_NetShareInfo info;
3563         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
3564
3565         /* no specific share requested, enumerate all */
3566         if (argc == 0) {
3567
3568                 uint32_t preferred_len = 0xffffffff;
3569                 uint32_t total_entries = 0;
3570                 uint32_t resume_handle = 0;
3571
3572                 info_ctr->level = level;
3573
3574                 status = dcerpc_srvsvc_NetShareEnumAll(b, mem_ctx,
3575                                                        pipe_hnd->desthost,
3576                                                        info_ctr,
3577                                                        preferred_len,
3578                                                        &total_entries,
3579                                                        &resume_handle,
3580                                                        &result);
3581                 if (!NT_STATUS_IS_OK(status)) {
3582                         return ntstatus_to_werror(status);
3583                 }
3584                 return result;
3585         }
3586
3587         /* request just one share */
3588         status = dcerpc_srvsvc_NetShareGetInfo(b, mem_ctx,
3589                                                pipe_hnd->desthost,
3590                                                argv[0],
3591                                                level,
3592                                                &info,
3593                                                &result);
3594
3595         if (!NT_STATUS_IS_OK(status)) {
3596                 result = ntstatus_to_werror(status);
3597                 goto done;
3598         }
3599
3600         if (!W_ERROR_IS_OK(result)) {
3601                 goto done;
3602         }
3603
3604         /* construct ctr */
3605         ZERO_STRUCTP(info_ctr);
3606
3607         info_ctr->level = level;
3608
3609         switch (level) {
3610         case 1:
3611         {
3612                 struct srvsvc_NetShareCtr1 *ctr1;
3613
3614                 ctr1 = talloc_zero(mem_ctx, struct srvsvc_NetShareCtr1);
3615                 W_ERROR_HAVE_NO_MEMORY(ctr1);
3616
3617                 ctr1->count = 1;
3618                 ctr1->array = info.info1;
3619
3620                 info_ctr->ctr.ctr1 = ctr1;
3621
3622                 break;
3623         }
3624         case 2:
3625         {
3626                 struct srvsvc_NetShareCtr2 *ctr2;
3627
3628                 ctr2 = talloc_zero(mem_ctx, struct srvsvc_NetShareCtr2);
3629                 W_ERROR_HAVE_NO_MEMORY(ctr2);
3630
3631                 ctr2->count = 1;
3632                 ctr2->array = info.info2;
3633
3634                 info_ctr->ctr.ctr2 = ctr2;
3635
3636                 break;
3637         }
3638         case 502:
3639         {
3640                 struct srvsvc_NetShareCtr502 *ctr502;
3641
3642                 ctr502 = talloc_zero(mem_ctx, struct srvsvc_NetShareCtr502);
3643                 W_ERROR_HAVE_NO_MEMORY(ctr502);
3644
3645                 ctr502->count = 1;
3646                 ctr502->array = info.info502;
3647
3648                 info_ctr->ctr.ctr502 = ctr502;
3649
3650                 break;
3651         }
3652         } /* switch */
3653 done:
3654         return result;
3655 }
3656
3657 /***
3658  * 'net rpc share list' entrypoint.
3659  * @param argc  Standard main() style argc.
3660  * @param argv  Standard main() style argv. Initial components are already
3661  *              stripped.
3662  **/
3663 static int rpc_share_list(struct net_context *c, int argc, const char **argv)
3664 {
3665         NET_API_STATUS status;
3666         struct SHARE_INFO_1 *i1 = NULL;
3667         uint32_t entries_read = 0;
3668         uint32_t total_entries = 0;
3669         uint32_t resume_handle = 0;
3670         uint32_t i, level = 1;
3671
3672         if (c->display_usage) {
3673                 d_printf(  "%s\n"
3674                            "net rpc share list\n"
3675                            "    %s\n",
3676                          _("Usage:"),
3677                          _("List shares on remote server"));
3678                 return 0;
3679         }
3680
3681         status = NetShareEnum(c->opt_host,
3682                               level,
3683                               (uint8_t **)(void *)&i1,
3684                               (uint32_t)-1,
3685                               &entries_read,
3686                               &total_entries,
3687                               &resume_handle);
3688         if (status != 0) {
3689                 goto done;
3690         }
3691
3692         /* Display results */
3693
3694         if (c->opt_long_list_entries) {
3695                 d_printf(_(
3696         "\nEnumerating shared resources (exports) on remote server:\n\n"
3697         "\nShare name   Type     Description\n"
3698         "----------   ----     -----------\n"));
3699         }
3700         for (i = 0; i < entries_read; i++)
3701                 display_share_info_1(c, &i1[i]);
3702  done:
3703         return status;
3704 }
3705
3706 static bool check_share_availability(struct cli_state *cli, const char *netname)
3707 {
3708         NTSTATUS status;
3709
3710         status = cli_tree_connect(cli, netname, "A:", "", 0);
3711         if (!NT_STATUS_IS_OK(status)) {
3712                 d_printf(_("skipping   [%s]: not a file share.\n"), netname);
3713                 return false;
3714         }
3715
3716         status = cli_tdis(cli);
3717         if (!NT_STATUS_IS_OK(status)) {
3718                 d_printf(_("cli_tdis returned %s\n"), nt_errstr(status));
3719                 return false;
3720         }
3721
3722         return true;
3723 }
3724
3725 static bool check_share_sanity(struct net_context *c, struct cli_state *cli,
3726                                const char *netname, uint32 type)
3727 {
3728         /* only support disk shares */
3729         if (! ( type == STYPE_DISKTREE || type == (STYPE_DISKTREE | STYPE_HIDDEN)) ) {
3730                 printf(_("share [%s] is not a diskshare (type: %x)\n"), netname,
3731                        type);
3732                 return false;
3733         }
3734
3735         /* skip builtin shares */
3736         /* FIXME: should print$ be added too ? */
3737         if (strequal(netname,"IPC$") || strequal(netname,"ADMIN$") ||
3738             strequal(netname,"global"))
3739                 return false;
3740
3741         if (c->opt_exclude && in_list(netname, c->opt_exclude, false)) {
3742                 printf(_("excluding  [%s]\n"), netname);
3743                 return false;
3744         }
3745
3746         return check_share_availability(cli, netname);
3747 }
3748
3749 /**
3750  * Migrate shares from a remote RPC server to the local RPC server.
3751  *
3752  * All parameters are provided by the run_rpc_command function, except for
3753  * argc, argv which are passed through.
3754  *
3755  * @param domain_sid The domain sid acquired from the remote server.
3756  * @param cli A cli_state connected to the server.
3757  * @param mem_ctx Talloc context, destroyed on completion of the function.
3758  * @param argc  Standard main() style argc.
3759  * @param argv  Standard main() style argv. Initial components are already
3760  *              stripped.
3761  *
3762  * @return Normal NTSTATUS return.
3763  **/
3764
3765 static NTSTATUS rpc_share_migrate_shares_internals(struct net_context *c,
3766                                                 const struct dom_sid *domain_sid,
3767                                                 const char *domain_name,
3768                                                 struct cli_state *cli,
3769                                                 struct rpc_pipe_client *pipe_hnd,
3770                                                 TALLOC_CTX *mem_ctx,
3771                                                 int argc,
3772                                                 const char **argv)
3773 {
3774         WERROR result;
3775         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
3776         struct srvsvc_NetShareInfoCtr ctr_src;
3777         uint32 i;
3778         struct rpc_pipe_client *srvsvc_pipe = NULL;
3779         struct cli_state *cli_dst = NULL;
3780         uint32 level = 502; /* includes secdesc */
3781         uint32_t parm_error = 0;
3782         struct dcerpc_binding_handle *b;
3783
3784         result = get_share_info(c, pipe_hnd, mem_ctx, level, argc, argv,
3785                                 &ctr_src);
3786         if (!W_ERROR_IS_OK(result))
3787                 goto done;
3788
3789         /* connect destination PI_SRVSVC */
3790         nt_status = connect_dst_pipe(c, &cli_dst, &srvsvc_pipe,
3791                                      &ndr_table_srvsvc);
3792         if (!NT_STATUS_IS_OK(nt_status))
3793                 return nt_status;
3794
3795         b = srvsvc_pipe->binding_handle;
3796
3797         for (i = 0; i < ctr_src.ctr.ctr502->count; i++) {
3798
3799                 union srvsvc_NetShareInfo info;
3800                 struct srvsvc_NetShareInfo502 info502 =
3801                         ctr_src.ctr.ctr502->array[i];
3802
3803                 /* reset error-code */
3804                 nt_status = NT_STATUS_UNSUCCESSFUL;
3805
3806                 if (!check_share_sanity(c, cli, info502.name, info502.type))
3807                         continue;
3808
3809                 /* finally add the share on the dst server */
3810
3811                 printf(_("migrating: [%s], path: %s, comment: %s, without "
3812                          "share-ACLs\n"),
3813                         info502.name, info502.path, info502.comment);
3814
3815                 info.info502 = &info502;
3816
3817                 nt_status = dcerpc_srvsvc_NetShareAdd(b, mem_ctx,
3818                                                       srvsvc_pipe->desthost,
3819                                                       502,
3820                                                       &info,
3821                                                       &parm_error,
3822                                                       &result);
3823                 if (!NT_STATUS_IS_OK(nt_status)) {
3824                         printf(_("cannot add share: %s\n"),
3825                                 nt_errstr(nt_status));
3826                         goto done;
3827                 }
3828                 if (W_ERROR_V(result) == W_ERROR_V(WERR_FILE_EXISTS)) {
3829                         printf(_("           [%s] does already exist\n"),
3830                                 info502.name);
3831                         continue;
3832                 }
3833
3834                 if (!W_ERROR_IS_OK(result)) {
3835                         nt_status = werror_to_ntstatus(result);
3836                         printf(_("cannot add share: %s\n"),
3837                                 win_errstr(result));
3838                         goto done;
3839                 }
3840
3841         }
3842
3843         nt_status = NT_STATUS_OK;
3844
3845 done:
3846         if (cli_dst) {
3847                 cli_shutdown(cli_dst);
3848         }
3849
3850         return nt_status;
3851
3852 }
3853
3854 /**
3855  * Migrate shares from a RPC server to another.
3856  *
3857  * @param argc  Standard main() style argc.
3858  * @param argv  Standard main() style argv. Initial components are already
3859  *              stripped.
3860  *
3861  * @return A shell status integer (0 for success).
3862  **/
3863 static int rpc_share_migrate_shares(struct net_context *c, int argc,
3864                                     const char **argv)
3865 {
3866         if (c->display_usage) {
3867                 d_printf(  "%s\n"
3868                            "net rpc share migrate shares\n"
3869                            "    %s\n",
3870                          _("Usage:"),
3871                          _("Migrate shares to local server"));
3872                 return 0;
3873         }
3874
3875         if (!c->opt_host) {
3876                 printf(_("no server to migrate\n"));
3877                 return -1;
3878         }
3879
3880         return run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
3881                                rpc_share_migrate_shares_internals,
3882                                argc, argv);
3883 }
3884
3885 /**
3886  * Copy a file/dir
3887  *
3888  * @param f     file_info
3889  * @param mask  current search mask
3890  * @param state arg-pointer
3891  *
3892  **/
3893 static NTSTATUS copy_fn(const char *mnt, struct file_info *f,
3894                     const char *mask, void *state)
3895 {
3896         static NTSTATUS nt_status;
3897         static struct copy_clistate *local_state;
3898         static fstring filename, new_mask;
3899         fstring dir;
3900         char *old_dir;
3901         struct net_context *c;
3902
3903         local_state = (struct copy_clistate *)state;
3904         nt_status = NT_STATUS_UNSUCCESSFUL;
3905
3906         c = local_state->c;
3907
3908         if (strequal(f->name, ".") || strequal(f->name, ".."))
3909                 return NT_STATUS_OK;
3910
3911         DEBUG(3,("got mask: %s, name: %s\n", mask, f->name));
3912
3913         /* DIRECTORY */
3914         if (f->mode & FILE_ATTRIBUTE_DIRECTORY) {
3915
3916                 DEBUG(3,("got dir: %s\n", f->name));
3917
3918                 fstrcpy(dir, local_state->cwd);
3919                 fstrcat(dir, "\\");
3920                 fstrcat(dir, f->name);
3921
3922                 switch (net_mode_share)
3923                 {
3924                 case NET_MODE_SHARE_MIGRATE:
3925                         /* create that directory */
3926                         nt_status = net_copy_file(c, local_state->mem_ctx,
3927                                                   local_state->cli_share_src,
3928                                                   local_state->cli_share_dst,
3929                                                   dir, dir,
3930                                                   c->opt_acls? true : false,
3931                                                   c->opt_attrs? true : false,
3932                                                   c->opt_timestamps? true:false,
3933                                                   false);
3934                         break;
3935                 default:
3936                         d_fprintf(stderr, _("Unsupported mode %d\n"), net_mode_share);
3937                         return NT_STATUS_INTERNAL_ERROR;
3938                 }
3939
3940                 if (!NT_STATUS_IS_OK(nt_status)) {
3941                         printf(_("could not handle dir %s: %s\n"),
3942                                 dir, nt_errstr(nt_status));
3943                         return nt_status;
3944                 }
3945
3946                 /* search below that directory */
3947                 if (strlcpy(new_mask, dir, sizeof(new_mask)) >= sizeof(new_mask)) {
3948                         return NT_STATUS_NO_MEMORY;
3949                 }
3950                 if (strlcat(new_mask, "\\*", sizeof(new_mask)) >= sizeof(new_mask)) {
3951                         return NT_STATUS_NO_MEMORY;
3952                 }
3953
3954                 old_dir = local_state->cwd;
3955                 local_state->cwd = dir;
3956                 nt_status = sync_files(local_state, new_mask);
3957                 if (!NT_STATUS_IS_OK(nt_status)) {
3958                         printf(_("could not handle files\n"));
3959                 }
3960                 local_state->cwd = old_dir;
3961
3962                 return nt_status;
3963         }
3964
3965
3966         /* FILE */
3967         fstrcpy(filename, local_state->cwd);
3968         fstrcat(filename, "\\");
3969         fstrcat(filename, f->name);
3970
3971         DEBUG(3,("got file: %s\n", filename));
3972
3973         switch (net_mode_share)
3974         {
3975         case NET_MODE_SHARE_MIGRATE:
3976                 nt_status = net_copy_file(c, local_state->mem_ctx,
3977                                           local_state->cli_share_src,
3978                                           local_state->cli_share_dst,
3979                                           filename, filename,
3980                                           c->opt_acls? true : false,
3981                                           c->opt_attrs? true : false,
3982                                           c->opt_timestamps? true: false,
3983                                           true);
3984                 break;
3985         default:
3986                 d_fprintf(stderr, _("Unsupported file mode %d\n"),
3987                           net_mode_share);
3988                 return NT_STATUS_INTERNAL_ERROR;
3989         }
3990
3991         if (!NT_STATUS_IS_OK(nt_status))
3992                 printf(_("could not handle file %s: %s\n"),
3993                         filename, nt_errstr(nt_status));
3994         return nt_status;
3995 }
3996
3997 /**
3998  * sync files, can be called recursivly to list files
3999  * and then call copy_fn for each file
4000  *
4001  * @param cp_clistate   pointer to the copy_clistate we work with
4002  * @param mask          the current search mask
4003  *
4004  * @return              Boolean result
4005  **/
4006 static NTSTATUS sync_files(struct copy_clistate *cp_clistate, const char *mask)
4007 {
4008         struct cli_state *targetcli;
4009         char *targetpath = NULL;
4010         NTSTATUS status;
4011
4012         DEBUG(3,("calling cli_list with mask: %s\n", mask));
4013
4014         status = cli_resolve_path(talloc_tos(), "", NULL,
4015                                   cp_clistate->cli_share_src,
4016                                   mask, &targetcli, &targetpath);
4017         if (!NT_STATUS_IS_OK(status)) {
4018                 d_fprintf(stderr, _("cli_resolve_path %s failed with error: "
4019                                     "%s\n"),
4020                         mask, nt_errstr(status));
4021                 return status;
4022         }
4023
4024         status = cli_list(targetcli, targetpath, cp_clistate->attribute,
4025                           copy_fn, cp_clistate);
4026         if (!NT_STATUS_IS_OK(status)) {
4027                 d_fprintf(stderr, _("listing %s failed with error: %s\n"),
4028                           mask, nt_errstr(status));
4029         }
4030
4031         return status;
4032 }
4033
4034
4035 /**
4036  * Set the top level directory permissions before we do any further copies.
4037  * Should set up ACL inheritance.
4038  **/
4039
4040 bool copy_top_level_perms(struct net_context *c,
4041                                 struct copy_clistate *cp_clistate,
4042                                 const char *sharename)
4043 {
4044         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
4045
4046         switch (net_mode_share) {
4047         case NET_MODE_SHARE_MIGRATE:
4048                 DEBUG(3,("calling net_copy_fileattr for '.' directory in share %s\n", sharename));
4049                 nt_status = net_copy_fileattr(c,
4050                                                 cp_clistate->mem_ctx,
4051                                                 cp_clistate->cli_share_src,
4052                                                 cp_clistate->cli_share_dst,
4053                                                 "\\", "\\",
4054                                                 c->opt_acls? true : false,
4055                                                 c->opt_attrs? true : false,
4056                                                 c->opt_timestamps? true: false,
4057                                                 false);
4058                 break;
4059         default:
4060                 d_fprintf(stderr, _("Unsupported mode %d\n"), net_mode_share);
4061                 break;
4062         }
4063
4064         if (!NT_STATUS_IS_OK(nt_status))  {
4065                 printf(_("Could handle directory attributes for top level "
4066                          "directory of share %s. Error %s\n"),
4067                         sharename, nt_errstr(nt_status));
4068                 return false;
4069         }
4070
4071         return true;
4072 }
4073
4074 /**
4075  * Sync all files inside a remote share to another share (over smb).
4076  *
4077  * All parameters are provided by the run_rpc_command function, except for
4078  * argc, argv which are passed through.
4079  *
4080  * @param domain_sid The domain sid acquired from the remote server.
4081  * @param cli A cli_state connected to the server.
4082  * @param mem_ctx Talloc context, destroyed on completion of the function.
4083  * @param argc  Standard main() style argc.
4084  * @param argv  Standard main() style argv. Initial components are already
4085  *              stripped.
4086  *
4087  * @return Normal NTSTATUS return.
4088  **/
4089
4090 static NTSTATUS rpc_share_migrate_files_internals(struct net_context *c,
4091                                                 const struct dom_sid *domain_sid,
4092                                                 const char *domain_name,
4093                                                 struct cli_state *cli,
4094                                                 struct rpc_pipe_client *pipe_hnd,
4095                                                 TALLOC_CTX *mem_ctx,
4096                                                 int argc,
4097                                                 const char **argv)
4098 {
4099         WERROR result;
4100         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
4101         struct srvsvc_NetShareInfoCtr ctr_src;
4102         uint32 i;
4103         uint32 level = 502;
4104         struct copy_clistate cp_clistate;
4105         bool got_src_share = false;
4106         bool got_dst_share = false;
4107         const char *mask = "\\*";
4108         char *dst = NULL;
4109
4110         dst = SMB_STRDUP(c->opt_destination?c->opt_destination:"127.0.0.1");
4111         if (dst == NULL) {
4112                 nt_status = NT_STATUS_NO_MEMORY;
4113                 goto done;
4114         }
4115
4116         result = get_share_info(c, pipe_hnd, mem_ctx, level, argc, argv,
4117                                 &ctr_src);
4118
4119         if (!W_ERROR_IS_OK(result))
4120                 goto done;
4121
4122         for (i = 0; i < ctr_src.ctr.ctr502->count; i++) {
4123
4124                 struct srvsvc_NetShareInfo502 info502 =
4125                         ctr_src.ctr.ctr502->array[i];
4126
4127                 if (!check_share_sanity(c, cli, info502.name, info502.type))
4128                         continue;
4129
4130                 /* one might not want to mirror whole discs :) */
4131                 if (strequal(info502.name, "print$") || info502.name[1] == '$') {
4132                         d_printf(_("skipping   [%s]: builtin/hidden share\n"),
4133                                  info502.name);
4134                         continue;
4135                 }
4136
4137                 switch (net_mode_share)
4138                 {
4139                 case NET_MODE_SHARE_MIGRATE:
4140                         printf("syncing");
4141                         break;
4142                 default:
4143                         d_fprintf(stderr, _("Unsupported mode %d\n"),
4144                                   net_mode_share);
4145                         break;
4146                 }
4147                 printf(_("    [%s] files and directories %s ACLs, %s DOS "
4148                          "Attributes %s\n"),
4149                         info502.name,
4150                         c->opt_acls ? _("including") : _("without"),
4151                         c->opt_attrs ? _("including") : _("without"),
4152                         c->opt_timestamps ? _("(preserving timestamps)") : "");
4153
4154                 cp_clistate.mem_ctx = mem_ctx;
4155                 cp_clistate.cli_share_src = NULL;
4156                 cp_clistate.cli_share_dst = NULL;
4157                 cp_clistate.cwd = NULL;
4158                 cp_clistate.attribute = FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_DIRECTORY;
4159                 cp_clistate.c = c;
4160
4161                 /* open share source */
4162                 nt_status = connect_to_service(c, &cp_clistate.cli_share_src,
4163                                                smbXcli_conn_remote_sockaddr(cli->conn),
4164                                                smbXcli_conn_remote_name(cli->conn),
4165                                                info502.name, "A:");
4166                 if (!NT_STATUS_IS_OK(nt_status))
4167                         goto done;
4168
4169                 got_src_share = true;
4170
4171                 if (net_mode_share == NET_MODE_SHARE_MIGRATE) {
4172                         /* open share destination */
4173                         nt_status = connect_to_service(c, &cp_clistate.cli_share_dst,
4174                                                        NULL, dst, info502.name, "A:");
4175                         if (!NT_STATUS_IS_OK(nt_status))
4176                                 goto done;
4177
4178                         got_dst_share = true;
4179                 }
4180
4181                 if (!copy_top_level_perms(c, &cp_clistate, info502.name)) {
4182                         d_fprintf(stderr, _("Could not handle the top level "
4183                                             "directory permissions for the "
4184                                             "share: %s\n"), info502.name);
4185                         nt_status = NT_STATUS_UNSUCCESSFUL;
4186                         goto done;
4187                 }
4188
4189                 nt_status = sync_files(&cp_clistate, mask);
4190                 if (!NT_STATUS_IS_OK(nt_status)) {
4191                         d_fprintf(stderr, _("could not handle files for share: "
4192                                             "%s\n"), info502.name);
4193                         goto done;
4194                 }
4195         }
4196
4197         nt_status = NT_STATUS_OK;
4198
4199 done:
4200
4201         if (got_src_share)
4202                 cli_shutdown(cp_clistate.cli_share_src);
4203
4204         if (got_dst_share)
4205                 cli_shutdown(cp_clistate.cli_share_dst);
4206
4207         SAFE_FREE(dst);
4208         return nt_status;
4209
4210 }
4211
4212 static int rpc_share_migrate_files(struct net_context *c, int argc, const char **argv)
4213 {
4214         if (c->display_usage) {
4215                 d_printf(  "%s\n"
4216                            "net share migrate files\n"
4217                            "    %s\n",
4218                          _("Usage:"),
4219                          _("Migrate files to local server"));
4220                 return 0;
4221         }
4222
4223         if (!c->opt_host) {
4224                 d_printf(_("no server to migrate\n"));
4225                 return -1;
4226         }
4227
4228         return run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
4229                                rpc_share_migrate_files_internals,
4230                                argc, argv);
4231 }
4232
4233 /**
4234  * Migrate share-ACLs from a remote RPC server to the local RPC server.
4235  *
4236  * All parameters are provided by the run_rpc_command function, except for
4237  * argc, argv which are passed through.
4238  *
4239  * @param domain_sid The domain sid acquired from the remote server.
4240  * @param cli A cli_state connected to the server.
4241  * @param mem_ctx Talloc context, destroyed on completion of the function.
4242  * @param argc  Standard main() style argc.
4243  * @param argv  Standard main() style argv. Initial components are already
4244  *              stripped.
4245  *
4246  * @return Normal NTSTATUS return.
4247  **/
4248
4249 static NTSTATUS rpc_share_migrate_security_internals(struct net_context *c,
4250                                                 const struct dom_sid *domain_sid,
4251                                                 const char *domain_name,
4252                                                 struct cli_state *cli,
4253                                                 struct rpc_pipe_client *pipe_hnd,
4254                                                 TALLOC_CTX *mem_ctx,
4255                                                 int argc,
4256                                                 const char **argv)
4257 {
4258         WERROR result;
4259         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
4260         struct srvsvc_NetShareInfoCtr ctr_src;
4261         union srvsvc_NetShareInfo info;
4262         uint32 i;
4263         struct rpc_pipe_client *srvsvc_pipe = NULL;
4264         struct cli_state *cli_dst = NULL;
4265         uint32 level = 502; /* includes secdesc */
4266         uint32_t parm_error = 0;
4267         struct dcerpc_binding_handle *b;
4268
4269         result = get_share_info(c, pipe_hnd, mem_ctx, level, argc, argv,
4270                                 &ctr_src);
4271
4272         if (!W_ERROR_IS_OK(result))
4273                 goto done;
4274
4275         /* connect destination PI_SRVSVC */
4276         nt_status = connect_dst_pipe(c, &cli_dst, &srvsvc_pipe,
4277                                      &ndr_table_srvsvc);
4278         if (!NT_STATUS_IS_OK(nt_status))
4279                 return nt_status;
4280
4281         b = srvsvc_pipe->binding_handle;
4282
4283         for (i = 0; i < ctr_src.ctr.ctr502->count; i++) {
4284
4285                 struct srvsvc_NetShareInfo502 info502 =
4286                         ctr_src.ctr.ctr502->array[i];
4287
4288                 /* reset error-code */
4289                 nt_status = NT_STATUS_UNSUCCESSFUL;
4290
4291                 if (!check_share_sanity(c, cli, info502.name, info502.type))
4292                         continue;
4293
4294                 printf(_("migrating: [%s], path: %s, comment: %s, including "
4295                          "share-ACLs\n"),
4296                         info502.name, info502.path, info502.comment);
4297
4298                 if (c->opt_verbose)
4299                         display_sec_desc(info502.sd_buf.sd);
4300
4301                 /* FIXME: shouldn't we be able to just set the security descriptor ? */
4302                 info.info502 = &info502;
4303
4304                 /* finally modify the share on the dst server */
4305                 nt_status = dcerpc_srvsvc_NetShareSetInfo(b, mem_ctx,
4306                                                           srvsvc_pipe->desthost,
4307                                                           info502.name,
4308                                                           level,
4309                                                           &info,
4310                                                           &parm_error,
4311                                                           &result);
4312                 if (!NT_STATUS_IS_OK(nt_status)) {
4313                         printf(_("cannot set share-acl: %s\n"),
4314                                nt_errstr(nt_status));
4315                         goto done;
4316                 }
4317                 if (!W_ERROR_IS_OK(result)) {
4318                         nt_status = werror_to_ntstatus(result);
4319                         printf(_("cannot set share-acl: %s\n"),
4320                                win_errstr(result));
4321                         goto done;
4322                 }
4323
4324         }
4325
4326         nt_status = NT_STATUS_OK;
4327
4328 done:
4329         if (cli_dst) {
4330                 cli_shutdown(cli_dst);
4331         }
4332
4333         return nt_status;
4334
4335 }
4336
4337 /**
4338  * Migrate share-acls from a RPC server to another.
4339  *
4340  * @param argc  Standard main() style argc.
4341  * @param argv  Standard main() style argv. Initial components are already
4342  *              stripped.
4343  *
4344  * @return A shell status integer (0 for success).
4345  **/
4346 static int rpc_share_migrate_security(struct net_context *c, int argc,
4347                                       const char **argv)
4348 {
4349         if (c->display_usage) {
4350                 d_printf(  "%s\n"
4351                            "net rpc share migrate security\n"
4352                            "    %s\n",
4353                          _("Usage:"),
4354                          _("Migrate share-acls to local server"));
4355                 return 0;
4356         }
4357
4358         if (!c->opt_host) {
4359                 d_printf(_("no server to migrate\n"));
4360                 return -1;
4361         }
4362
4363         return run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
4364                                rpc_share_migrate_security_internals,
4365                                argc, argv);
4366 }
4367
4368 /**
4369  * Migrate shares (including share-definitions, share-acls and files with acls/attrs)
4370  * from one server to another.
4371  *
4372  * @param argc  Standard main() style argc.
4373  * @param argv  Standard main() style argv. Initial components are already
4374  *              stripped.
4375  *
4376  * @return A shell status integer (0 for success).
4377  *
4378  **/
4379 static int rpc_share_migrate_all(struct net_context *c, int argc,
4380                                  const char **argv)
4381 {
4382         int ret;
4383
4384         if (c->display_usage) {
4385                 d_printf(  "%s\n"
4386                            "net rpc share migrate all\n"
4387                            "    %s\n",
4388                          _("Usage:"),
4389                          _("Migrates shares including all share settings"));
4390                 return 0;
4391         }
4392
4393         if (!c->opt_host) {
4394                 d_printf(_("no server to migrate\n"));
4395                 return -1;
4396         }
4397
4398         /* order is important. we don't want to be locked out by the share-acl
4399          * before copying files - gd */
4400
4401         ret = run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
4402                               rpc_share_migrate_shares_internals, argc, argv);
4403         if (ret)
4404                 return ret;
4405
4406         ret = run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
4407                               rpc_share_migrate_files_internals, argc, argv);
4408         if (ret)
4409                 return ret;
4410
4411         return run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
4412                                rpc_share_migrate_security_internals, argc,
4413                                argv);
4414 }
4415
4416
4417 /**
4418  * 'net rpc share migrate' entrypoint.
4419  * @param argc  Standard main() style argc.
4420  * @param argv  Standard main() style argv. Initial components are already
4421  *              stripped.
4422  **/
4423 static int rpc_share_migrate(struct net_context *c, int argc, const char **argv)
4424 {
4425
4426         struct functable func[] = {
4427                 {
4428                         "all",
4429                         rpc_share_migrate_all,
4430                         NET_TRANSPORT_RPC,
4431                         N_("Migrate shares from remote to local server"),
4432                         N_("net rpc share migrate all\n"
4433                            "    Migrate shares from remote to local server")
4434                 },
4435                 {
4436                         "files",
4437                         rpc_share_migrate_files,
4438                         NET_TRANSPORT_RPC,
4439                         N_("Migrate files from remote to local server"),
4440                         N_("net rpc share migrate files\n"
4441                            "    Migrate files from remote to local server")
4442                 },
4443                 {
4444                         "security",
4445                         rpc_share_migrate_security,
4446                         NET_TRANSPORT_RPC,
4447                         N_("Migrate share-ACLs from remote to local server"),
4448                         N_("net rpc share migrate security\n"
4449                            "    Migrate share-ACLs from remote to local server")
4450                 },
4451                 {
4452                         "shares",
4453                         rpc_share_migrate_shares,
4454                         NET_TRANSPORT_RPC,
4455                         N_("Migrate shares from remote to local server"),
4456                         N_("net rpc share migrate shares\n"
4457                            "    Migrate shares from remote to local server")
4458                 },
4459                 {NULL, NULL, 0, NULL, NULL}
4460         };
4461
4462         net_mode_share = NET_MODE_SHARE_MIGRATE;
4463
4464         return net_run_function(c, argc, argv, "net rpc share migrate", func);
4465 }
4466
4467 struct full_alias {
4468         struct dom_sid sid;
4469         uint32 num_members;
4470         struct dom_sid *members;
4471 };
4472
4473 static int num_server_aliases;
4474 static struct full_alias *server_aliases;
4475
4476 /*
4477  * Add an alias to the static list.
4478  */
4479 static void push_alias(TALLOC_CTX *mem_ctx, struct full_alias *alias)
4480 {
4481         if (server_aliases == NULL)
4482                 server_aliases = SMB_MALLOC_ARRAY(struct full_alias, 100);
4483
4484         server_aliases[num_server_aliases] = *alias;
4485         num_server_aliases += 1;
4486 }
4487
4488 /*
4489  * For a specific domain on the server, fetch all the aliases
4490  * and their members. Add all of them to the server_aliases.
4491  */
4492
4493 static NTSTATUS rpc_fetch_domain_aliases(struct rpc_pipe_client *pipe_hnd,
4494                                         TALLOC_CTX *mem_ctx,
4495                                         struct policy_handle *connect_pol,
4496                                         const struct dom_sid *domain_sid)
4497 {
4498         uint32 start_idx, max_entries, num_entries, i;
4499         struct samr_SamArray *groups = NULL;
4500         NTSTATUS result, status;
4501         struct policy_handle domain_pol;
4502         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
4503
4504         /* Get domain policy handle */
4505
4506         status = dcerpc_samr_OpenDomain(b, mem_ctx,
4507                                         connect_pol,
4508                                         MAXIMUM_ALLOWED_ACCESS,
4509                                         discard_const_p(struct dom_sid2, domain_sid),
4510                                         &domain_pol,
4511                                         &result);
4512         if (!NT_STATUS_IS_OK(status)) {
4513                 return status;
4514         }
4515         if (!NT_STATUS_IS_OK(result)) {
4516                 return result;
4517         }
4518
4519         start_idx = 0;
4520         max_entries = 250;
4521
4522         do {
4523                 status = dcerpc_samr_EnumDomainAliases(b, mem_ctx,
4524                                                        &domain_pol,
4525                                                        &start_idx,
4526                                                        &groups,
4527                                                        max_entries,
4528                                                        &num_entries,
4529                                                        &result);
4530                 if (!NT_STATUS_IS_OK(status)) {
4531                         goto done;
4532                 }
4533                 for (i = 0; i < num_entries; i++) {
4534
4535                         struct policy_handle alias_pol;
4536                         struct full_alias alias;
4537                         struct lsa_SidArray sid_array;
4538                         int j;
4539                         NTSTATUS _result;
4540
4541                         status = dcerpc_samr_OpenAlias(b, mem_ctx,
4542                                                        &domain_pol,
4543                                                        MAXIMUM_ALLOWED_ACCESS,
4544                                                        groups->entries[i].idx,
4545                                                        &alias_pol,
4546                                                        &_result);
4547                         if (!NT_STATUS_IS_OK(status)) {
4548                                 goto done;
4549                         }
4550                         if (!NT_STATUS_IS_OK(_result)) {
4551                                 status = _result;
4552                                 goto done;
4553                         }
4554
4555                         status = dcerpc_samr_GetMembersInAlias(b, mem_ctx,
4556                                                                &alias_pol,
4557                                                                &sid_array,
4558                                                                &_result);
4559                         if (!NT_STATUS_IS_OK(status)) {
4560                                 goto done;
4561                         }
4562                         if (!NT_STATUS_IS_OK(_result)) {
4563                                 status = _result;
4564                                 goto done;
4565                         }
4566
4567                         alias.num_members = sid_array.num_sids;
4568
4569                         status = dcerpc_samr_Close(b, mem_ctx, &alias_pol, &_result);
4570                         if (!NT_STATUS_IS_OK(status)) {
4571                                 goto done;
4572                         }
4573                         if (!NT_STATUS_IS_OK(_result)) {
4574                                 status = _result;
4575                                 goto done;
4576                         }
4577
4578                         alias.members = NULL;
4579
4580                         if (alias.num_members > 0) {
4581                                 alias.members = SMB_MALLOC_ARRAY(struct dom_sid, alias.num_members);
4582
4583                                 for (j = 0; j < alias.num_members; j++)
4584                                         sid_copy(&alias.members[j],
4585                                                  sid_array.sids[j].sid);
4586                         }
4587
4588                         sid_compose(&alias.sid, domain_sid,
4589                                     groups->entries[i].idx);
4590
4591                         push_alias(mem_ctx, &alias);
4592                 }
4593         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
4594
4595         status = NT_STATUS_OK;
4596
4597  done:
4598         dcerpc_samr_Close(b, mem_ctx, &domain_pol, &result);
4599
4600         return status;
4601 }
4602
4603 /*
4604  * Dump server_aliases as names for debugging purposes.
4605  */
4606
4607 static NTSTATUS rpc_aliaslist_dump(struct net_context *c,
4608                                 const struct dom_sid *domain_sid,
4609                                 const char *domain_name,
4610                                 struct cli_state *cli,
4611                                 struct rpc_pipe_client *pipe_hnd,
4612                                 TALLOC_CTX *mem_ctx,
4613                                 int argc,
4614                                 const char **argv)
4615 {
4616         int i;
4617         NTSTATUS result;
4618         struct policy_handle lsa_pol;
4619         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
4620
4621         result = rpccli_lsa_open_policy(pipe_hnd, mem_ctx, true,
4622                                      SEC_FLAG_MAXIMUM_ALLOWED,
4623                                      &lsa_pol);
4624         if (!NT_STATUS_IS_OK(result))
4625                 return result;
4626
4627         for (i=0; i<num_server_aliases; i++) {
4628                 char **names;
4629                 char **domains;
4630                 enum lsa_SidType *types;
4631                 int j;
4632
4633                 struct full_alias *alias = &server_aliases[i];
4634
4635                 result = rpccli_lsa_lookup_sids(pipe_hnd, mem_ctx, &lsa_pol, 1,
4636                                              &alias->sid,
4637                                              &domains, &names, &types);
4638                 if (!NT_STATUS_IS_OK(result))
4639                         continue;
4640
4641                 DEBUG(1, ("%s\\%s %d: ", domains[0], names[0], types[0]));
4642
4643                 if (alias->num_members == 0) {
4644                         DEBUG(1, ("\n"));
4645                         continue;
4646                 }
4647
4648                 result = rpccli_lsa_lookup_sids(pipe_hnd, mem_ctx, &lsa_pol,
4649                                              alias->num_members,
4650                                              alias->members,
4651                                              &domains, &names, &types);
4652
4653                 if (!NT_STATUS_IS_OK(result) &&
4654                     !NT_STATUS_EQUAL(result, STATUS_SOME_UNMAPPED))
4655                         continue;
4656
4657                 for (j=0; j<alias->num_members; j++)
4658                         DEBUG(1, ("%s\\%s (%d); ",
4659                                   domains[j] ? domains[j] : "*unknown*",
4660                                   names[j] ? names[j] : "*unknown*",types[j]));
4661                 DEBUG(1, ("\n"));
4662         }
4663
4664         dcerpc_lsa_Close(b, mem_ctx, &lsa_pol, &result);
4665
4666         return NT_STATUS_OK;
4667 }
4668
4669 /*
4670  * Fetch a list of all server aliases and their members into
4671  * server_aliases.
4672  */
4673
4674 static NTSTATUS rpc_aliaslist_internals(struct net_context *c,
4675                                         const struct dom_sid *domain_sid,
4676                                         const char *domain_name,
4677                                         struct cli_state *cli,
4678                                         struct rpc_pipe_client *pipe_hnd,
4679                                         TALLOC_CTX *mem_ctx,
4680                                         int argc,
4681                                         const char **argv)
4682 {
4683         NTSTATUS result, status;
4684         struct policy_handle connect_pol;
4685         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
4686
4687         status = dcerpc_samr_Connect2(b, mem_ctx,
4688                                       pipe_hnd->desthost,
4689                                       MAXIMUM_ALLOWED_ACCESS,
4690                                       &connect_pol,
4691                                       &result);
4692         if (!NT_STATUS_IS_OK(status)) {
4693                 goto done;
4694         }
4695         if (!NT_STATUS_IS_OK(result)) {
4696                 status = result;
4697                 goto done;
4698         }
4699
4700         status = rpc_fetch_domain_aliases(pipe_hnd, mem_ctx, &connect_pol,
4701                                           &global_sid_Builtin);
4702         if (!NT_STATUS_IS_OK(status)) {
4703                 goto done;
4704         }
4705
4706         status = rpc_fetch_domain_aliases(pipe_hnd, mem_ctx, &connect_pol,
4707                                           domain_sid);
4708
4709         dcerpc_samr_Close(b, mem_ctx, &connect_pol, &result);
4710  done:
4711         return status;
4712 }
4713
4714 static void init_user_token(struct security_token *token, struct dom_sid *user_sid)
4715 {
4716         token->num_sids = 4;
4717
4718         if (!(token->sids = SMB_MALLOC_ARRAY(struct dom_sid, 4))) {
4719                 d_fprintf(stderr, "malloc %s\n",_("failed"));
4720                 token->num_sids = 0;
4721                 return;
4722         }
4723
4724         token->sids[0] = *user_sid;
4725         sid_copy(&token->sids[1], &global_sid_World);
4726         sid_copy(&token->sids[2], &global_sid_Network);
4727         sid_copy(&token->sids[3], &global_sid_Authenticated_Users);
4728 }
4729
4730 static void free_user_token(struct security_token *token)
4731 {
4732         SAFE_FREE(token->sids);
4733 }
4734
4735 static void add_sid_to_token(struct security_token *token, struct dom_sid *sid)
4736 {
4737         if (security_token_has_sid(token, sid))
4738                 return;
4739
4740         token->sids = SMB_REALLOC_ARRAY(token->sids, struct dom_sid, token->num_sids+1);
4741         if (!token->sids) {
4742                 return;
4743         }
4744
4745         sid_copy(&token->sids[token->num_sids], sid);
4746
4747         token->num_sids += 1;
4748 }
4749
4750 struct user_token {
4751         fstring name;
4752         struct security_token token;
4753 };
4754
4755 static void dump_user_token(struct user_token *token)
4756 {
4757         int i;
4758
4759         d_printf("%s\n", token->name);
4760
4761         for (i=0; i<token->token.num_sids; i++) {
4762                 d_printf(" %s\n", sid_string_tos(&token->token.sids[i]));
4763         }
4764 }
4765
4766 static bool is_alias_member(struct dom_sid *sid, struct full_alias *alias)
4767 {
4768         int i;
4769
4770         for (i=0; i<alias->num_members; i++) {
4771                 if (dom_sid_compare(sid, &alias->members[i]) == 0)
4772                         return true;
4773         }
4774
4775         return false;
4776 }
4777
4778 static void collect_sid_memberships(struct security_token *token, struct dom_sid sid)
4779 {
4780         int i;
4781
4782         for (i=0; i<num_server_aliases; i++) {
4783                 if (is_alias_member(&sid, &server_aliases[i]))
4784                         add_sid_to_token(token, &server_aliases[i].sid);
4785         }
4786 }
4787
4788 /*
4789  * We got a user token with all the SIDs we can know about without asking the
4790  * server directly. These are the user and domain group sids. All of these can
4791  * be members of aliases. So scan the list of aliases for each of the SIDs and
4792  * add them to the token.
4793  */
4794
4795 static void collect_alias_memberships(struct security_token *token)
4796 {
4797         int num_global_sids = token->num_sids;
4798         int i;
4799
4800         for (i=0; i<num_global_sids; i++) {
4801                 collect_sid_memberships(token, token->sids[i]);
4802         }
4803 }
4804
4805 static bool get_user_sids(const char *domain, const char *user, struct security_token *token)
4806 {
4807         wbcErr wbc_status = WBC_ERR_UNKNOWN_FAILURE;
4808         enum wbcSidType type;
4809         fstring full_name;
4810         struct wbcDomainSid wsid;
4811         char sid_str[WBC_SID_STRING_BUFLEN];
4812         struct dom_sid user_sid;
4813         uint32_t num_groups;
4814         gid_t *groups = NULL;
4815         uint32_t i;
4816
4817         fstr_sprintf(full_name, "%s%c%s",
4818                      domain, *lp_winbind_separator(), user);
4819
4820         /* First let's find out the user sid */
4821
4822         wbc_status = wbcLookupName(domain, user, &wsid, &type);
4823
4824         if (!WBC_ERROR_IS_OK(wbc_status)) {
4825                 DEBUG(1, ("winbind could not find %s: %s\n",
4826                           full_name, wbcErrorString(wbc_status)));
4827                 return false;
4828         }
4829
4830         wbcSidToStringBuf(&wsid, sid_str, sizeof(sid_str));
4831
4832         if (type != WBC_SID_NAME_USER) {
4833                 DEBUG(1, ("%s is not a user\n", full_name));
4834                 return false;
4835         }
4836
4837         if (!string_to_sid(&user_sid, sid_str)) {
4838                 DEBUG(1,("Could not convert sid %s from string\n", sid_str));
4839                 return false;
4840         }
4841
4842         init_user_token(token, &user_sid);
4843
4844         /* And now the groups winbind knows about */
4845
4846         wbc_status = wbcGetGroups(full_name, &num_groups, &groups);
4847         if (!WBC_ERROR_IS_OK(wbc_status)) {
4848                 DEBUG(1, ("winbind could not get groups of %s: %s\n",
4849                         full_name, wbcErrorString(wbc_status)));
4850                 return false;
4851         }
4852
4853         for (i = 0; i < num_groups; i++) {
4854                 gid_t gid = groups[i];
4855                 struct dom_sid sid;
4856                 bool ok;
4857
4858                 wbc_status = wbcGidToSid(gid, &wsid);
4859                 if (!WBC_ERROR_IS_OK(wbc_status)) {
4860                         DEBUG(1, ("winbind could not find SID of gid %u: %s\n",
4861                                   (unsigned int)gid, wbcErrorString(wbc_status)));
4862                         wbcFreeMemory(groups);
4863                         return false;
4864                 }
4865
4866                 wbcSidToStringBuf(&wsid, sid_str, sizeof(sid_str));
4867
4868                 DEBUG(3, (" %s\n", sid_str));
4869
4870                 ok = string_to_sid(&sid, sid_str);
4871                 if (!ok) {
4872                         DEBUG(1, ("Failed to convert string to SID\n"));
4873                         wbcFreeMemory(groups);
4874                         return false;
4875                 }
4876                 add_sid_to_token(token, &sid);
4877         }
4878         wbcFreeMemory(groups);
4879
4880         return true;
4881 }
4882
4883 /**
4884  * Get a list of all user tokens we want to look at
4885  **/
4886
4887 static bool get_user_tokens(struct net_context *c, int *num_tokens,
4888                             struct user_token **user_tokens)
4889 {
4890         wbcErr wbc_status = WBC_ERR_UNKNOWN_FAILURE;
4891         uint32_t i, num_users;
4892         const char **users;
4893         struct user_token *result;
4894         TALLOC_CTX *frame = NULL;
4895
4896         if (lp_winbind_use_default_domain() &&
4897             (c->opt_target_workgroup == NULL)) {
4898                 d_fprintf(stderr, _("winbind use default domain = yes set, "
4899                          "please specify a workgroup\n"));
4900                 return false;
4901         }
4902
4903         /* Send request to winbind daemon */
4904
4905         wbc_status = wbcListUsers(NULL, &num_users, &users);
4906         if (!WBC_ERROR_IS_OK(wbc_status)) {
4907                 DEBUG(1, (_("winbind could not list users: %s\n"),
4908                           wbcErrorString(wbc_status)));
4909                 return false;
4910         }
4911
4912         result = SMB_MALLOC_ARRAY(struct user_token, num_users);
4913
4914         if (result == NULL) {
4915                 DEBUG(1, ("Could not malloc sid array\n"));
4916                 wbcFreeMemory(users);
4917                 return false;
4918         }
4919
4920         frame = talloc_stackframe();
4921         for (i=0; i < num_users; i++) {
4922                 fstring domain, user;
4923                 char *p;
4924
4925                 fstrcpy(result[i].name, users[i]);
4926
4927                 p = strchr(users[i], *lp_winbind_separator());
4928
4929                 DEBUG(3, ("%s\n", users[i]));
4930
4931                 if (p == NULL) {
4932                         fstrcpy(domain, c->opt_target_workgroup);
4933                         fstrcpy(user, users[i]);
4934                 } else {
4935                         *p++ = '\0';
4936                         fstrcpy(domain, users[i]);
4937                         if (!strupper_m(domain)) {
4938                                 DEBUG(1, ("strupper_m %s failed\n", domain));
4939                                 wbcFreeMemory(users);
4940                                 return false;
4941                         }
4942                         fstrcpy(user, p);
4943                 }
4944
4945                 get_user_sids(domain, user, &(result[i].token));
4946         }
4947         TALLOC_FREE(frame);
4948         wbcFreeMemory(users);
4949
4950         *num_tokens = num_users;
4951         *user_tokens = result;
4952
4953         return true;
4954 }
4955
4956 static bool get_user_tokens_from_file(FILE *f,
4957                                       int *num_tokens,
4958                                       struct user_token **tokens)
4959 {
4960         struct user_token *token = NULL;
4961
4962         while (!feof(f)) {
4963                 fstring line;
4964
4965                 if (fgets(line, sizeof(line)-1, f) == NULL) {
4966                         return true;
4967                 }
4968
4969                 if ((strlen(line) > 0) && (line[strlen(line)-1] == '\n')) {
4970                         line[strlen(line)-1] = '\0';
4971                 }
4972
4973                 if (line[0] == ' ') {
4974                         /* We have a SID */
4975
4976                         struct dom_sid sid;
4977                         if(!string_to_sid(&sid, &line[1])) {
4978                                 DEBUG(1,("get_user_tokens_from_file: Could "
4979                                         "not convert sid %s \n",&line[1]));
4980                                 return false;
4981                         }
4982
4983                         if (token == NULL) {
4984                                 DEBUG(0, ("File does not begin with username"));
4985                                 return false;
4986                         }
4987
4988                         add_sid_to_token(&token->token, &sid);
4989                         continue;
4990                 }
4991
4992                 /* And a new user... */
4993
4994                 *num_tokens += 1;
4995                 *tokens = SMB_REALLOC_ARRAY(*tokens, struct user_token, *num_tokens);
4996                 if (*tokens == NULL) {
4997                         DEBUG(0, ("Could not realloc tokens\n"));
4998                         return false;
4999                 }
5000
5001                 token = &((*tokens)[*num_tokens-1]);
5002
5003                 if (strlcpy(token->name, line, sizeof(token->name)) >= sizeof(token->name)) {
5004                         return false;
5005                 }
5006                 token->token.num_sids = 0;
5007                 token->token.sids = NULL;
5008                 continue;
5009         }
5010
5011         return false;
5012 }
5013
5014
5015 /*
5016  * Show the list of all users that have access to a share
5017  */
5018
5019 static void show_userlist(struct rpc_pipe_client *pipe_hnd,
5020                         TALLOC_CTX *mem_ctx,
5021                         const char *netname,
5022                         int num_tokens,
5023                         struct user_token *tokens)
5024 {
5025         uint16_t fnum;
5026         struct security_descriptor *share_sd = NULL;
5027         struct security_descriptor *root_sd = NULL;
5028         struct cli_state *cli = rpc_pipe_np_smb_conn(pipe_hnd);
5029         int i;
5030         union srvsvc_NetShareInfo info;
5031         WERROR result;
5032         NTSTATUS status;
5033         uint16 cnum;
5034         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
5035
5036         status = dcerpc_srvsvc_NetShareGetInfo(b, mem_ctx,
5037                                                pipe_hnd->desthost,
5038                                                netname,
5039                                                502,
5040                                                &info,
5041                                                &result);
5042
5043         if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(result)) {
5044                 DEBUG(1, ("Coult not query secdesc for share %s\n",
5045                           netname));
5046                 return;
5047         }
5048
5049         share_sd = info.info502->sd_buf.sd;
5050         if (share_sd == NULL) {
5051                 DEBUG(1, ("Got no secdesc for share %s\n",
5052                           netname));
5053         }
5054
5055         cnum = cli_state_get_tid(cli);
5056
5057         if (!NT_STATUS_IS_OK(cli_tree_connect(cli, netname, "A:", "", 0))) {
5058                 return;
5059         }
5060
5061         if (!NT_STATUS_IS_OK(cli_ntcreate(cli, "\\", 0, READ_CONTROL_ACCESS, 0,
5062                         FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN, 0x0, 0x0, &fnum))) {
5063                 cli_query_secdesc(cli, fnum, mem_ctx, &root_sd);
5064         }
5065
5066         for (i=0; i<num_tokens; i++) {
5067                 uint32 acc_granted;
5068
5069                 if (share_sd != NULL) {
5070                         status = se_access_check(share_sd, &tokens[i].token,
5071                                              1, &acc_granted);
5072
5073                         if (!NT_STATUS_IS_OK(status)) {
5074                                 DEBUG(1, ("Could not check share_sd for "
5075                                           "user %s\n",
5076                                           tokens[i].name));
5077                                 continue;
5078                         }
5079                 }
5080
5081                 if (root_sd == NULL) {
5082                         d_printf(" %s\n", tokens[i].name);
5083                         continue;
5084                 }
5085
5086                 status = se_access_check(root_sd, &tokens[i].token,
5087                                      1, &acc_granted);
5088                 if (!NT_STATUS_IS_OK(status)) {
5089                         DEBUG(1, ("Could not check root_sd for user %s\n",
5090                                   tokens[i].name));
5091                         continue;
5092                 }
5093                 d_printf(" %s\n", tokens[i].name);
5094         }
5095
5096         if (fnum != (uint16_t)-1)
5097                 cli_close(cli, fnum);
5098         cli_tdis(cli);
5099         cli_state_set_tid(cli, cnum);
5100
5101         return;
5102 }
5103
5104 /**
5105  * List shares on a remote RPC server, including the security descriptors.
5106  *
5107  * All parameters are provided by the run_rpc_command function, except for
5108  * argc, argv which are passed through.
5109  *
5110  * @param domain_sid The domain sid acquired from the remote server.
5111  * @param cli A cli_state connected to the server.
5112  * @param mem_ctx Talloc context, destroyed on completion of the function.
5113  * @param argc  Standard main() style argc.
5114  * @param argv  Standard main() style argv. Initial components are already
5115  *              stripped.
5116  *
5117  * @return Normal NTSTATUS return.
5118  **/
5119
5120 static NTSTATUS rpc_share_allowedusers_internals(struct net_context *c,
5121                                                 const struct dom_sid *domain_sid,
5122                                                 const char *domain_name,
5123                                                 struct cli_state *cli,
5124                                                 struct rpc_pipe_client *pipe_hnd,
5125                                                 TALLOC_CTX *mem_ctx,
5126                                                 int argc,
5127                                                 const char **argv)
5128 {
5129         bool r;
5130         FILE *f;
5131         NTSTATUS nt_status = NT_STATUS_OK;
5132         uint32_t total_entries = 0;
5133         uint32_t resume_handle = 0;
5134         uint32_t preferred_len = 0xffffffff;
5135         uint32_t i;
5136         struct dcerpc_binding_handle *b = NULL;
5137         struct srvsvc_NetShareInfoCtr info_ctr;
5138         struct srvsvc_NetShareCtr1 ctr1;
5139         WERROR result;
5140
5141         struct user_token *tokens = NULL;
5142         int num_tokens = 0;
5143
5144         if (argc == 0) {
5145                 f = stdin;
5146         } else {
5147                 f = fopen(argv[0], "r");
5148         }
5149
5150         if (f == NULL) {
5151                 DEBUG(0, ("Could not open userlist: %s\n", strerror(errno)));
5152                 return NT_STATUS_UNSUCCESSFUL;
5153         }
5154
5155         r = get_user_tokens_from_file(f, &num_tokens, &tokens);
5156
5157         if (f != stdin)
5158                 fclose(f);
5159
5160         if (!r) {
5161                 DEBUG(0, ("Could not read users from file\n"));
5162                 return NT_STATUS_UNSUCCESSFUL;
5163         }
5164
5165         for (i=0; i<num_tokens; i++)
5166                 collect_alias_memberships(&tokens[i].token);
5167
5168         ZERO_STRUCT(info_ctr);
5169         ZERO_STRUCT(ctr1);
5170
5171         info_ctr.level = 1;
5172         info_ctr.ctr.ctr1 = &ctr1;
5173
5174         b = pipe_hnd->binding_handle;
5175
5176         /* Issue the NetShareEnum RPC call and retrieve the response */
5177         nt_status = dcerpc_srvsvc_NetShareEnumAll(b,
5178                                         talloc_tos(),
5179                                         pipe_hnd->desthost,
5180                                         &info_ctr,
5181                                         preferred_len,
5182                                         &total_entries,
5183                                         &resume_handle,
5184                                         &result);
5185
5186         /* Was it successful? */
5187         if (!NT_STATUS_IS_OK(nt_status)) {
5188                 /*  Nope.  Go clean up. */
5189                 goto done;
5190         }
5191
5192         if (!W_ERROR_IS_OK(result)) {
5193                 /*  Nope.  Go clean up. */
5194                 nt_status = werror_to_ntstatus(result);
5195                 goto done;
5196         }
5197
5198         if (total_entries == 0) {
5199                 goto done;
5200         }
5201
5202         /* For each returned entry... */
5203         for (i = 0; i < info_ctr.ctr.ctr1->count; i++) {
5204                 const char *netname = info_ctr.ctr.ctr1->array[i].name;
5205
5206                 if (info_ctr.ctr.ctr1->array[i].type != STYPE_DISKTREE) {
5207                         continue;
5208                 }
5209
5210                 d_printf("%s\n", netname);
5211
5212                 show_userlist(pipe_hnd, mem_ctx, netname,
5213                               num_tokens, tokens);
5214         }
5215  done:
5216         for (i=0; i<num_tokens; i++) {
5217                 free_user_token(&tokens[i].token);
5218         }
5219         SAFE_FREE(tokens);
5220
5221         return nt_status;
5222 }
5223
5224 static int rpc_share_allowedusers(struct net_context *c, int argc,
5225                                   const char **argv)
5226 {
5227         int result;
5228
5229         if (c->display_usage) {
5230                 d_printf(  "%s\n"
5231                            "net rpc share allowedusers\n"
5232                             "    %s\n",
5233                           _("Usage:"),
5234                           _("List allowed users"));
5235                 return 0;
5236         }
5237
5238         result = run_rpc_command(c, NULL, &ndr_table_samr, 0,
5239                                  rpc_aliaslist_internals,
5240                                  argc, argv);
5241         if (result != 0)
5242                 return result;
5243
5244         result = run_rpc_command(c, NULL, &ndr_table_lsarpc, 0,
5245                                  rpc_aliaslist_dump,
5246                                  argc, argv);
5247         if (result != 0)
5248                 return result;
5249
5250         return run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
5251                                rpc_share_allowedusers_internals,
5252                                argc, argv);
5253 }
5254
5255 int net_usersidlist(struct net_context *c, int argc, const char **argv)
5256 {
5257         int num_tokens = 0;
5258         struct user_token *tokens = NULL;
5259         int i;
5260
5261         if (argc != 0) {
5262                 net_usersidlist_usage(c, argc, argv);
5263                 return 0;
5264         }
5265
5266         if (!get_user_tokens(c, &num_tokens, &tokens)) {
5267                 DEBUG(0, ("Could not get the user/sid list\n"));
5268                 return -1;
5269         }
5270
5271         for (i=0; i<num_tokens; i++) {
5272                 dump_user_token(&tokens[i]);
5273                 free_user_token(&tokens[i].token);
5274         }
5275
5276         SAFE_FREE(tokens);
5277         return 0;
5278 }
5279
5280 int net_usersidlist_usage(struct net_context *c, int argc, const char **argv)
5281 {
5282         d_printf(_("net usersidlist\n"
5283                    "\tprints out a list of all users the running winbind knows\n"
5284                    "\tabout, together with all their SIDs. This is used as\n"
5285                    "\tinput to the 'net rpc share allowedusers' command.\n\n"));
5286
5287         net_common_flags_usage(c, argc, argv);
5288         return -1;
5289 }
5290
5291 /**
5292  * 'net rpc share' entrypoint.
5293  * @param argc  Standard main() style argc.
5294  * @param argv  Standard main() style argv. Initial components are already
5295  *              stripped.
5296  **/
5297
5298 int net_rpc_share(struct net_context *c, int argc, const char **argv)
5299 {
5300         NET_API_STATUS status;
5301
5302         struct functable func[] = {
5303                 {
5304                         "add",
5305                         rpc_share_add,
5306                         NET_TRANSPORT_RPC,
5307                         N_("Add share"),
5308                         N_("net rpc share add\n"
5309                            "    Add share")
5310                 },
5311                 {
5312                         "delete",
5313                         rpc_share_delete,
5314                         NET_TRANSPORT_RPC,
5315                         N_("Remove share"),
5316                         N_("net rpc share delete\n"
5317                            "    Remove share")
5318                 },
5319                 {
5320                         "allowedusers",
5321                         rpc_share_allowedusers,
5322                         NET_TRANSPORT_RPC,
5323                         N_("Modify allowed users"),
5324                         N_("net rpc share allowedusers\n"
5325                            "    Modify allowed users")
5326                 },
5327                 {
5328                         "migrate",
5329                         rpc_share_migrate,
5330                         NET_TRANSPORT_RPC,
5331                         N_("Migrate share to local server"),
5332                         N_("net rpc share migrate\n"
5333                            "    Migrate share to local server")
5334                 },
5335                 {
5336                         "list",
5337                         rpc_share_list,
5338                         NET_TRANSPORT_RPC,
5339                         N_("List shares"),
5340                         N_("net rpc share list\n"
5341                            "    List shares")
5342                 },
5343                 {NULL, NULL, 0, NULL, NULL}
5344         };
5345
5346         status = libnetapi_net_init(&c->netapi_ctx);
5347         if (status != 0) {
5348                 return -1;
5349         }
5350         libnetapi_set_username(c->netapi_ctx, c->opt_user_name);
5351         libnetapi_set_password(c->netapi_ctx, c->opt_password);
5352         if (c->opt_kerberos) {
5353                 libnetapi_set_use_kerberos(c->netapi_ctx);
5354         }
5355
5356         if (argc == 0) {
5357                 if (c->display_usage) {
5358                         d_printf("%s\n%s",
5359                                  _("Usage:"),
5360                                  _("net rpc share\n"
5361                                    "    List shares\n"
5362                                    "    Alias for net rpc share list\n"));
5363                         net_display_usage_from_functable(func);
5364                         return 0;
5365                 }
5366
5367                 return rpc_share_list(c, argc, argv);
5368         }
5369
5370         return net_run_function(c, argc, argv, "net rpc share", func);
5371 }
5372
5373 static NTSTATUS rpc_sh_share_list(struct net_context *c,
5374                                   TALLOC_CTX *mem_ctx,
5375                                   struct rpc_sh_ctx *ctx,
5376                                   struct rpc_pipe_client *pipe_hnd,
5377                                   int argc, const char **argv)
5378 {
5379
5380         return werror_to_ntstatus(W_ERROR(rpc_share_list(c, argc, argv)));
5381 }
5382
5383 static NTSTATUS rpc_sh_share_add(struct net_context *c,
5384                                  TALLOC_CTX *mem_ctx,
5385                                  struct rpc_sh_ctx *ctx,
5386                                  struct rpc_pipe_client *pipe_hnd,
5387                                  int argc, const char **argv)
5388 {
5389         NET_API_STATUS status;
5390         uint32_t parm_err = 0;
5391         struct SHARE_INFO_2 i2;
5392
5393         if ((argc < 2) || (argc > 3)) {
5394                 d_fprintf(stderr, _("Usage: %s <share> <path> [comment]\n"),
5395                           ctx->whoami);
5396                 return NT_STATUS_INVALID_PARAMETER;
5397         }
5398
5399         i2.shi2_netname         = argv[0];
5400         i2.shi2_type            = STYPE_DISKTREE;
5401         i2.shi2_remark          = (argc == 3) ? argv[2] : "";
5402         i2.shi2_permissions     = 0;
5403         i2.shi2_max_uses        = 0;
5404         i2.shi2_current_uses    = 0;
5405         i2.shi2_path            = argv[1];
5406         i2.shi2_passwd          = NULL;
5407
5408         status = NetShareAdd(pipe_hnd->desthost,
5409                              2,
5410                              (uint8_t *)&i2,
5411                              &parm_err);
5412
5413         return werror_to_ntstatus(W_ERROR(status));
5414 }
5415
5416 static NTSTATUS rpc_sh_share_delete(struct net_context *c,
5417                                     TALLOC_CTX *mem_ctx,
5418                                     struct rpc_sh_ctx *ctx,
5419                                     struct rpc_pipe_client *pipe_hnd,
5420                                     int argc, const char **argv)
5421 {
5422         if (argc != 1) {
5423                 d_fprintf(stderr, "%s %s <share>\n", _("Usage:"), ctx->whoami);
5424                 return NT_STATUS_INVALID_PARAMETER;
5425         }
5426
5427         return werror_to_ntstatus(W_ERROR(NetShareDel(pipe_hnd->desthost, argv[0], 0)));
5428 }
5429
5430 static NTSTATUS rpc_sh_share_info(struct net_context *c,
5431                                   TALLOC_CTX *mem_ctx,
5432                                   struct rpc_sh_ctx *ctx,
5433                                   struct rpc_pipe_client *pipe_hnd,
5434                                   int argc, const char **argv)
5435 {
5436         union srvsvc_NetShareInfo info;
5437         WERROR result;
5438         NTSTATUS status;
5439         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
5440
5441         if (argc != 1) {
5442                 d_fprintf(stderr, "%s %s <share>\n", _("Usage:"), ctx->whoami);
5443                 return NT_STATUS_INVALID_PARAMETER;
5444         }
5445
5446         status = dcerpc_srvsvc_NetShareGetInfo(b, mem_ctx,
5447                                                pipe_hnd->desthost,
5448                                                argv[0],
5449                                                2,
5450                                                &info,
5451                                                &result);
5452         if (!NT_STATUS_IS_OK(status)) {
5453                 result = ntstatus_to_werror(status);
5454                 goto done;
5455         }
5456         if (!W_ERROR_IS_OK(result)) {
5457                 goto done;
5458         }
5459
5460         d_printf(_("Name:     %s\n"), info.info2->name);
5461         d_printf(_("Comment:  %s\n"), info.info2->comment);
5462         d_printf(_("Path:     %s\n"), info.info2->path);
5463         d_printf(_("Password: %s\n"), info.info2->password);
5464
5465  done:
5466         return werror_to_ntstatus(result);
5467 }
5468
5469 struct rpc_sh_cmd *net_rpc_share_cmds(struct net_context *c, TALLOC_CTX *mem_ctx,
5470                                       struct rpc_sh_ctx *ctx)
5471 {
5472         static struct rpc_sh_cmd cmds[] = {
5473
5474         { "list", NULL, &ndr_table_srvsvc, rpc_sh_share_list,
5475           N_("List available shares") },
5476
5477         { "add", NULL, &ndr_table_srvsvc, rpc_sh_share_add,
5478           N_("Add a share") },
5479
5480         { "delete", NULL, &ndr_table_srvsvc, rpc_sh_share_delete,
5481           N_("Delete a share") },
5482
5483         { "info", NULL, &ndr_table_srvsvc, rpc_sh_share_info,
5484           N_("Get information about a share") },
5485
5486         { NULL, NULL, 0, NULL, NULL }
5487         };
5488
5489         return cmds;
5490 }
5491
5492 /****************************************************************************/
5493
5494 static int rpc_file_usage(struct net_context *c, int argc, const char **argv)
5495 {
5496         return net_file_usage(c, argc, argv);
5497 }
5498
5499 /**
5500  * Close a file on a remote RPC server.
5501  *
5502  * @param argc  Standard main() style argc.
5503  * @param argv  Standard main() style argv. Initial components are already
5504  *              stripped.
5505  *
5506  * @return A shell status integer (0 for success).
5507  **/
5508 static int rpc_file_close(struct net_context *c, int argc, const char **argv)
5509 {
5510         if (argc < 1 || c->display_usage) {
5511                 return rpc_file_usage(c, argc, argv);
5512         }
5513
5514         return NetFileClose(c->opt_host, atoi(argv[0]));
5515 }
5516
5517 /**
5518  * Formatted print of open file info
5519  *
5520  * @param r  struct FILE_INFO_3 contents
5521  **/
5522
5523 static void display_file_info_3(struct FILE_INFO_3 *r)
5524 {
5525         d_printf("%-7.1d %-20.20s 0x%-4.2x %-6.1d %s\n",
5526                  r->fi3_id, r->fi3_username, r->fi3_permissions,
5527                  r->fi3_num_locks, r->fi3_pathname);
5528 }
5529
5530 /**
5531  * List files for a user on a remote RPC server.
5532  *
5533  * @param argc  Standard main() style argc.
5534  * @param argv  Standard main() style argv. Initial components are already
5535  *              stripped.
5536  *
5537  * @return A shell status integer (0 for success)..
5538  **/
5539
5540 static int rpc_file_user(struct net_context *c, int argc, const char **argv)
5541 {
5542         NET_API_STATUS status;
5543         uint32 preferred_len = 0xffffffff, i;
5544         char *username=NULL;
5545         uint32_t total_entries = 0;
5546         uint32_t entries_read = 0;
5547         uint32_t resume_handle = 0;
5548         struct FILE_INFO_3 *i3 = NULL;
5549
5550         if (c->display_usage) {
5551                 return rpc_file_usage(c, argc, argv);
5552         }
5553
5554         /* if argc > 0, must be user command */
5555         if (argc > 0) {
5556                 username = smb_xstrdup(argv[0]);
5557         }
5558
5559         status = NetFileEnum(c->opt_host,
5560                              NULL,
5561                              username,
5562                              3,
5563                              (uint8_t **)(void *)&i3,
5564                              preferred_len,
5565                              &entries_read,
5566                              &total_entries,
5567                              &resume_handle);
5568
5569         if (status != 0) {
5570                 goto done;
5571         }
5572
5573         /* Display results */
5574
5575         d_printf(_(
5576                  "\nEnumerating open files on remote server:\n\n"
5577                  "\nFileId  Opened by            Perms  Locks  Path"
5578                  "\n------  ---------            -----  -----  ---- \n"));
5579         for (i = 0; i < entries_read; i++) {
5580                 display_file_info_3(&i3[i]);
5581         }
5582  done:
5583         SAFE_FREE(username);
5584         return status;
5585 }
5586
5587 /**
5588  * 'net rpc file' entrypoint.
5589  * @param argc  Standard main() style argc.
5590  * @param argv  Standard main() style argv. Initial components are already
5591  *              stripped.
5592  **/
5593
5594 int net_rpc_file(struct net_context *c, int argc, const char **argv)
5595 {
5596         NET_API_STATUS status;
5597
5598         struct functable func[] = {
5599                 {
5600                         "close",
5601                         rpc_file_close,
5602                         NET_TRANSPORT_RPC,
5603                         N_("Close opened file"),
5604                         N_("net rpc file close\n"
5605                            "    Close opened file")
5606                 },
5607                 {
5608                         "user",
5609                         rpc_file_user,
5610                         NET_TRANSPORT_RPC,
5611                         N_("List files opened by user"),
5612                         N_("net rpc file user\n"
5613                            "    List files opened by user")
5614                 },
5615 #if 0
5616                 {
5617                         "info",
5618                         rpc_file_info,
5619                         NET_TRANSPORT_RPC,
5620                         N_("Display information about opened file"),
5621                         N_("net rpc file info\n"
5622                            "    Display information about opened file")
5623                 },
5624 #endif
5625                 {NULL, NULL, 0, NULL, NULL}
5626         };
5627
5628         status = libnetapi_net_init(&c->netapi_ctx);
5629         if (status != 0) {
5630                 return -1;
5631         }
5632         libnetapi_set_username(c->netapi_ctx, c->opt_user_name);
5633         libnetapi_set_password(c->netapi_ctx, c->opt_password);
5634         if (c->opt_kerberos) {
5635                 libnetapi_set_use_kerberos(c->netapi_ctx);
5636         }
5637
5638         if (argc == 0) {
5639                 if (c->display_usage) {
5640                         d_printf(_("Usage:\n"));
5641                         d_printf(_("net rpc file\n"
5642                                    "    List opened files\n"));
5643                         net_display_usage_from_functable(func);
5644                         return 0;
5645                 }
5646
5647                 return rpc_file_user(c, argc, argv);
5648         }
5649
5650         return net_run_function(c, argc, argv, "net rpc file", func);
5651 }
5652
5653 /**
5654  * ABORT the shutdown of a remote RPC Server, over initshutdown pipe.
5655  *
5656  * All parameters are provided by the run_rpc_command function, except for
5657  * argc, argv which are passed through.
5658  *
5659  * @param c     A net_context structure.
5660  * @param domain_sid The domain sid acquired from the remote server.
5661  * @param cli A cli_state connected to the server.
5662  * @param mem_ctx Talloc context, destroyed on completion of the function.
5663  * @param argc  Standard main() style argc.
5664  * @param argv  Standard main() style argv. Initial components are already
5665  *              stripped.
5666  *
5667  * @return Normal NTSTATUS return.
5668  **/
5669
5670 static NTSTATUS rpc_shutdown_abort_internals(struct net_context *c,
5671                                         const struct dom_sid *domain_sid,
5672                                         const char *domain_name,
5673                                         struct cli_state *cli,
5674                                         struct rpc_pipe_client *pipe_hnd,
5675                                         TALLOC_CTX *mem_ctx,
5676                                         int argc,
5677                                         const char **argv)
5678 {
5679         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
5680         WERROR result;
5681         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
5682
5683         status = dcerpc_initshutdown_Abort(b, mem_ctx, NULL, &result);
5684         if (!NT_STATUS_IS_OK(status)) {
5685                 return status;
5686         }
5687         if (W_ERROR_IS_OK(result)) {
5688                 d_printf(_("\nShutdown successfully aborted\n"));
5689                 DEBUG(5,("cmd_shutdown_abort: query succeeded\n"));
5690         } else
5691                 DEBUG(5,("cmd_shutdown_abort: query failed\n"));
5692
5693         return werror_to_ntstatus(result);
5694 }
5695
5696 /**
5697  * ABORT the shutdown of a remote RPC Server, over winreg pipe.
5698  *
5699  * All parameters are provided by the run_rpc_command function, except for
5700  * argc, argv which are passed through.
5701  *
5702  * @param c     A net_context structure.
5703  * @param domain_sid The domain sid acquired from the remote server.
5704  * @param cli A cli_state connected to the server.
5705  * @param mem_ctx Talloc context, destroyed on completion of the function.
5706  * @param argc  Standard main() style argc.
5707  * @param argv  Standard main() style argv. Initial components are already
5708  *              stripped.
5709  *
5710  * @return Normal NTSTATUS return.
5711  **/
5712
5713 static NTSTATUS rpc_reg_shutdown_abort_internals(struct net_context *c,
5714                                                 const struct dom_sid *domain_sid,
5715                                                 const char *domain_name,
5716                                                 struct cli_state *cli,
5717                                                 struct rpc_pipe_client *pipe_hnd,
5718                                                 TALLOC_CTX *mem_ctx,
5719                                                 int argc,
5720                                                 const char **argv)
5721 {
5722         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
5723         WERROR werr;
5724         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
5725
5726         result = dcerpc_winreg_AbortSystemShutdown(b, mem_ctx, NULL, &werr);
5727
5728         if (!NT_STATUS_IS_OK(result)) {
5729                 DEBUG(5,("cmd_reg_abort_shutdown: query failed\n"));
5730                 return result;
5731         }
5732         if (W_ERROR_IS_OK(werr)) {
5733                 d_printf(_("\nShutdown successfully aborted\n"));
5734                 DEBUG(5,("cmd_reg_abort_shutdown: query succeeded\n"));
5735         } else
5736                 DEBUG(5,("cmd_reg_abort_shutdown: query failed\n"));
5737
5738         return werror_to_ntstatus(werr);
5739 }
5740
5741 /**
5742  * ABORT the shutdown of a remote RPC server.
5743  *
5744  * @param argc  Standard main() style argc.
5745  * @param argv  Standard main() style argv. Initial components are already
5746  *              stripped.
5747  *
5748  * @return A shell status integer (0 for success).
5749  **/
5750
5751 static int rpc_shutdown_abort(struct net_context *c, int argc,
5752                               const char **argv)
5753 {
5754         int rc = -1;
5755
5756         if (c->display_usage) {
5757                 d_printf(  "%s\n"
5758                            "net rpc abortshutdown\n"
5759                            "    %s\n",
5760                          _("Usage:"),
5761                          _("Abort a scheduled shutdown"));
5762                 return 0;
5763         }
5764
5765         rc = run_rpc_command(c, NULL, &ndr_table_initshutdown, 0,
5766                              rpc_shutdown_abort_internals, argc, argv);
5767
5768         if (rc == 0)
5769                 return rc;
5770
5771         DEBUG(1, ("initshutdown pipe didn't work, trying winreg pipe\n"));
5772
5773         return run_rpc_command(c, NULL, &ndr_table_winreg, 0,
5774                                rpc_reg_shutdown_abort_internals,
5775                                argc, argv);
5776 }
5777
5778 /**
5779  * Shut down a remote RPC Server via initshutdown pipe.
5780  *
5781  * All parameters are provided by the run_rpc_command function, except for
5782  * argc, argv which are passed through.
5783  *
5784  * @param c     A net_context structure.
5785  * @param domain_sid The domain sid acquired from the remote server.
5786  * @param cli A cli_state connected to the server.
5787  * @param mem_ctx Talloc context, destroyed on completion of the function.
5788  * @param argc  Standard main() style argc.
5789  * @param argv  Standard main() style argv. Initial components are already
5790  *              stripped.
5791  *
5792  * @return Normal NTSTATUS return.
5793  **/
5794
5795 NTSTATUS rpc_init_shutdown_internals(struct net_context *c,
5796                                      const struct dom_sid *domain_sid,
5797                                      const char *domain_name,
5798                                      struct cli_state *cli,
5799                                      struct rpc_pipe_client *pipe_hnd,
5800                                      TALLOC_CTX *mem_ctx,
5801                                      int argc,
5802                                      const char **argv)
5803 {
5804         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
5805         WERROR result;
5806         const char *msg = N_("This machine will be shutdown shortly");
5807         uint32 timeout = 20;
5808         struct lsa_StringLarge msg_string;
5809         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
5810
5811         if (c->opt_comment) {
5812                 msg = c->opt_comment;
5813         }
5814         if (c->opt_timeout) {
5815                 timeout = c->opt_timeout;
5816         }
5817
5818         msg_string.string = msg;
5819
5820         /* create an entry */
5821         status = dcerpc_initshutdown_Init(b, mem_ctx, NULL,
5822                         &msg_string, timeout, c->opt_force, c->opt_reboot,
5823                         &result);
5824         if (!NT_STATUS_IS_OK(status)) {
5825                 return status;
5826         }
5827         if (W_ERROR_IS_OK(result)) {
5828                 d_printf(_("\nShutdown of remote machine succeeded\n"));
5829                 DEBUG(5,("Shutdown of remote machine succeeded\n"));
5830         } else {
5831                 DEBUG(1,("Shutdown of remote machine failed!\n"));
5832         }
5833         return werror_to_ntstatus(result);
5834 }
5835
5836 /**
5837  * Shut down a remote RPC Server via winreg pipe.
5838  *
5839  * All parameters are provided by the run_rpc_command function, except for
5840  * argc, argv which are passed through.
5841  *
5842  * @param c     A net_context structure.
5843  * @param domain_sid The domain sid acquired from the remote server.
5844  * @param cli A cli_state connected to the server.
5845  * @param mem_ctx Talloc context, destroyed on completion of the function.
5846  * @param argc  Standard main() style argc.
5847  * @param argv  Standard main() style argv. Initial components are already
5848  *              stripped.
5849  *
5850  * @return Normal NTSTATUS return.
5851  **/
5852
5853 NTSTATUS rpc_reg_shutdown_internals(struct net_context *c,
5854                                     const struct dom_sid *domain_sid,
5855                                     const char *domain_name,
5856                                     struct cli_state *cli,
5857                                     struct rpc_pipe_client *pipe_hnd,
5858                                     TALLOC_CTX *mem_ctx,
5859                                     int argc,
5860                                     const char **argv)
5861 {
5862         const char *msg = N_("This machine will be shutdown shortly");
5863         uint32 timeout = 20;
5864         struct lsa_StringLarge msg_string;
5865         NTSTATUS result;
5866         WERROR werr;
5867         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
5868
5869         if (c->opt_comment) {
5870                 msg = c->opt_comment;
5871         }
5872         msg_string.string = msg;
5873
5874         if (c->opt_timeout) {
5875                 timeout = c->opt_timeout;
5876         }
5877
5878         /* create an entry */
5879         result = dcerpc_winreg_InitiateSystemShutdown(b, mem_ctx, NULL,
5880                         &msg_string, timeout, c->opt_force, c->opt_reboot,
5881                         &werr);
5882         if (!NT_STATUS_IS_OK(result)) {
5883                 d_fprintf(stderr, "\nShutdown of remote machine failed\n");
5884                 return result;
5885         }
5886
5887         if (W_ERROR_IS_OK(werr)) {
5888                 d_printf(_("\nShutdown of remote machine succeeded\n"));
5889         } else {
5890                 d_fprintf(stderr, "\nShutdown of remote machine failed\n");
5891                 if ( W_ERROR_EQUAL(werr, WERR_MACHINE_LOCKED) )
5892                         d_fprintf(stderr, "\nMachine locked, use -f switch to force\n");
5893                 else
5894                         d_fprintf(stderr, "\nresult was: %s\n", win_errstr(werr));
5895         }
5896
5897         return werror_to_ntstatus(werr);
5898 }
5899
5900 /**
5901  * Shut down a remote RPC server.
5902  *
5903  * @param argc  Standard main() style argc.
5904  * @param argv  Standard main() style argv. Initial components are already
5905  *              stripped.
5906  *
5907  * @return A shell status integer (0 for success).
5908  **/
5909
5910 static int rpc_shutdown(struct net_context *c, int argc, const char **argv)
5911 {
5912         int rc =  -1;
5913
5914         if (c->display_usage) {
5915                 d_printf(  "%s\n"
5916                            "net rpc shutdown\n"
5917                            "    %s\n",
5918                          _("Usage:"),
5919                          _("Shut down a remote RPC server"));
5920                 return 0;
5921         }
5922
5923         rc = run_rpc_command(c, NULL, &ndr_table_initshutdown, 0,
5924                              rpc_init_shutdown_internals, argc, argv);
5925
5926         if (rc) {
5927                 DEBUG(1, ("initshutdown pipe failed, trying winreg pipe\n"));
5928                 rc = run_rpc_command(c, NULL, &ndr_table_winreg, 0,
5929                                      rpc_reg_shutdown_internals, argc, argv);
5930         }
5931
5932         return rc;
5933 }
5934
5935 /***************************************************************************
5936   NT Domain trusts code (i.e. 'net rpc trustdom' functionality)
5937  ***************************************************************************/
5938
5939 /**
5940  * Add interdomain trust account to the RPC server.
5941  * All parameters (except for argc and argv) are passed by run_rpc_command
5942  * function.
5943  *
5944  * @param c     A net_context structure.
5945  * @param domain_sid The domain sid acquired from the server.
5946  * @param cli A cli_state connected to the server.
5947  * @param mem_ctx Talloc context, destroyed on completion of the function.
5948  * @param argc  Standard main() style argc.
5949  * @param argv  Standard main() style argv. Initial components are already
5950  *              stripped.
5951  *
5952  * @return normal NTSTATUS return code.
5953  */
5954
5955 static NTSTATUS rpc_trustdom_add_internals(struct net_context *c,
5956                                                 const struct dom_sid *domain_sid,
5957                                                 const char *domain_name,
5958                                                 struct cli_state *cli,
5959                                                 struct rpc_pipe_client *pipe_hnd,
5960                                                 TALLOC_CTX *mem_ctx,
5961                                                 int argc,
5962                                                 const char **argv)
5963 {
5964         struct policy_handle connect_pol, domain_pol, user_pol;
5965         NTSTATUS status, result;
5966         char *acct_name;
5967         struct lsa_String lsa_acct_name;
5968         uint32 acb_info;
5969         uint32 acct_flags=0;
5970         uint32 user_rid;
5971         uint32_t access_granted = 0;
5972         union samr_UserInfo info;
5973         unsigned int orig_timeout;
5974         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
5975         DATA_BLOB session_key = data_blob_null;
5976
5977         if (argc != 2) {
5978                 d_printf("%s\n%s",
5979                          _("Usage:"),
5980                          _(" net rpc trustdom add <domain_name> "
5981                            "<trust password>\n"));
5982                 return NT_STATUS_INVALID_PARAMETER;
5983         }
5984
5985         /*
5986          * Make valid trusting domain account (ie. uppercased and with '$' appended)
5987          */
5988
5989         if (asprintf(&acct_name, "%s$", argv[0]) < 0) {
5990                 return NT_STATUS_NO_MEMORY;
5991         }
5992
5993         if (!strupper_m(acct_name)) {
5994                 SAFE_FREE(acct_name);
5995                 return NT_STATUS_INVALID_PARAMETER;
5996         }
5997
5998         init_lsa_String(&lsa_acct_name, acct_name);
5999
6000         status = cli_get_session_key(mem_ctx, pipe_hnd, &session_key);
6001         if (!NT_STATUS_IS_OK(status)) {
6002                 DEBUG(0,("Error getting session_key of SAM pipe. Error was %s\n",
6003                         nt_errstr(status)));
6004                 goto done;
6005         }
6006
6007         /* Get samr policy handle */
6008         status = dcerpc_samr_Connect2(b, mem_ctx,
6009                                       pipe_hnd->desthost,
6010                                       MAXIMUM_ALLOWED_ACCESS,
6011                                       &connect_pol,
6012                                       &result);
6013         if (!NT_STATUS_IS_OK(status)) {
6014                 goto done;
6015         }
6016         if (!NT_STATUS_IS_OK(result)) {
6017                 status = result;
6018                 goto done;
6019         }
6020
6021         /* Get domain policy handle */
6022         status = dcerpc_samr_OpenDomain(b, mem_ctx,
6023                                         &connect_pol,
6024                                         MAXIMUM_ALLOWED_ACCESS,
6025                                         discard_const_p(struct dom_sid2, domain_sid),
6026                                         &domain_pol,
6027                                         &result);
6028         if (!NT_STATUS_IS_OK(status)) {
6029                 goto done;
6030         }
6031         if (!NT_STATUS_IS_OK(result)) {
6032                 status = result;
6033                 goto done;
6034         }
6035
6036         /* This call can take a long time - allow the server to time out.
6037          * 35 seconds should do it. */
6038
6039         orig_timeout = rpccli_set_timeout(pipe_hnd, 35000);
6040
6041         /* Create trusting domain's account */
6042         acb_info = ACB_NORMAL;
6043         acct_flags = SEC_GENERIC_READ | SEC_GENERIC_WRITE | SEC_GENERIC_EXECUTE |
6044                      SEC_STD_WRITE_DAC | SEC_STD_DELETE |
6045                      SAMR_USER_ACCESS_SET_PASSWORD |
6046                      SAMR_USER_ACCESS_GET_ATTRIBUTES |
6047                      SAMR_USER_ACCESS_SET_ATTRIBUTES;
6048
6049         status = dcerpc_samr_CreateUser2(b, mem_ctx,
6050                                          &domain_pol,
6051                                          &lsa_acct_name,
6052                                          acb_info,
6053                                          acct_flags,
6054                                          &user_pol,
6055                                          &access_granted,
6056                                          &user_rid,
6057                                          &result);
6058         if (!NT_STATUS_IS_OK(status)) {
6059                 goto done;
6060         }
6061         /* And restore our original timeout. */
6062         rpccli_set_timeout(pipe_hnd, orig_timeout);
6063
6064         if (!NT_STATUS_IS_OK(result)) {
6065                 status = result;
6066                 d_printf(_("net rpc trustdom add: create user %s failed %s\n"),
6067                         acct_name, nt_errstr(result));
6068                 goto done;
6069         }
6070
6071         {
6072                 struct samr_CryptPassword crypt_pwd;
6073
6074                 ZERO_STRUCT(info.info23);
6075
6076                 init_samr_CryptPassword(argv[1],
6077                                         &session_key,
6078                                         &crypt_pwd);
6079
6080                 info.info23.info.fields_present = SAMR_FIELD_ACCT_FLAGS |
6081                                                   SAMR_FIELD_NT_PASSWORD_PRESENT;
6082                 info.info23.info.acct_flags = ACB_DOMTRUST;
6083                 info.info23.password = crypt_pwd;
6084
6085                 status = dcerpc_samr_SetUserInfo2(b, mem_ctx,
6086                                                   &user_pol,
6087                                                   23,
6088                                                   &info,
6089                                                   &result);
6090                 if (!NT_STATUS_IS_OK(status)) {
6091                         goto done;
6092                 }
6093
6094                 if (!NT_STATUS_IS_OK(result)) {
6095                         status = result;
6096                         DEBUG(0,("Could not set trust account password: %s\n",
6097                                  nt_errstr(result)));
6098                         goto done;
6099                 }
6100         }
6101
6102  done:
6103         SAFE_FREE(acct_name);
6104         data_blob_clear_free(&session_key);
6105         return status;
6106 }
6107
6108 /**
6109  * Create interdomain trust account for a remote domain.
6110  *
6111  * @param argc Standard argc.
6112  * @param argv Standard argv without initial components.
6113  *
6114  * @return Integer status (0 means success).
6115  **/
6116
6117 static int rpc_trustdom_add(struct net_context *c, int argc, const char **argv)
6118 {
6119         if (argc > 0 && !c->display_usage) {
6120                 return run_rpc_command(c, NULL, &ndr_table_samr, 0,
6121                                        rpc_trustdom_add_internals, argc, argv);
6122         } else {
6123                 d_printf("%s\n%s",
6124                          _("Usage:"),
6125                          _("net rpc trustdom add <domain_name> <trust "
6126                            "password>\n"));
6127                 return -1;
6128         }
6129 }
6130
6131
6132 /**
6133  * Remove interdomain trust account from the RPC server.
6134  * All parameters (except for argc and argv) are passed by run_rpc_command
6135  * function.
6136  *
6137  * @param c     A net_context structure.
6138  * @param domain_sid The domain sid acquired from the server.
6139  * @param cli A cli_state connected to the server.
6140  * @param mem_ctx Talloc context, destroyed on completion of the function.
6141  * @param argc  Standard main() style argc.
6142  * @param argv  Standard main() style argv. Initial components are already
6143  *              stripped.
6144  *
6145  * @return normal NTSTATUS return code.
6146  */
6147
6148 static NTSTATUS rpc_trustdom_del_internals(struct net_context *c,
6149                                         const struct dom_sid *domain_sid,
6150                                         const char *domain_name,
6151                                         struct cli_state *cli,
6152                                         struct rpc_pipe_client *pipe_hnd,
6153                                         TALLOC_CTX *mem_ctx,
6154                                         int argc,
6155                                         const char **argv)
6156 {
6157         struct policy_handle connect_pol, domain_pol, user_pol;
6158         NTSTATUS status, result;
6159         char *acct_name;
6160         struct dom_sid trust_acct_sid;
6161         struct samr_Ids user_rids, name_types;
6162         struct lsa_String lsa_acct_name;
6163         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
6164
6165         if (argc != 1) {
6166                 d_printf("%s\n%s",
6167                          _("Usage:"),
6168                          _(" net rpc trustdom del <domain_name>\n"));
6169                 return NT_STATUS_INVALID_PARAMETER;
6170         }
6171
6172         /*
6173          * Make valid trusting domain account (ie. uppercased and with '$' appended)
6174          */
6175         acct_name = talloc_asprintf(mem_ctx, "%s$", argv[0]);
6176
6177         if (acct_name == NULL)
6178                 return NT_STATUS_NO_MEMORY;
6179
6180         if (!strupper_m(acct_name)) {
6181                 TALLOC_FREE(acct_name);
6182                 return NT_STATUS_INVALID_PARAMETER;
6183         }
6184
6185         /* Get samr policy handle */
6186         status = dcerpc_samr_Connect2(b, mem_ctx,
6187                                       pipe_hnd->desthost,
6188                                       MAXIMUM_ALLOWED_ACCESS,
6189                                       &connect_pol,
6190                                       &result);
6191         if (!NT_STATUS_IS_OK(status)) {
6192                 goto done;
6193         }
6194         if (!NT_STATUS_IS_OK(result)) {
6195                 status = result;
6196                 goto done;
6197         }
6198
6199         /* Get domain policy handle */
6200         status = dcerpc_samr_OpenDomain(b, mem_ctx,
6201                                         &connect_pol,
6202                                         MAXIMUM_ALLOWED_ACCESS,
6203                                         discard_const_p(struct dom_sid2, domain_sid),
6204                                         &domain_pol,
6205                                         &result);
6206         if (!NT_STATUS_IS_OK(status)) {
6207                 goto done;
6208         }
6209         if (!NT_STATUS_IS_OK(result)) {
6210                 status = result;
6211                 goto done;
6212         }
6213
6214         init_lsa_String(&lsa_acct_name, acct_name);
6215
6216         status = dcerpc_samr_LookupNames(b, mem_ctx,
6217                                          &domain_pol,
6218                                          1,
6219                                          &lsa_acct_name,
6220                                          &user_rids,
6221                                          &name_types,
6222                                          &result);
6223         if (!NT_STATUS_IS_OK(status)) {
6224                 d_printf(_("net rpc trustdom del: LookupNames on user %s "
6225                            "failed %s\n"),
6226                         acct_name, nt_errstr(status));
6227                 goto done;
6228         }
6229         if (!NT_STATUS_IS_OK(result)) {
6230                 status = result;
6231                 d_printf(_("net rpc trustdom del: LookupNames on user %s "
6232                            "failed %s\n"),
6233                         acct_name, nt_errstr(result) );
6234                 goto done;
6235         }
6236
6237         status = dcerpc_samr_OpenUser(b, mem_ctx,
6238                                       &domain_pol,
6239                                       MAXIMUM_ALLOWED_ACCESS,
6240                                       user_rids.ids[0],
6241                                       &user_pol,
6242                                       &result);
6243         if (!NT_STATUS_IS_OK(status)) {
6244                 d_printf(_("net rpc trustdom del: OpenUser on user %s failed "
6245                            "%s\n"),
6246                         acct_name, nt_errstr(status) );
6247                 goto done;
6248         }
6249
6250         if (!NT_STATUS_IS_OK(result)) {
6251                 status = result;
6252                 d_printf(_("net rpc trustdom del: OpenUser on user %s failed "
6253                            "%s\n"),
6254                         acct_name, nt_errstr(result) );
6255                 goto done;
6256         }
6257
6258         /* append the rid to the domain sid */
6259         if (!sid_compose(&trust_acct_sid, domain_sid, user_rids.ids[0])) {
6260                 goto done;
6261         }
6262
6263         /* remove the sid */
6264
6265         status = dcerpc_samr_RemoveMemberFromForeignDomain(b, mem_ctx,
6266                                                            &user_pol,
6267                                                            &trust_acct_sid,
6268                                                            &result);
6269         if (!NT_STATUS_IS_OK(status)) {
6270                 d_printf(_("net rpc trustdom del: RemoveMemberFromForeignDomain"
6271                            " on user %s failed %s\n"),
6272                         acct_name, nt_errstr(status));
6273                 goto done;
6274         }
6275         if (!NT_STATUS_IS_OK(result)) {
6276                 status = result;
6277                 d_printf(_("net rpc trustdom del: RemoveMemberFromForeignDomain"
6278                            " on user %s failed %s\n"),
6279                         acct_name, nt_errstr(result) );
6280                 goto done;
6281         }
6282
6283
6284         /* Delete user */
6285
6286         status = dcerpc_samr_DeleteUser(b, mem_ctx,
6287                                         &user_pol,
6288                                         &result);
6289         if (!NT_STATUS_IS_OK(status)) {
6290                 d_printf(_("net rpc trustdom del: DeleteUser on user %s failed "
6291                            "%s\n"),
6292                         acct_name, nt_errstr(status));
6293                 goto done;
6294         }
6295
6296         if (!NT_STATUS_IS_OK(result)) {
6297                 result = status;
6298                 d_printf(_("net rpc trustdom del: DeleteUser on user %s failed "
6299                            "%s\n"),
6300                         acct_name, nt_errstr(result) );
6301                 goto done;
6302         }
6303
6304         if (!NT_STATUS_IS_OK(result)) {
6305                 d_printf(_("Could not set trust account password: %s\n"),
6306                    nt_errstr(result));
6307                 goto done;
6308         }
6309
6310  done:
6311         return status;
6312 }
6313
6314 /**
6315  * Delete interdomain trust account for a remote domain.
6316  *
6317  * @param argc Standard argc.
6318  * @param argv Standard argv without initial components.
6319  *
6320  * @return Integer status (0 means success).
6321  **/
6322
6323 static int rpc_trustdom_del(struct net_context *c, int argc, const char **argv)
6324 {
6325         if (argc > 0 && !c->display_usage) {
6326                 return run_rpc_command(c, NULL, &ndr_table_samr, 0,
6327                                        rpc_trustdom_del_internals, argc, argv);
6328         } else {
6329                 d_printf("%s\n%s",
6330                          _("Usage:"),
6331                          _("net rpc trustdom del <domain>\n"));
6332                 return -1;
6333         }
6334 }
6335
6336 static NTSTATUS rpc_trustdom_get_pdc(struct net_context *c,
6337                                      struct cli_state *cli,
6338                                      TALLOC_CTX *mem_ctx,
6339                                      const char *domain_name)
6340 {
6341         char *dc_name = NULL;
6342         const char *buffer = NULL;
6343         struct rpc_pipe_client *netr;
6344         NTSTATUS status;
6345         WERROR result;
6346         struct dcerpc_binding_handle *b;
6347
6348         /* Use NetServerEnum2 */
6349
6350         if (cli_get_pdc_name(cli, domain_name, &dc_name)) {
6351                 SAFE_FREE(dc_name);
6352                 return NT_STATUS_OK;
6353         }
6354
6355         DEBUG(1,("NetServerEnum2 error: Couldn't find primary domain controller\
6356                  for domain %s\n", domain_name));
6357
6358         /* Try netr_GetDcName */
6359
6360         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_netlogon,
6361                                           &netr);
6362         if (!NT_STATUS_IS_OK(status)) {
6363                 return status;
6364         }
6365
6366         b = netr->binding_handle;
6367
6368         status = dcerpc_netr_GetDcName(b, mem_ctx,
6369                                        netr->desthost,
6370                                        domain_name,
6371                                        &buffer,
6372                                        &result);
6373         TALLOC_FREE(netr);
6374
6375         if (NT_STATUS_IS_OK(status) && W_ERROR_IS_OK(result)) {
6376                 return status;
6377         }
6378
6379         DEBUG(1,("netr_GetDcName error: Couldn't find primary domain controller\
6380                  for domain %s\n", domain_name));
6381
6382         if (!NT_STATUS_IS_OK(status)) {
6383                 return status;
6384         }
6385
6386         return werror_to_ntstatus(result);
6387 }
6388
6389 /**
6390  * Establish trust relationship to a trusting domain.
6391  * Interdomain account must already be created on remote PDC.
6392  *
6393  * @param c    A net_context structure.
6394  * @param argc Standard argc.
6395  * @param argv Standard argv without initial components.
6396  *
6397  * @return Integer status (0 means success).
6398  **/
6399
6400 static int rpc_trustdom_establish(struct net_context *c, int argc,
6401                                   const char **argv)
6402 {
6403         struct cli_state *cli = NULL;
6404         struct sockaddr_storage server_ss;
6405         struct rpc_pipe_client *pipe_hnd = NULL;
6406         struct policy_handle connect_hnd;
6407         TALLOC_CTX *mem_ctx;
6408         NTSTATUS nt_status, result;
6409         struct dom_sid *domain_sid;
6410
6411         char* domain_name;
6412         char* acct_name;
6413         fstring pdc_name;
6414         union lsa_PolicyInformation *info = NULL;
6415         struct dcerpc_binding_handle *b;
6416
6417         /*
6418          * Connect to \\server\ipc$ as 'our domain' account with password
6419          */
6420
6421         if (argc != 1 || c->display_usage) {
6422                 d_printf("%s\n%s",
6423                          _("Usage:"),
6424                          _("net rpc trustdom establish <domain_name>\n"));
6425                 return -1;
6426         }
6427
6428         domain_name = smb_xstrdup(argv[0]);
6429         if (!strupper_m(domain_name)) {
6430                 SAFE_FREE(domain_name);
6431                 return -1;
6432         }
6433
6434         /* account name used at first is our domain's name with '$' */
6435         if (asprintf(&acct_name, "%s$", lp_workgroup()) == -1) {
6436                 return -1;
6437         }
6438         if (!strupper_m(acct_name)) {
6439                 SAFE_FREE(domain_name);
6440                 SAFE_FREE(acct_name);
6441                 return -1;
6442         }
6443
6444         /*
6445          * opt_workgroup will be used by connection functions further,
6446          * hence it should be set to remote domain name instead of ours
6447          */
6448         if (c->opt_workgroup) {
6449                 c->opt_workgroup = smb_xstrdup(domain_name);
6450         };
6451
6452         c->opt_user_name = acct_name;
6453
6454         /* find the domain controller */
6455         if (!net_find_pdc(&server_ss, pdc_name, domain_name)) {
6456                 DEBUG(0, ("Couldn't find domain controller for domain %s\n", domain_name));
6457                 return -1;
6458         }
6459
6460         /* connect to ipc$ as username/password */
6461         nt_status = connect_to_ipc(c, &cli, &server_ss, pdc_name);
6462         if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT)) {
6463
6464                 /* Is it trusting domain account for sure ? */
6465                 DEBUG(0, ("Couldn't verify trusting domain account. Error was %s\n",
6466                         nt_errstr(nt_status)));
6467                 return -1;
6468         }
6469
6470         /* store who we connected to */
6471
6472         saf_store( domain_name, pdc_name );
6473
6474         /*
6475          * Connect to \\server\ipc$ again (this time anonymously)
6476          */
6477
6478         nt_status = connect_to_ipc_anonymous(c, &cli, &server_ss,
6479                                              (char*)pdc_name);
6480
6481         if (NT_STATUS_IS_ERR(nt_status)) {
6482                 DEBUG(0, ("Couldn't connect to domain %s controller. Error was %s.\n",
6483                         domain_name, nt_errstr(nt_status)));
6484                 return -1;
6485         }
6486
6487         if (!(mem_ctx = talloc_init("establishing trust relationship to "
6488                                     "domain %s", domain_name))) {
6489                 DEBUG(0, ("talloc_init() failed\n"));
6490                 cli_shutdown(cli);
6491                 return -1;
6492         }
6493
6494         /* Make sure we're talking to a proper server */
6495
6496         nt_status = rpc_trustdom_get_pdc(c, cli, mem_ctx, domain_name);
6497         if (!NT_STATUS_IS_OK(nt_status)) {
6498                 cli_shutdown(cli);
6499                 talloc_destroy(mem_ctx);
6500                 return -1;
6501         }
6502
6503         /*
6504          * Call LsaOpenPolicy and LsaQueryInfo
6505          */
6506
6507         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
6508                                              &pipe_hnd);
6509         if (!NT_STATUS_IS_OK(nt_status)) {
6510                 DEBUG(0, ("Could not initialise lsa pipe. Error was %s\n", nt_errstr(nt_status) ));
6511                 cli_shutdown(cli);
6512                 talloc_destroy(mem_ctx);
6513                 return -1;
6514         }
6515
6516         b = pipe_hnd->binding_handle;
6517
6518         nt_status = rpccli_lsa_open_policy2(pipe_hnd, mem_ctx, true, KEY_QUERY_VALUE,
6519                                          &connect_hnd);
6520         if (NT_STATUS_IS_ERR(nt_status)) {
6521                 DEBUG(0, ("Couldn't open policy handle. Error was %s\n",
6522                         nt_errstr(nt_status)));
6523                 cli_shutdown(cli);
6524                 talloc_destroy(mem_ctx);
6525                 return -1;
6526         }
6527
6528         /* Querying info level 5 */
6529
6530         nt_status = dcerpc_lsa_QueryInfoPolicy(b, mem_ctx,
6531                                                &connect_hnd,
6532                                                LSA_POLICY_INFO_ACCOUNT_DOMAIN,
6533                                                &info,
6534                                                &result);
6535         if (NT_STATUS_IS_ERR(nt_status)) {
6536                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
6537                         nt_errstr(nt_status)));
6538                 cli_shutdown(cli);
6539                 talloc_destroy(mem_ctx);
6540                 return -1;
6541         }
6542         if (NT_STATUS_IS_ERR(result)) {
6543                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
6544                         nt_errstr(result)));
6545                 cli_shutdown(cli);
6546                 talloc_destroy(mem_ctx);
6547                 return -1;
6548         }
6549
6550         domain_sid = info->account_domain.sid;
6551
6552         /* There should be actually query info level 3 (following nt serv behaviour),
6553            but I still don't know if it's _really_ necessary */
6554
6555         /*
6556          * Store the password in secrets db
6557          */
6558
6559         if (!pdb_set_trusteddom_pw(domain_name, c->opt_password, domain_sid)) {
6560                 DEBUG(0, ("Storing password for trusted domain failed.\n"));
6561                 cli_shutdown(cli);
6562                 talloc_destroy(mem_ctx);
6563                 return -1;
6564         }
6565
6566         /*
6567          * Close the pipes and clean up
6568          */
6569
6570         nt_status = dcerpc_lsa_Close(b, mem_ctx, &connect_hnd, &result);
6571         if (NT_STATUS_IS_ERR(nt_status)) {
6572                 DEBUG(0, ("Couldn't close LSA pipe. Error was %s\n",
6573                         nt_errstr(nt_status)));
6574                 cli_shutdown(cli);
6575                 talloc_destroy(mem_ctx);
6576                 return -1;
6577         }
6578
6579         cli_shutdown(cli);
6580
6581         talloc_destroy(mem_ctx);
6582
6583         d_printf(_("Trust to domain %s established\n"), domain_name);
6584         return 0;
6585 }
6586
6587 /**
6588  * Revoke trust relationship to the remote domain.
6589  *
6590  * @param c    A net_context structure.
6591  * @param argc Standard argc.
6592  * @param argv Standard argv without initial components.
6593  *
6594  * @return Integer status (0 means success).
6595  **/
6596
6597 static int rpc_trustdom_revoke(struct net_context *c, int argc,
6598                                const char **argv)
6599 {
6600         char* domain_name;
6601         int rc = -1;
6602
6603         if (argc < 1 || c->display_usage) {
6604                 d_printf("%s\n%s",
6605                          _("Usage:"),
6606                          _("net rpc trustdom revoke <domain_name>\n"
6607                            "  Revoke trust relationship\n"
6608                            "    domain_name\tName of domain to revoke trust\n"));
6609                 return -1;
6610         }
6611
6612         /* generate upper cased domain name */
6613         domain_name = smb_xstrdup(argv[0]);
6614         if (!strupper_m(domain_name)) {
6615                 SAFE_FREE(domain_name);
6616                 return -1;
6617         }
6618
6619         /* delete password of the trust */
6620         if (!pdb_del_trusteddom_pw(domain_name)) {
6621                 DEBUG(0, ("Failed to revoke relationship to the trusted domain %s\n",
6622                           domain_name));
6623                 goto done;
6624         };
6625
6626         rc = 0;
6627 done:
6628         SAFE_FREE(domain_name);
6629         return rc;
6630 }
6631
6632 static NTSTATUS rpc_query_domain_sid(struct net_context *c,
6633                                         const struct dom_sid *domain_sid,
6634                                         const char *domain_name,
6635                                         struct cli_state *cli,
6636                                         struct rpc_pipe_client *pipe_hnd,
6637                                         TALLOC_CTX *mem_ctx,
6638                                         int argc,
6639                                         const char **argv)
6640 {
6641         fstring str_sid;
6642         if (!sid_to_fstring(str_sid, domain_sid)) {
6643                 return NT_STATUS_UNSUCCESSFUL;
6644         }
6645         d_printf("%s\n", str_sid);
6646         return NT_STATUS_OK;
6647 }
6648
6649 static void print_trusted_domain(struct dom_sid *dom_sid, const char *trusted_dom_name)
6650 {
6651         fstring ascii_sid;
6652
6653         /* convert sid into ascii string */
6654         sid_to_fstring(ascii_sid, dom_sid);
6655
6656         d_printf("%-20s%s\n", trusted_dom_name, ascii_sid);
6657 }
6658
6659 static NTSTATUS vampire_trusted_domain(struct rpc_pipe_client *pipe_hnd,
6660                                       TALLOC_CTX *mem_ctx,
6661                                       struct policy_handle *pol,
6662                                       struct dom_sid dom_sid,
6663                                       const char *trusted_dom_name)
6664 {
6665         NTSTATUS nt_status, result;
6666         union lsa_TrustedDomainInfo *info = NULL;
6667         char *cleartextpwd = NULL;
6668         DATA_BLOB session_key;
6669         DATA_BLOB data = data_blob_null;
6670         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
6671
6672         nt_status = dcerpc_lsa_QueryTrustedDomainInfoBySid(b, mem_ctx,
6673                                                            pol,
6674                                                            &dom_sid,
6675                                                            LSA_TRUSTED_DOMAIN_INFO_PASSWORD,
6676                                                            &info,
6677                                                            &result);
6678         if (NT_STATUS_IS_ERR(nt_status)) {
6679                 DEBUG(0,("Could not query trusted domain info. Error was %s\n",
6680                 nt_errstr(nt_status)));
6681                 goto done;
6682         }
6683         if (NT_STATUS_IS_ERR(result)) {
6684                 nt_status = result;
6685                 DEBUG(0,("Could not query trusted domain info. Error was %s\n",
6686                 nt_errstr(result)));
6687                 goto done;
6688         }
6689
6690         data = data_blob(info->password.password->data,
6691                          info->password.password->length);
6692
6693         nt_status = cli_get_session_key(mem_ctx, pipe_hnd, &session_key);
6694         if (!NT_STATUS_IS_OK(nt_status)) {
6695                 DEBUG(0, ("Could not retrieve session key: %s\n", nt_errstr(nt_status)));
6696                 goto done;
6697         }
6698
6699         cleartextpwd = sess_decrypt_string(mem_ctx, &data, &session_key);
6700         data_blob_free(&session_key);
6701
6702         if (cleartextpwd == NULL) {
6703                 DEBUG(0,("retrieved NULL password\n"));
6704                 nt_status = NT_STATUS_UNSUCCESSFUL;
6705                 goto done;
6706         }
6707
6708         if (!pdb_set_trusteddom_pw(trusted_dom_name, cleartextpwd, &dom_sid)) {
6709                 DEBUG(0, ("Storing password for trusted domain failed.\n"));
6710                 nt_status = NT_STATUS_UNSUCCESSFUL;
6711                 goto done;
6712         }
6713
6714 #ifdef DEBUG_PASSWORD
6715         DEBUG(100,("successfully vampired trusted domain [%s], sid: [%s], "
6716                    "password: [%s]\n", trusted_dom_name,
6717                    sid_string_dbg(&dom_sid), cleartextpwd));
6718 #endif
6719
6720 done:
6721         SAFE_FREE(cleartextpwd);
6722         data_blob_free(&data);
6723
6724         return nt_status;
6725 }
6726
6727 static int rpc_trustdom_vampire(struct net_context *c, int argc,
6728                                 const char **argv)
6729 {
6730         /* common variables */
6731         TALLOC_CTX* mem_ctx;
6732         struct cli_state *cli = NULL;
6733         struct rpc_pipe_client *pipe_hnd = NULL;
6734         NTSTATUS nt_status, result;
6735         const char *domain_name = NULL;
6736         struct policy_handle connect_hnd;
6737         union lsa_PolicyInformation *info = NULL;
6738
6739         /* trusted domains listing variables */
6740         unsigned int enum_ctx = 0;
6741         int i;
6742         struct lsa_DomainList dom_list;
6743         fstring pdc_name;
6744         struct dcerpc_binding_handle *b;
6745
6746         if (c->display_usage) {
6747                 d_printf(  "%s\n"
6748                            "net rpc trustdom vampire\n"
6749                            "  %s\n",
6750                          _("Usage:"),
6751                          _("Vampire trust relationship from remote server"));
6752                 return 0;
6753         }
6754
6755         /*
6756          * Listing trusted domains (stored in secrets.tdb, if local)
6757          */
6758
6759         mem_ctx = talloc_init("trust relationships vampire");
6760
6761         /*
6762          * set domain and pdc name to local samba server (default)
6763          * or to remote one given in command line
6764          */
6765
6766         if (strcasecmp_m(c->opt_workgroup, lp_workgroup())) {
6767                 domain_name = c->opt_workgroup;
6768                 c->opt_target_workgroup = c->opt_workgroup;
6769         } else {
6770                 fstrcpy(pdc_name, lp_netbios_name());
6771                 domain_name = talloc_strdup(mem_ctx, lp_workgroup());
6772                 c->opt_target_workgroup = domain_name;
6773         };
6774
6775         /* open \PIPE\lsarpc and open policy handle */
6776         nt_status = net_make_ipc_connection(c, NET_FLAGS_PDC, &cli);
6777         if (!NT_STATUS_IS_OK(nt_status)) {
6778                 DEBUG(0, ("Couldn't connect to domain controller: %s\n",
6779                           nt_errstr(nt_status)));
6780                 talloc_destroy(mem_ctx);
6781                 return -1;
6782         };
6783
6784         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
6785                                              &pipe_hnd);
6786         if (!NT_STATUS_IS_OK(nt_status)) {
6787                 DEBUG(0, ("Could not initialise lsa pipe. Error was %s\n",
6788                         nt_errstr(nt_status) ));
6789                 cli_shutdown(cli);
6790                 talloc_destroy(mem_ctx);
6791                 return -1;
6792         };
6793
6794         b = pipe_hnd->binding_handle;
6795
6796         nt_status = rpccli_lsa_open_policy2(pipe_hnd, mem_ctx, false, KEY_QUERY_VALUE,
6797                                         &connect_hnd);
6798         if (NT_STATUS_IS_ERR(nt_status)) {
6799                 DEBUG(0, ("Couldn't open policy handle. Error was %s\n",
6800                         nt_errstr(nt_status)));
6801                 cli_shutdown(cli);
6802                 talloc_destroy(mem_ctx);
6803                 return -1;
6804         };
6805
6806         /* query info level 5 to obtain sid of a domain being queried */
6807         nt_status = dcerpc_lsa_QueryInfoPolicy(b, mem_ctx,
6808                                                &connect_hnd,
6809                                                LSA_POLICY_INFO_ACCOUNT_DOMAIN,
6810                                                &info,
6811                                                &result);
6812
6813         if (NT_STATUS_IS_ERR(nt_status)) {
6814                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
6815                         nt_errstr(nt_status)));
6816                 cli_shutdown(cli);
6817                 talloc_destroy(mem_ctx);
6818                 return -1;
6819         }
6820         if (NT_STATUS_IS_ERR(result)) {
6821                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
6822                         nt_errstr(result)));
6823                 cli_shutdown(cli);
6824                 talloc_destroy(mem_ctx);
6825                 return -1;
6826         }
6827
6828         /*
6829          * Keep calling LsaEnumTrustdom over opened pipe until
6830          * the end of enumeration is reached
6831          */
6832
6833         d_printf(_("Vampire trusted domains:\n\n"));
6834
6835         do {
6836                 nt_status = dcerpc_lsa_EnumTrustDom(b, mem_ctx,
6837                                                     &connect_hnd,
6838                                                     &enum_ctx,
6839                                                     &dom_list,
6840                                                     (uint32_t)-1,
6841                                                     &result);
6842                 if (NT_STATUS_IS_ERR(nt_status)) {
6843                         DEBUG(0, ("Couldn't enumerate trusted domains. Error was %s\n",
6844                                 nt_errstr(nt_status)));
6845                         cli_shutdown(cli);
6846                         talloc_destroy(mem_ctx);
6847                         return -1;
6848                 };
6849                 if (NT_STATUS_IS_ERR(result)) {
6850                         nt_status = result;
6851                         DEBUG(0, ("Couldn't enumerate trusted domains. Error was %s\n",
6852                                 nt_errstr(result)));
6853                         cli_shutdown(cli);
6854                         talloc_destroy(mem_ctx);
6855                         return -1;
6856                 };
6857
6858
6859                 for (i = 0; i < dom_list.count; i++) {
6860
6861                         print_trusted_domain(dom_list.domains[i].sid,
6862                                              dom_list.domains[i].name.string);
6863
6864                         nt_status = vampire_trusted_domain(pipe_hnd, mem_ctx, &connect_hnd,
6865                                                            *dom_list.domains[i].sid,
6866                                                            dom_list.domains[i].name.string);
6867                         if (!NT_STATUS_IS_OK(nt_status)) {
6868                                 cli_shutdown(cli);
6869                                 talloc_destroy(mem_ctx);
6870                                 return -1;
6871                         }
6872                 };
6873
6874                 /*
6875                  * in case of no trusted domains say something rather
6876                  * than just display blank line
6877                  */
6878                 if (!dom_list.count) d_printf(_("none\n"));
6879
6880         } while (NT_STATUS_EQUAL(nt_status, STATUS_MORE_ENTRIES));
6881
6882         /* close this connection before doing next one */
6883         nt_status = dcerpc_lsa_Close(b, mem_ctx, &connect_hnd, &result);
6884         if (NT_STATUS_IS_ERR(nt_status)) {
6885                 DEBUG(0, ("Couldn't properly close lsa policy handle. Error was %s\n",
6886                         nt_errstr(nt_status)));
6887                 cli_shutdown(cli);
6888                 talloc_destroy(mem_ctx);
6889                 return -1;
6890         };
6891
6892         /* close lsarpc pipe and connection to IPC$ */
6893         cli_shutdown(cli);
6894
6895         talloc_destroy(mem_ctx);
6896         return 0;
6897 }
6898
6899 static int rpc_trustdom_list(struct net_context *c, int argc, const char **argv)
6900 {
6901         /* common variables */
6902         TALLOC_CTX* mem_ctx;
6903         struct cli_state *cli = NULL, *remote_cli = NULL;
6904         struct rpc_pipe_client *pipe_hnd = NULL;
6905         NTSTATUS nt_status, result;
6906         const char *domain_name = NULL;
6907         struct dom_sid *queried_dom_sid;
6908         int ascii_dom_name_len;
6909         struct policy_handle connect_hnd;
6910         union lsa_PolicyInformation *info = NULL;
6911         struct dcerpc_binding_handle *b = NULL;
6912
6913         /* trusted domains listing variables */
6914         unsigned int num_domains, enum_ctx = 0;
6915         int i;
6916         struct lsa_DomainList dom_list;
6917         fstring pdc_name;
6918         bool found_domain;
6919
6920         /* trusting domains listing variables */
6921         struct policy_handle domain_hnd;
6922         struct samr_SamArray *trusts = NULL;
6923
6924         if (c->display_usage) {
6925                 d_printf(  "%s\n"
6926                            "net rpc trustdom list\n"
6927                            "    %s\n",
6928                          _("Usage:"),
6929                          _("List incoming and outgoing trust relationships"));
6930                 return 0;
6931         }
6932
6933         /*
6934          * Listing trusted domains (stored in secrets.tdb, if local)
6935          */
6936
6937         mem_ctx = talloc_init("trust relationships listing");
6938
6939         /*
6940          * set domain and pdc name to local samba server (default)
6941          * or to remote one given in command line
6942          */
6943
6944         if (strcasecmp_m(c->opt_workgroup, lp_workgroup())) {
6945                 domain_name = c->opt_workgroup;
6946                 c->opt_target_workgroup = c->opt_workgroup;
6947         } else {
6948                 fstrcpy(pdc_name, lp_netbios_name());
6949                 domain_name = talloc_strdup(mem_ctx, lp_workgroup());
6950                 c->opt_target_workgroup = domain_name;
6951         };
6952
6953         /* open \PIPE\lsarpc and open policy handle */
6954         nt_status = net_make_ipc_connection(c, NET_FLAGS_PDC, &cli);
6955         if (!NT_STATUS_IS_OK(nt_status)) {
6956                 DEBUG(0, ("Couldn't connect to domain controller: %s\n",
6957                           nt_errstr(nt_status)));
6958                 talloc_destroy(mem_ctx);
6959                 return -1;
6960         };
6961
6962         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
6963                                              &pipe_hnd);
6964         if (!NT_STATUS_IS_OK(nt_status)) {
6965                 DEBUG(0, ("Could not initialise lsa pipe. Error was %s\n",
6966                         nt_errstr(nt_status) ));
6967                 cli_shutdown(cli);
6968                 talloc_destroy(mem_ctx);
6969                 return -1;
6970         };
6971
6972         b = pipe_hnd->binding_handle;
6973
6974         nt_status = rpccli_lsa_open_policy2(pipe_hnd, mem_ctx, false, KEY_QUERY_VALUE,
6975                                         &connect_hnd);
6976         if (NT_STATUS_IS_ERR(nt_status)) {
6977                 DEBUG(0, ("Couldn't open policy handle. Error was %s\n",
6978                         nt_errstr(nt_status)));
6979                 cli_shutdown(cli);
6980                 talloc_destroy(mem_ctx);
6981                 return -1;
6982         };
6983
6984         /* query info level 5 to obtain sid of a domain being queried */
6985         nt_status = dcerpc_lsa_QueryInfoPolicy(b, mem_ctx,
6986                                                &connect_hnd,
6987                                                LSA_POLICY_INFO_ACCOUNT_DOMAIN,
6988                                                &info,
6989                                                &result);
6990
6991         if (NT_STATUS_IS_ERR(nt_status)) {
6992                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
6993                         nt_errstr(nt_status)));
6994                 cli_shutdown(cli);
6995                 talloc_destroy(mem_ctx);
6996                 return -1;
6997         }
6998         if (NT_STATUS_IS_ERR(result)) {
6999                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
7000                         nt_errstr(result)));
7001                 cli_shutdown(cli);
7002                 talloc_destroy(mem_ctx);
7003                 return -1;
7004         }
7005
7006         queried_dom_sid = info->account_domain.sid;
7007
7008         /*
7009          * Keep calling LsaEnumTrustdom over opened pipe until
7010          * the end of enumeration is reached
7011          */
7012
7013         d_printf(_("Trusted domains list:\n\n"));
7014
7015         found_domain = false;
7016
7017         do {
7018                 nt_status = dcerpc_lsa_EnumTrustDom(b, mem_ctx,
7019                                                     &connect_hnd,
7020                                                     &enum_ctx,
7021                                                     &dom_list,
7022                                                     (uint32_t)-1,
7023                                                     &result);
7024                 if (NT_STATUS_IS_ERR(nt_status)) {
7025                         DEBUG(0, ("Couldn't enumerate trusted domains. Error was %s\n",
7026                                 nt_errstr(nt_status)));
7027                         cli_shutdown(cli);
7028                         talloc_destroy(mem_ctx);
7029                         return -1;
7030                 };
7031                 if (NT_STATUS_IS_ERR(result)) {
7032                         DEBUG(0, ("Couldn't enumerate trusted domains. Error was %s\n",
7033                                 nt_errstr(result)));
7034                         cli_shutdown(cli);
7035                         talloc_destroy(mem_ctx);
7036                         return -1;
7037                 };
7038
7039
7040                 for (i = 0; i < dom_list.count; i++) {
7041                         print_trusted_domain(dom_list.domains[i].sid,
7042                                              dom_list.domains[i].name.string);
7043                         found_domain = true;
7044                 };
7045
7046
7047         } while (NT_STATUS_EQUAL(nt_status, STATUS_MORE_ENTRIES));
7048
7049         /*
7050          * in case of no trusted domains say something rather
7051          * than just display blank line
7052          */
7053         if (!found_domain) {
7054                 d_printf(_("none\n"));
7055         }
7056
7057         /* close this connection before doing next one */
7058         nt_status = dcerpc_lsa_Close(b, mem_ctx, &connect_hnd, &result);
7059         if (NT_STATUS_IS_ERR(nt_status)) {
7060                 DEBUG(0, ("Couldn't properly close lsa policy handle. Error was %s\n",
7061                         nt_errstr(nt_status)));
7062                 cli_shutdown(cli);
7063                 talloc_destroy(mem_ctx);
7064                 return -1;
7065         };
7066
7067         TALLOC_FREE(pipe_hnd);
7068
7069         /*
7070          * Listing trusting domains (stored in passdb backend, if local)
7071          */
7072
7073         d_printf(_("\nTrusting domains list:\n\n"));
7074
7075         /*
7076          * Open \PIPE\samr and get needed policy handles
7077          */
7078         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_samr,
7079                                              &pipe_hnd);
7080         if (!NT_STATUS_IS_OK(nt_status)) {
7081                 DEBUG(0, ("Could not initialise samr pipe. Error was %s\n", nt_errstr(nt_status)));
7082                 cli_shutdown(cli);
7083                 talloc_destroy(mem_ctx);
7084                 return -1;
7085         };
7086
7087         b = pipe_hnd->binding_handle;
7088
7089         /* SamrConnect2 */
7090         nt_status = dcerpc_samr_Connect2(b, mem_ctx,
7091                                          pipe_hnd->desthost,
7092                                          SAMR_ACCESS_LOOKUP_DOMAIN,
7093                                          &connect_hnd,
7094                                          &result);
7095         if (!NT_STATUS_IS_OK(nt_status)) {
7096                 DEBUG(0, ("Couldn't open SAMR policy handle. Error was %s\n",
7097                         nt_errstr(nt_status)));
7098                 cli_shutdown(cli);
7099                 talloc_destroy(mem_ctx);
7100                 return -1;
7101         };
7102         if (!NT_STATUS_IS_OK(result)) {
7103                 nt_status = result;
7104                 DEBUG(0, ("Couldn't open SAMR policy handle. Error was %s\n",
7105                         nt_errstr(result)));
7106                 cli_shutdown(cli);
7107                 talloc_destroy(mem_ctx);
7108                 return -1;
7109         };
7110
7111         /* SamrOpenDomain - we have to open domain policy handle in order to be
7112            able to enumerate accounts*/
7113         nt_status = dcerpc_samr_OpenDomain(b, mem_ctx,
7114                                            &connect_hnd,
7115                                            SAMR_DOMAIN_ACCESS_ENUM_ACCOUNTS,
7116                                            queried_dom_sid,
7117                                            &domain_hnd,
7118                                            &result);
7119         if (!NT_STATUS_IS_OK(nt_status)) {
7120                 DEBUG(0, ("Couldn't open domain object. Error was %s\n",
7121                         nt_errstr(nt_status)));
7122                 cli_shutdown(cli);
7123                 talloc_destroy(mem_ctx);
7124                 return -1;
7125         };
7126         if (!NT_STATUS_IS_OK(result)) {
7127                 nt_status = result;
7128                 DEBUG(0, ("Couldn't open domain object. Error was %s\n",
7129                         nt_errstr(result)));
7130                 cli_shutdown(cli);
7131                 talloc_destroy(mem_ctx);
7132                 return -1;
7133         };
7134
7135         /*
7136          * perform actual enumeration
7137          */
7138
7139         found_domain = false;
7140
7141         enum_ctx = 0;   /* reset enumeration context from last enumeration */
7142         do {
7143
7144                 nt_status = dcerpc_samr_EnumDomainUsers(b, mem_ctx,
7145                                                         &domain_hnd,
7146                                                         &enum_ctx,
7147                                                         ACB_DOMTRUST,
7148                                                         &trusts,
7149                                                         0xffff,
7150                                                         &num_domains,
7151                                                         &result);
7152                 if (NT_STATUS_IS_ERR(nt_status)) {
7153                         DEBUG(0, ("Couldn't enumerate accounts. Error was: %s\n",
7154                                 nt_errstr(nt_status)));
7155                         cli_shutdown(cli);
7156                         talloc_destroy(mem_ctx);
7157                         return -1;
7158                 };
7159                 if (NT_STATUS_IS_ERR(result)) {
7160                         nt_status = result;
7161                         DEBUG(0, ("Couldn't enumerate accounts. Error was: %s\n",
7162                                 nt_errstr(result)));
7163                         cli_shutdown(cli);
7164                         talloc_destroy(mem_ctx);
7165                         return -1;
7166                 };
7167
7168                 for (i = 0; i < num_domains; i++) {
7169
7170                         char *str = discard_const_p(char, trusts->entries[i].name.string);
7171
7172                         found_domain = true;
7173
7174                         /*
7175                          * get each single domain's sid (do we _really_ need this ?):
7176                          *  1) connect to domain's pdc
7177                          *  2) query the pdc for domain's sid
7178                          */
7179
7180                         /* get rid of '$' tail */
7181                         ascii_dom_name_len = strlen(str);
7182                         if (ascii_dom_name_len && ascii_dom_name_len < FSTRING_LEN)
7183                                 str[ascii_dom_name_len - 1] = '\0';
7184
7185                         /* set opt_* variables to remote domain */
7186                         if (!strupper_m(str)) {
7187                                 cli_shutdown(cli);
7188                                 talloc_destroy(mem_ctx);
7189                                 return -1;
7190                         }
7191                         c->opt_workgroup = talloc_strdup(mem_ctx, str);
7192                         c->opt_target_workgroup = c->opt_workgroup;
7193
7194                         d_printf("%-20s", str);
7195
7196                         /* connect to remote domain controller */
7197                         nt_status = net_make_ipc_connection(c,
7198                                         NET_FLAGS_PDC | NET_FLAGS_ANONYMOUS,
7199                                         &remote_cli);
7200                         if (NT_STATUS_IS_OK(nt_status)) {
7201                                 /* query for domain's sid */
7202                                 if (run_rpc_command(
7203                                             c, remote_cli,
7204                                             &ndr_table_lsarpc, 0,
7205                                             rpc_query_domain_sid, argc,
7206                                             argv))
7207                                         d_printf(_("strange - couldn't get domain's sid\n"));
7208
7209                                 cli_shutdown(remote_cli);
7210
7211                         } else {
7212                                 d_fprintf(stderr, _("domain controller is not "
7213                                           "responding: %s\n"),
7214                                           nt_errstr(nt_status));
7215                                 d_printf(_("couldn't get domain's sid\n"));
7216                         }
7217                 }
7218
7219         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
7220
7221         if (!found_domain) {
7222                 d_printf("none\n");
7223         }
7224
7225         /* close opened samr and domain policy handles */
7226         nt_status = dcerpc_samr_Close(b, mem_ctx, &domain_hnd, &result);
7227         if (!NT_STATUS_IS_OK(nt_status)) {
7228                 DEBUG(0, ("Couldn't properly close domain policy handle for domain %s\n", domain_name));
7229         };
7230
7231         nt_status = dcerpc_samr_Close(b, mem_ctx, &connect_hnd, &result);
7232         if (!NT_STATUS_IS_OK(nt_status)) {
7233                 DEBUG(0, ("Couldn't properly close samr policy handle for domain %s\n", domain_name));
7234         };
7235
7236         /* close samr pipe and connection to IPC$ */
7237         cli_shutdown(cli);
7238
7239         talloc_destroy(mem_ctx);
7240         return 0;
7241 }
7242
7243 /**
7244  * Entrypoint for 'net rpc trustdom' code.
7245  *
7246  * @param argc Standard argc.
7247  * @param argv Standard argv without initial components.
7248  *
7249  * @return Integer status (0 means success).
7250  */
7251
7252 static int rpc_trustdom(struct net_context *c, int argc, const char **argv)
7253 {
7254         struct functable func[] = {
7255                 {
7256                         "add",
7257                         rpc_trustdom_add,
7258                         NET_TRANSPORT_RPC,
7259                         N_("Add trusting domain's account"),
7260                         N_("net rpc trustdom add\n"
7261                            "    Add trusting domain's account")
7262                 },
7263                 {
7264                         "del",
7265                         rpc_trustdom_del,
7266                         NET_TRANSPORT_RPC,
7267                         N_("Remove trusting domain's account"),
7268                         N_("net rpc trustdom del\n"
7269                            "    Remove trusting domain's account")
7270                 },
7271                 {
7272                         "establish",
7273                         rpc_trustdom_establish,
7274                         NET_TRANSPORT_RPC,
7275                         N_("Establish outgoing trust relationship"),
7276                         N_("net rpc trustdom establish\n"
7277                            "    Establish outgoing trust relationship")
7278                 },
7279                 {
7280                         "revoke",
7281                         rpc_trustdom_revoke,
7282                         NET_TRANSPORT_RPC,
7283                         N_("Revoke outgoing trust relationship"),
7284                         N_("net rpc trustdom revoke\n"
7285                            "    Revoke outgoing trust relationship")
7286                 },
7287                 {
7288                         "list",
7289                         rpc_trustdom_list,
7290                         NET_TRANSPORT_RPC,
7291                         N_("List in- and outgoing domain trusts"),
7292                         N_("net rpc trustdom list\n"
7293                            "    List in- and outgoing domain trusts")
7294                 },
7295                 {
7296                         "vampire",
7297                         rpc_trustdom_vampire,
7298                         NET_TRANSPORT_RPC,
7299                         N_("Vampire trusts from remote server"),
7300                         N_("net rpc trustdom vampire\n"
7301                            "    Vampire trusts from remote server")
7302                 },
7303                 {NULL, NULL, 0, NULL, NULL}
7304         };
7305
7306         return net_run_function(c, argc, argv, "net rpc trustdom", func);
7307 }
7308
7309 /**
7310  * Check if a server will take rpc commands
7311  * @param flags Type of server to connect to (PDC, DMB, localhost)
7312  *              if the host is not explicitly specified
7313  * @return  bool (true means rpc supported)
7314  */
7315 bool net_rpc_check(struct net_context *c, unsigned flags)
7316 {
7317         struct cli_state *cli;
7318         bool ret = false;
7319         struct sockaddr_storage server_ss;
7320         char *server_name = NULL;
7321         NTSTATUS status;
7322
7323         /* flags (i.e. server type) may depend on command */
7324         if (!net_find_server(c, NULL, flags, &server_ss, &server_name))
7325                 return false;
7326
7327         status = cli_connect_nb(server_name, &server_ss, 0, 0x20,
7328                                 lp_netbios_name(), SMB_SIGNING_DEFAULT,
7329                                 0, &cli);
7330         if (!NT_STATUS_IS_OK(status)) {
7331                 return false;
7332         }
7333         status = smbXcli_negprot(cli->conn, cli->timeout, PROTOCOL_CORE,
7334                                  PROTOCOL_NT1);
7335         if (!NT_STATUS_IS_OK(status))
7336                 goto done;
7337         if (smbXcli_conn_protocol(cli->conn) < PROTOCOL_NT1)
7338                 goto done;
7339
7340         ret = true;
7341  done:
7342         cli_shutdown(cli);
7343         return ret;
7344 }
7345
7346 /* dump sam database via samsync rpc calls */
7347 static int rpc_samdump(struct net_context *c, int argc, const char **argv) {
7348         if (c->display_usage) {
7349                 d_printf(  "%s\n"
7350                            "net rpc samdump\n"
7351                            "    %s\n",
7352                          _("Usage:"),
7353                          _("Dump remote SAM database"));
7354                 return 0;
7355         }
7356
7357         return run_rpc_command(c, NULL, &ndr_table_netlogon,
7358                                NET_FLAGS_ANONYMOUS,
7359                                rpc_samdump_internals, argc, argv);
7360 }
7361
7362 /* syncronise sam database via samsync rpc calls */
7363 static int rpc_vampire(struct net_context *c, int argc, const char **argv)
7364 {
7365         struct functable func[] = {
7366                 {
7367                         "ldif",
7368                         rpc_vampire_ldif,
7369                         NET_TRANSPORT_RPC,
7370                         N_("Dump remote SAM database to ldif"),
7371                         N_("net rpc vampire ldif\n"
7372                            "    Dump remote SAM database to LDIF file or "
7373                            "stdout")
7374                 },
7375                 {
7376                         "keytab",
7377                         rpc_vampire_keytab,
7378                         NET_TRANSPORT_RPC,
7379                         N_("Dump remote SAM database to Kerberos Keytab"),
7380                         N_("net rpc vampire keytab\n"
7381                            "    Dump remote SAM database to Kerberos keytab "
7382                            "file")
7383                 },
7384                 {
7385                         "passdb",
7386                         rpc_vampire_passdb,
7387                         NET_TRANSPORT_RPC,
7388                         N_("Dump remote SAM database to passdb"),
7389                         N_("net rpc vampire passdb\n"
7390                            "    Dump remote SAM database to passdb")
7391                 },
7392
7393                 {NULL, NULL, 0, NULL, NULL}
7394         };
7395
7396         if (argc == 0) {
7397                 if (c->display_usage) {
7398                         d_printf(  "%s\n"
7399                                    "net rpc vampire\n"
7400                                    "    %s\n",
7401                                  _("Usage:"),
7402                                  _("Vampire remote SAM database"));
7403                         return 0;
7404                 }
7405
7406                 return rpc_vampire_passdb(c, argc, argv);
7407         }
7408
7409         return net_run_function(c, argc, argv, "net rpc vampire", func);
7410 }
7411
7412 /**
7413  * Migrate everything from a print server.
7414  *
7415  * @param c     A net_context structure.
7416  * @param argc  Standard main() style argc.
7417  * @param argv  Standard main() style argv. Initial components are already
7418  *              stripped.
7419  *
7420  * @return A shell status integer (0 for success).
7421  *
7422  * The order is important !
7423  * To successfully add drivers the print queues have to exist !
7424  * Applying ACLs should be the last step, because you're easily locked out.
7425  *
7426  **/
7427 static int rpc_printer_migrate_all(struct net_context *c, int argc,
7428                                    const char **argv)
7429 {
7430         int ret;
7431
7432         if (c->display_usage) {
7433                 d_printf(  "%s\n"
7434                            "net rpc printer migrate all\n"
7435                            "    %s\n",
7436                          _("Usage:"),
7437                          _("Migrate everything from a print server"));
7438                 return 0;
7439         }
7440
7441         if (!c->opt_host) {
7442                 d_printf(_("no server to migrate\n"));
7443                 return -1;
7444         }
7445
7446         ret = run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7447                               rpc_printer_migrate_printers_internals, argc,
7448                               argv);
7449         if (ret)
7450                 return ret;
7451
7452         ret = run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7453                               rpc_printer_migrate_drivers_internals, argc,
7454                               argv);
7455         if (ret)
7456                 return ret;
7457
7458         ret = run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7459                               rpc_printer_migrate_forms_internals, argc, argv);
7460         if (ret)
7461                 return ret;
7462
7463         ret = run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7464                               rpc_printer_migrate_settings_internals, argc,
7465                               argv);
7466         if (ret)
7467                 return ret;
7468
7469         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7470                                rpc_printer_migrate_security_internals, argc,
7471                                argv);
7472
7473 }
7474
7475 /**
7476  * Migrate print drivers from a print server.
7477  *
7478  * @param c     A net_context structure.
7479  * @param argc  Standard main() style argc.
7480  * @param argv  Standard main() style argv. Initial components are already
7481  *              stripped.
7482  *
7483  * @return A shell status integer (0 for success).
7484  **/
7485 static int rpc_printer_migrate_drivers(struct net_context *c, int argc,
7486                                        const char **argv)
7487 {
7488         if (c->display_usage) {
7489                 d_printf(  "%s\n"
7490                            "net rpc printer migrate drivers\n"
7491                            "     %s\n",
7492                          _("Usage:"),
7493                          _("Migrate print-drivers from a print-server"));
7494                 return 0;
7495         }
7496
7497         if (!c->opt_host) {
7498                 d_printf(_("no server to migrate\n"));
7499                 return -1;
7500         }
7501
7502         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7503                                rpc_printer_migrate_drivers_internals,
7504                                argc, argv);
7505 }
7506
7507 /**
7508  * Migrate print-forms from a print-server.
7509  *
7510  * @param c     A net_context structure.
7511  * @param argc  Standard main() style argc.
7512  * @param argv  Standard main() style argv. Initial components are already
7513  *              stripped.
7514  *
7515  * @return A shell status integer (0 for success).
7516  **/
7517 static int rpc_printer_migrate_forms(struct net_context *c, int argc,
7518                                      const char **argv)
7519 {
7520         if (c->display_usage) {
7521                 d_printf(  "%s\n"
7522                            "net rpc printer migrate forms\n"
7523                            "    %s\n",
7524                          _("Usage:"),
7525                          _("Migrate print-forms from a print-server"));
7526                 return 0;
7527         }
7528
7529         if (!c->opt_host) {
7530                 d_printf(_("no server to migrate\n"));
7531                 return -1;
7532         }
7533
7534         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7535                                rpc_printer_migrate_forms_internals,
7536                                argc, argv);
7537 }
7538
7539 /**
7540  * Migrate printers from a print-server.
7541  *
7542  * @param c     A net_context structure.
7543  * @param argc  Standard main() style argc.
7544  * @param argv  Standard main() style argv. Initial components are already
7545  *              stripped.
7546  *
7547  * @return A shell status integer (0 for success).
7548  **/
7549 static int rpc_printer_migrate_printers(struct net_context *c, int argc,
7550                                         const char **argv)
7551 {
7552         if (c->display_usage) {
7553                 d_printf(  "%s\n"
7554                            "net rpc printer migrate printers\n"
7555                            "    %s\n",
7556                          _("Usage:"),
7557                          _("Migrate printers from a print-server"));
7558                 return 0;
7559         }
7560
7561         if (!c->opt_host) {
7562                 d_printf(_("no server to migrate\n"));
7563                 return -1;
7564         }
7565
7566         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7567                                rpc_printer_migrate_printers_internals,
7568                                argc, argv);
7569 }
7570
7571 /**
7572  * Migrate printer-ACLs from a print-server
7573  *
7574  * @param c     A net_context structure.
7575  * @param argc  Standard main() style argc.
7576  * @param argv  Standard main() style argv. Initial components are already
7577  *              stripped.
7578  *
7579  * @return A shell status integer (0 for success).
7580  **/
7581 static int rpc_printer_migrate_security(struct net_context *c, int argc,
7582                                         const char **argv)
7583 {
7584         if (c->display_usage) {
7585                 d_printf(  "%s\n"
7586                            "net rpc printer migrate security\n"
7587                            "    %s\n",
7588                          _("Usage:"),
7589                          _("Migrate printer-ACLs from a print-server"));
7590                 return 0;
7591         }
7592
7593         if (!c->opt_host) {
7594                 d_printf(_("no server to migrate\n"));
7595                 return -1;
7596         }
7597
7598         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7599                                rpc_printer_migrate_security_internals,
7600                                argc, argv);
7601 }
7602
7603 /**
7604  * Migrate printer-settings from a print-server.
7605  *
7606  * @param c     A net_context structure.
7607  * @param argc  Standard main() style argc.
7608  * @param argv  Standard main() style argv. Initial components are already
7609  *              stripped.
7610  *
7611  * @return A shell status integer (0 for success).
7612  **/
7613 static int rpc_printer_migrate_settings(struct net_context *c, int argc,
7614                                         const char **argv)
7615 {
7616         if (c->display_usage) {
7617                 d_printf(  "%s\n"
7618                            "net rpc printer migrate settings\n"
7619                             "    %s\n",
7620                           _("Usage:"),
7621                           _("Migrate printer-settings from a "
7622                             "print-server"));
7623                 return 0;
7624         }
7625
7626         if (!c->opt_host) {
7627                 d_printf(_("no server to migrate\n"));
7628                 return -1;
7629         }
7630
7631         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7632                                rpc_printer_migrate_settings_internals,
7633                                argc, argv);
7634 }
7635
7636 /**
7637  * 'net rpc printer' entrypoint.
7638  *
7639  * @param c     A net_context structure.
7640  * @param argc  Standard main() style argc.
7641  * @param argv  Standard main() style argv. Initial components are already
7642  *              stripped.
7643  **/
7644
7645 int rpc_printer_migrate(struct net_context *c, int argc, const char **argv)
7646 {
7647
7648         /* ouch: when addriver and setdriver are called from within
7649            rpc_printer_migrate_drivers_internals, the printer-queue already
7650            *has* to exist */
7651
7652         struct functable func[] = {
7653                 {
7654                         "all",
7655                         rpc_printer_migrate_all,
7656                         NET_TRANSPORT_RPC,
7657                         N_("Migrate all from remote to local print server"),
7658                         N_("net rpc printer migrate all\n"
7659                            "    Migrate all from remote to local print server")
7660                 },
7661                 {
7662                         "drivers",
7663                         rpc_printer_migrate_drivers,
7664                         NET_TRANSPORT_RPC,
7665                         N_("Migrate drivers to local server"),
7666                         N_("net rpc printer migrate drivers\n"
7667                            "    Migrate drivers to local server")
7668                 },
7669                 {
7670                         "forms",
7671                         rpc_printer_migrate_forms,
7672                         NET_TRANSPORT_RPC,
7673                         N_("Migrate froms to local server"),
7674                         N_("net rpc printer migrate forms\n"
7675                            "    Migrate froms to local server")
7676                 },
7677                 {
7678                         "printers",
7679                         rpc_printer_migrate_printers,
7680                         NET_TRANSPORT_RPC,
7681                         N_("Migrate printers to local server"),
7682                         N_("net rpc printer migrate printers\n"
7683                            "    Migrate printers to local server")
7684                 },
7685                 {
7686                         "security",
7687                         rpc_printer_migrate_security,
7688                         NET_TRANSPORT_RPC,
7689                         N_("Mirgate printer ACLs to local server"),
7690                         N_("net rpc printer migrate security\n"
7691                            "    Mirgate printer ACLs to local server")
7692                 },
7693                 {
7694                         "settings",
7695                         rpc_printer_migrate_settings,
7696                         NET_TRANSPORT_RPC,
7697                         N_("Migrate printer settings to local server"),
7698                         N_("net rpc printer migrate settings\n"
7699                            "    Migrate printer settings to local server")
7700                 },
7701                 {NULL, NULL, 0, NULL, NULL}
7702         };
7703
7704         return net_run_function(c, argc, argv, "net rpc printer migrate",func);
7705 }
7706
7707
7708 /**
7709  * List printers on a remote RPC server.
7710  *
7711  * @param c     A net_context structure.
7712  * @param argc  Standard main() style argc.
7713  * @param argv  Standard main() style argv. Initial components are already
7714  *              stripped.
7715  *
7716  * @return A shell status integer (0 for success).
7717  **/
7718 static int rpc_printer_list(struct net_context *c, int argc, const char **argv)
7719 {
7720         if (c->display_usage) {
7721                 d_printf(  "%s\n"
7722                            "net rpc printer list\n"
7723                            "    %s\n",
7724                          _("Usage:"),
7725                          _("List printers on a remote RPC server"));
7726                 return 0;
7727         }
7728
7729         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7730                                rpc_printer_list_internals,
7731                                argc, argv);
7732 }
7733
7734 /**
7735  * List printer-drivers on a remote RPC server.
7736  *
7737  * @param c     A net_context structure.
7738  * @param argc  Standard main() style argc.
7739  * @param argv  Standard main() style argv. Initial components are already
7740  *              stripped.
7741  *
7742  * @return A shell status integer (0 for success).
7743  **/
7744 static int rpc_printer_driver_list(struct net_context *c, int argc,
7745                                    const char **argv)
7746 {
7747         if (c->display_usage) {
7748                 d_printf(  "%s\n"
7749                            "net rpc printer driver\n"
7750                            "    %s\n",
7751                          _("Usage:"),
7752                          _("List printer-drivers on a remote RPC server"));
7753                 return 0;
7754         }
7755
7756         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7757                                rpc_printer_driver_list_internals,
7758                                argc, argv);
7759 }
7760
7761 /**
7762  * Publish printer in ADS via MSRPC.
7763  *
7764  * @param c     A net_context structure.
7765  * @param argc  Standard main() style argc.
7766  * @param argv  Standard main() style argv. Initial components are already
7767  *              stripped.
7768  *
7769  * @return A shell status integer (0 for success).
7770  **/
7771 static int rpc_printer_publish_publish(struct net_context *c, int argc,
7772                                        const char **argv)
7773 {
7774         if (c->display_usage) {
7775                 d_printf(  "%s\n"
7776                            "net rpc printer publish publish\n"
7777                            "     %s\n",
7778                          _("Usage:"),
7779                          _("Publish printer in ADS via MSRPC"));
7780                 return 0;
7781         }
7782
7783         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7784                                rpc_printer_publish_publish_internals,
7785                                argc, argv);
7786 }
7787
7788 /**
7789  * Update printer in ADS via MSRPC.
7790  *
7791  * @param c     A net_context structure.
7792  * @param argc  Standard main() style argc.
7793  * @param argv  Standard main() style argv. Initial components are already
7794  *              stripped.
7795  *
7796  * @return A shell status integer (0 for success).
7797  **/
7798 static int rpc_printer_publish_update(struct net_context *c, int argc, const char **argv)
7799 {
7800         if (c->display_usage) {
7801                 d_printf(  "%s\n"
7802                            "net rpc printer publish update\n"
7803                            "    %s\n",
7804                          _("Usage:"),
7805                          _("Update printer in ADS via MSRPC"));
7806                 return 0;
7807         }
7808
7809         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7810                                rpc_printer_publish_update_internals,
7811                                argc, argv);
7812 }
7813
7814 /**
7815  * UnPublish printer in ADS via MSRPC.
7816  *
7817  * @param c     A net_context structure.
7818  * @param argc  Standard main() style argc.
7819  * @param argv  Standard main() style argv. Initial components are already
7820  *              stripped.
7821  *
7822  * @return A shell status integer (0 for success).
7823  **/
7824 static int rpc_printer_publish_unpublish(struct net_context *c, int argc,
7825                                          const char **argv)
7826 {
7827         if (c->display_usage) {
7828                 d_printf(  "%s\n"
7829                            "net rpc printer publish unpublish\n"
7830                            "    %s\n",
7831                          _("Usage:\n"),
7832                          _("UnPublish printer in ADS via MSRPC"));
7833                 return 0;
7834         }
7835
7836         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7837                                rpc_printer_publish_unpublish_internals,
7838                                argc, argv);
7839 }
7840
7841 /**
7842  * List published printers via MSRPC.
7843  *
7844  * @param c     A net_context structure.
7845  * @param argc  Standard main() style argc.
7846  * @param argv  Standard main() style argv. Initial components are already
7847  *              stripped.
7848  *
7849  * @return A shell status integer (0 for success).
7850  **/
7851 static int rpc_printer_publish_list(struct net_context *c, int argc,
7852                                     const char **argv)
7853 {
7854         if (c->display_usage) {
7855                 d_printf(  "%s\n"
7856                            "net rpc printer publish list\n"
7857                            "    %s\n",
7858                          _("Usage:"),
7859                          _("List published printers via MSRPC"));
7860                 return 0;
7861         }
7862
7863         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7864                                rpc_printer_publish_list_internals,
7865                                argc, argv);
7866 }
7867
7868
7869 /**
7870  * Publish printer in ADS.
7871  *
7872  * @param c     A net_context structure.
7873  * @param argc  Standard main() style argc.
7874  * @param argv  Standard main() style argv. Initial components are already
7875  *              stripped.
7876  *
7877  * @return A shell status integer (0 for success).
7878  **/
7879 static int rpc_printer_publish(struct net_context *c, int argc,
7880                                const char **argv)
7881 {
7882
7883         struct functable func[] = {
7884                 {
7885                         "publish",
7886                         rpc_printer_publish_publish,
7887                         NET_TRANSPORT_RPC,
7888                         N_("Publish printer in AD"),
7889                         N_("net rpc printer publish publish\n"
7890                            "    Publish printer in AD")
7891                 },
7892                 {
7893                         "update",
7894                         rpc_printer_publish_update,
7895                         NET_TRANSPORT_RPC,
7896                         N_("Update printer in AD"),
7897                         N_("net rpc printer publish update\n"
7898                            "    Update printer in AD")
7899                 },
7900                 {
7901                         "unpublish",
7902                         rpc_printer_publish_unpublish,
7903                         NET_TRANSPORT_RPC,
7904                         N_("Unpublish printer"),
7905                         N_("net rpc printer publish unpublish\n"
7906                            "    Unpublish printer")
7907                 },
7908                 {
7909                         "list",
7910                         rpc_printer_publish_list,
7911                         NET_TRANSPORT_RPC,
7912                         N_("List published printers"),
7913                         N_("net rpc printer publish list\n"
7914                            "    List published printers")
7915                 },
7916                 {NULL, NULL, 0, NULL, NULL}
7917         };
7918
7919         if (argc == 0) {
7920                 if (c->display_usage) {
7921                         d_printf(_("Usage:\n"));
7922                         d_printf(_("net rpc printer publish\n"
7923                                    "    List published printers\n"
7924                                    "    Alias of net rpc printer publish "
7925                                    "list\n"));
7926                         net_display_usage_from_functable(func);
7927                         return 0;
7928                 }
7929                 return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7930                                rpc_printer_publish_list_internals,
7931                                argc, argv);
7932         }
7933
7934         return net_run_function(c, argc, argv, "net rpc printer publish",func);
7935
7936 }
7937
7938
7939 /**
7940  * Display rpc printer help page.
7941  *
7942  * @param c     A net_context structure.
7943  * @param argc  Standard main() style argc.
7944  * @param argv  Standard main() style argv. Initial components are already
7945  *              stripped.
7946  **/
7947 int rpc_printer_usage(struct net_context *c, int argc, const char **argv)
7948 {
7949         d_printf(_("net rpc printer LIST [printer] [misc. options] [targets]\n"
7950                    "\tlists all printers on print-server\n\n"));
7951         d_printf(_("net rpc printer DRIVER [printer] [misc. options] [targets]\n"
7952                    "\tlists all printer-drivers on print-server\n\n"));
7953         d_printf(_("net rpc printer PUBLISH action [printer] [misc. options] [targets]\n"
7954                    "\tpublishes printer settings in Active Directory\n"
7955                    "\taction can be one of PUBLISH, UPDATE, UNPUBLISH or LIST\n\n"));
7956         d_printf(_("net rpc printer MIGRATE PRINTERS [printer] [misc. options] [targets]"
7957                    "\n\tmigrates printers from remote to local server\n\n"));
7958         d_printf(_("net rpc printer MIGRATE SETTINGS [printer] [misc. options] [targets]"
7959                    "\n\tmigrates printer-settings from remote to local server\n\n"));
7960         d_printf(_("net rpc printer MIGRATE DRIVERS [printer] [misc. options] [targets]"
7961                    "\n\tmigrates printer-drivers from remote to local server\n\n"));
7962         d_printf(_("net rpc printer MIGRATE FORMS [printer] [misc. options] [targets]"
7963                    "\n\tmigrates printer-forms from remote to local server\n\n"));
7964         d_printf(_("net rpc printer MIGRATE SECURITY [printer] [misc. options] [targets]"
7965                    "\n\tmigrates printer-ACLs from remote to local server\n\n"));
7966         d_printf(_("net rpc printer MIGRATE ALL [printer] [misc. options] [targets]"
7967                    "\n\tmigrates drivers, forms, queues, settings and acls from\n"
7968                    "\tremote to local print-server\n\n"));
7969         net_common_methods_usage(c, argc, argv);
7970         net_common_flags_usage(c, argc, argv);
7971         d_printf(_(
7972          "\t-v or --verbose\t\t\tgive verbose output\n"
7973          "\t      --destination\t\tmigration target server (default: localhost)\n"));
7974
7975         return -1;
7976 }
7977
7978 /**
7979  * 'net rpc printer' entrypoint.
7980  *
7981  * @param c     A net_context structure.
7982  * @param argc  Standard main() style argc.
7983  * @param argv  Standard main() style argv. Initial components are already
7984  *              stripped.
7985  **/
7986 int net_rpc_printer(struct net_context *c, int argc, const char **argv)
7987 {
7988         struct functable func[] = {
7989                 {
7990                         "list",
7991                         rpc_printer_list,
7992                         NET_TRANSPORT_RPC,
7993                         N_("List all printers on print server"),
7994                         N_("net rpc printer list\n"
7995                            "    List all printers on print server")
7996                 },
7997                 {
7998                         "migrate",
7999                         rpc_printer_migrate,
8000                         NET_TRANSPORT_RPC,
8001                         N_("Migrate printer to local server"),
8002                         N_("net rpc printer migrate\n"
8003                            "    Migrate printer to local server")
8004                 },
8005                 {
8006                         "driver",
8007                         rpc_printer_driver_list,
8008                         NET_TRANSPORT_RPC,
8009                         N_("List printer drivers"),
8010                         N_("net rpc printer driver\n"
8011                            "    List printer drivers")
8012                 },
8013                 {
8014                         "publish",
8015                         rpc_printer_publish,
8016                         NET_TRANSPORT_RPC,
8017                         N_("Publish printer in AD"),
8018                         N_("net rpc printer publish\n"
8019                            "    Publish printer in AD")
8020                 },
8021                 {NULL, NULL, 0, NULL, NULL}
8022         };
8023
8024         if (argc == 0) {
8025                 if (c->display_usage) {
8026                         d_printf(_("Usage:\n"));
8027                         d_printf(_("net rpc printer\n"
8028                                    "    List printers\n"));
8029                         net_display_usage_from_functable(func);
8030                         return 0;
8031                 }
8032                 return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
8033                                rpc_printer_list_internals,
8034                                argc, argv);
8035         }
8036
8037         return net_run_function(c, argc, argv, "net rpc printer", func);
8038 }
8039
8040 /**
8041  * 'net rpc' entrypoint.
8042  *
8043  * @param c     A net_context structure.
8044  * @param argc  Standard main() style argc.
8045  * @param argv  Standard main() style argv. Initial components are already
8046  *              stripped.
8047  **/
8048
8049 int net_rpc(struct net_context *c, int argc, const char **argv)
8050 {
8051         NET_API_STATUS status;
8052
8053         struct functable func[] = {
8054                 {
8055                         "audit",
8056                         net_rpc_audit,
8057                         NET_TRANSPORT_RPC,
8058                         N_("Modify global audit settings"),
8059                         N_("net rpc audit\n"
8060                            "    Modify global audit settings")
8061                 },
8062                 {
8063                         "info",
8064                         net_rpc_info,
8065                         NET_TRANSPORT_RPC,
8066                         N_("Show basic info about a domain"),
8067                         N_("net rpc info\n"
8068                            "    Show basic info about a domain")
8069                 },
8070                 {
8071                         "join",
8072                         net_rpc_join,
8073                         NET_TRANSPORT_RPC,
8074                         N_("Join a domain"),
8075                         N_("net rpc join\n"
8076                            "    Join a domain")
8077                 },
8078                 {
8079                         "oldjoin",
8080                         net_rpc_oldjoin,
8081                         NET_TRANSPORT_RPC,
8082                         N_("Join a domain created in server manager"),
8083                         N_("net rpc oldjoin\n"
8084                            "    Join a domain created in server manager")
8085                 },
8086                 {
8087                         "testjoin",
8088                         net_rpc_testjoin,
8089                         NET_TRANSPORT_RPC,
8090                         N_("Test that a join is valid"),
8091                         N_("net rpc testjoin\n"
8092                            "    Test that a join is valid")
8093                 },
8094                 {
8095                         "user",
8096                         net_rpc_user,
8097                         NET_TRANSPORT_RPC,
8098                         N_("List/modify users"),
8099                         N_("net rpc user\n"
8100                            "    List/modify users")
8101                 },
8102                 {
8103                         "password",
8104                         rpc_user_password,
8105                         NET_TRANSPORT_RPC,
8106                         N_("Change a user password"),
8107                         N_("net rpc password\n"
8108                            "    Change a user password\n"
8109                            "    Alias for net rpc user password")
8110                 },
8111                 {
8112                         "group",
8113                         net_rpc_group,
8114                         NET_TRANSPORT_RPC,
8115                         N_("List/modify groups"),
8116                         N_("net rpc group\n"
8117                            "    List/modify groups")
8118                 },
8119                 {
8120                         "share",
8121                         net_rpc_share,
8122                         NET_TRANSPORT_RPC,
8123                         N_("List/modify shares"),
8124                         N_("net rpc share\n"
8125                            "    List/modify shares")
8126                 },
8127                 {
8128                         "file",
8129                         net_rpc_file,
8130                         NET_TRANSPORT_RPC,
8131                         N_("List open files"),
8132                         N_("net rpc file\n"
8133                            "    List open files")
8134                 },
8135                 {
8136                         "printer",
8137                         net_rpc_printer,
8138                         NET_TRANSPORT_RPC,
8139                         N_("List/modify printers"),
8140                         N_("net rpc printer\n"
8141                            "    List/modify printers")
8142                 },
8143                 {
8144                         "changetrustpw",
8145                         net_rpc_changetrustpw,
8146                         NET_TRANSPORT_RPC,
8147                         N_("Change trust account password"),
8148                         N_("net rpc changetrustpw\n"
8149                            "    Change trust account password")
8150                 },
8151                 {
8152                         "trustdom",
8153                         rpc_trustdom,
8154                         NET_TRANSPORT_RPC,
8155                         N_("Modify domain trusts"),
8156                         N_("net rpc trustdom\n"
8157                            "    Modify domain trusts")
8158                 },
8159                 {
8160                         "abortshutdown",
8161                         rpc_shutdown_abort,
8162                         NET_TRANSPORT_RPC,
8163                         N_("Abort a remote shutdown"),
8164                         N_("net rpc abortshutdown\n"
8165                            "    Abort a remote shutdown")
8166                 },
8167                 {
8168                         "shutdown",
8169                         rpc_shutdown,
8170                         NET_TRANSPORT_RPC,
8171                         N_("Shutdown a remote server"),
8172                         N_("net rpc shutdown\n"
8173                            "    Shutdown a remote server")
8174                 },
8175                 {
8176                         "samdump",
8177                         rpc_samdump,
8178                         NET_TRANSPORT_RPC,
8179                         N_("Dump SAM data of remote NT PDC"),
8180                         N_("net rpc samdump\n"
8181                            "    Dump SAM data of remote NT PDC")
8182                 },
8183                 {
8184                         "vampire",
8185                         rpc_vampire,
8186                         NET_TRANSPORT_RPC,
8187                         N_("Sync a remote NT PDC's data into local passdb"),
8188                         N_("net rpc vampire\n"
8189                            "    Sync a remote NT PDC's data into local passdb")
8190                 },
8191                 {
8192                         "getsid",
8193                         net_rpc_getsid,
8194                         NET_TRANSPORT_RPC,
8195                         N_("Fetch the domain sid into local secrets.tdb"),
8196                         N_("net rpc getsid\n"
8197                            "    Fetch the domain sid into local secrets.tdb")
8198                 },
8199                 {
8200                         "rights",
8201                         net_rpc_rights,
8202                         NET_TRANSPORT_RPC,
8203                         N_("Manage privileges assigned to SID"),
8204                         N_("net rpc rights\n"
8205                            "    Manage privileges assigned to SID")
8206                 },
8207                 {
8208                         "service",
8209                         net_rpc_service,
8210                         NET_TRANSPORT_RPC,
8211                         N_("Start/stop/query remote services"),
8212                         N_("net rpc service\n"
8213                            "    Start/stop/query remote services")
8214                 },
8215                 {
8216                         "registry",
8217                         net_rpc_registry,
8218                         NET_TRANSPORT_RPC,
8219                         N_("Manage registry hives"),
8220                         N_("net rpc registry\n"
8221                            "    Manage registry hives")
8222                 },
8223                 {
8224                         "shell",
8225                         net_rpc_shell,
8226                         NET_TRANSPORT_RPC,
8227                         N_("Open interactive shell on remote server"),
8228                         N_("net rpc shell\n"
8229                            "    Open interactive shell on remote server")
8230                 },
8231                 {
8232                         "trust",
8233                         net_rpc_trust,
8234                         NET_TRANSPORT_RPC,
8235                         N_("Manage trusts"),
8236                         N_("net rpc trust\n"
8237                            "    Manage trusts")
8238                 },
8239                 {
8240                         "conf",
8241                         net_rpc_conf,
8242                         NET_TRANSPORT_RPC,
8243                         N_("Configure a remote samba server"),
8244                         N_("net rpc conf\n"
8245                            "    Configure a remote samba server")
8246                 },
8247                 {NULL, NULL, 0, NULL, NULL}
8248         };
8249
8250         status = libnetapi_net_init(&c->netapi_ctx);
8251         if (status != 0) {
8252                 return -1;
8253         }
8254         libnetapi_set_username(c->netapi_ctx, c->opt_user_name);
8255         libnetapi_set_password(c->netapi_ctx, c->opt_password);
8256         if (c->opt_kerberos) {
8257                 libnetapi_set_use_kerberos(c->netapi_ctx);
8258         }
8259         if (c->opt_ccache) {
8260                 libnetapi_set_use_ccache(c->netapi_ctx);
8261         }
8262
8263         return net_run_function(c, argc, argv, "net rpc", func);
8264 }