CVE-2013-4408:s3:Ensure LookupNames replies arrays are range checked.
[vlendec/samba-autobuild/.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, ctx->cli,
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         if (group_rids.count != 1) {
1840                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
1841                 goto done;
1842         }
1843         if (name_types.count != 1) {
1844                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
1845                 goto done;
1846         }
1847
1848         switch (name_types.ids[0])
1849         {
1850         case SID_NAME_DOM_GRP:
1851                 status = dcerpc_samr_OpenGroup(b, mem_ctx,
1852                                                &domain_pol,
1853                                                MAXIMUM_ALLOWED_ACCESS,
1854                                                group_rids.ids[0],
1855                                                &group_pol,
1856                                                &result);
1857                 if (!NT_STATUS_IS_OK(status)) {
1858                         d_fprintf(stderr, _("Request open_group failed"));
1859                         goto done;
1860                 }
1861
1862                 if (!NT_STATUS_IS_OK(result)) {
1863                         status = result;
1864                         d_fprintf(stderr, _("Request open_group failed"));
1865                         goto done;
1866                 }
1867
1868                 group_rid = group_rids.ids[0];
1869
1870                 status = dcerpc_samr_QueryGroupMember(b, mem_ctx,
1871                                                       &group_pol,
1872                                                       &rids,
1873                                                       &result);
1874                 if (!NT_STATUS_IS_OK(status)) {
1875                         d_fprintf(stderr,
1876                                   _("Unable to query group members of %s"),
1877                                   argv[0]);
1878                         goto done;
1879                 }
1880
1881                 if (!NT_STATUS_IS_OK(result)) {
1882                         status = result;
1883                         d_fprintf(stderr,
1884                                   _("Unable to query group members of %s"),
1885                                   argv[0]);
1886                         goto done;
1887                 }
1888
1889                 if (c->opt_verbose) {
1890                         d_printf(
1891                                 _("Domain Group %s (rid: %d) has %d members\n"),
1892                                 argv[0],group_rid, rids->count);
1893                 }
1894
1895                 /* Check if group is anyone's primary group */
1896                 for (i = 0; i < rids->count; i++)
1897                 {
1898                         status = dcerpc_samr_OpenUser(b, mem_ctx,
1899                                                       &domain_pol,
1900                                                       MAXIMUM_ALLOWED_ACCESS,
1901                                                       rids->rids[i],
1902                                                       &user_pol,
1903                                                       &result);
1904                         if (!NT_STATUS_IS_OK(status)) {
1905                                 d_fprintf(stderr,
1906                                         _("Unable to open group member %d\n"),
1907                                         rids->rids[i]);
1908                                 goto done;
1909                         }
1910
1911                         if (!NT_STATUS_IS_OK(result)) {
1912                                 status = result;
1913                                 d_fprintf(stderr,
1914                                         _("Unable to open group member %d\n"),
1915                                         rids->rids[i]);
1916                                 goto done;
1917                         }
1918
1919                         status = dcerpc_samr_QueryUserInfo(b, mem_ctx,
1920                                                            &user_pol,
1921                                                            21,
1922                                                            &info,
1923                                                            &result);
1924                         if (!NT_STATUS_IS_OK(status)) {
1925                                 d_fprintf(stderr,
1926                                         _("Unable to lookup userinfo for group "
1927                                           "member %d\n"),
1928                                         rids->rids[i]);
1929                                 goto done;
1930                         }
1931
1932                         if (!NT_STATUS_IS_OK(result)) {
1933                                 status = result;
1934                                 d_fprintf(stderr,
1935                                         _("Unable to lookup userinfo for group "
1936                                           "member %d\n"),
1937                                         rids->rids[i]);
1938                                 goto done;
1939                         }
1940
1941                         if (info->info21.primary_gid == group_rid) {
1942                                 if (c->opt_verbose) {
1943                                         d_printf(_("Group is primary group "
1944                                                    "of %s\n"),
1945                                                 info->info21.account_name.string);
1946                                 }
1947                                 group_is_primary = true;
1948                         }
1949
1950                         dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1951                 }
1952
1953                 if (group_is_primary) {
1954                         d_fprintf(stderr, _("Unable to delete group because "
1955                                  "some of it's members have it as primary "
1956                                  "group\n"));
1957                         status = NT_STATUS_MEMBERS_PRIMARY_GROUP;
1958                         goto done;
1959                 }
1960
1961                 /* remove all group members */
1962                 for (i = 0; i < rids->count; i++)
1963                 {
1964                         if (c->opt_verbose)
1965                                 d_printf(_("Remove group member %d..."),
1966                                         rids->rids[i]);
1967                         status = dcerpc_samr_DeleteGroupMember(b, mem_ctx,
1968                                                                &group_pol,
1969                                                                rids->rids[i],
1970                                                                &result);
1971                         if (!NT_STATUS_IS_OK(status)) {
1972                                 goto done;
1973                         }
1974                         status = result;
1975                         if (NT_STATUS_IS_OK(result)) {
1976                                 if (c->opt_verbose)
1977                                         d_printf(_("ok\n"));
1978                         } else {
1979                                 if (c->opt_verbose)
1980                                         d_printf("%s\n", _("failed"));
1981                                 goto done;
1982                         }
1983                 }
1984
1985                 status = dcerpc_samr_DeleteDomainGroup(b, mem_ctx,
1986                                                        &group_pol,
1987                                                        &result);
1988                 if (!NT_STATUS_IS_OK(status)) {
1989                         break;
1990                 }
1991
1992                 status = result;
1993
1994                 break;
1995         /* removing a local group is easier... */
1996         case SID_NAME_ALIAS:
1997                 status = dcerpc_samr_OpenAlias(b, mem_ctx,
1998                                                &domain_pol,
1999                                                MAXIMUM_ALLOWED_ACCESS,
2000                                                group_rids.ids[0],
2001                                                &group_pol,
2002                                                &result);
2003                 if (!NT_STATUS_IS_OK(status)) {
2004                         d_fprintf(stderr, _("Request open_alias failed\n"));
2005                         goto done;
2006                 }
2007                 if (!NT_STATUS_IS_OK(result)) {
2008                         status = result;
2009                         d_fprintf(stderr, _("Request open_alias failed\n"));
2010                         goto done;
2011                 }
2012
2013                 status = dcerpc_samr_DeleteDomAlias(b, mem_ctx,
2014                                                     &group_pol,
2015                                                     &result);
2016                 if (!NT_STATUS_IS_OK(status)) {
2017                         break;
2018                 }
2019
2020                 status = result;
2021
2022                 break;
2023         default:
2024                 d_fprintf(stderr, _("%s is of type %s. This command is only "
2025                                     "for deleting local or global groups\n"),
2026                         argv[0],sid_type_lookup(name_types.ids[0]));
2027                 status = NT_STATUS_UNSUCCESSFUL;
2028                 goto done;
2029         }
2030
2031         if (NT_STATUS_IS_OK(status)) {
2032                 if (c->opt_verbose)
2033                         d_printf(_("Deleted %s '%s'\n"),
2034                                  sid_type_lookup(name_types.ids[0]), argv[0]);
2035         } else {
2036                 d_fprintf(stderr, _("Deleting of %s failed: %s\n"), argv[0],
2037                         get_friendly_nt_error_msg(status));
2038         }
2039
2040  done:
2041         return status;
2042
2043 }
2044
2045 static int rpc_group_delete(struct net_context *c, int argc, const char **argv)
2046 {
2047         return run_rpc_command(c, NULL, &ndr_table_samr, 0,
2048                                rpc_group_delete_internals, argc,argv);
2049 }
2050
2051 static int rpc_group_add_internals(struct net_context *c, int argc, const char **argv)
2052 {
2053         NET_API_STATUS status;
2054         struct GROUP_INFO_1 info1;
2055         uint32_t parm_error = 0;
2056
2057         if (argc != 1 || c->display_usage) {
2058                 rpc_group_usage(c, argc, argv);
2059                 return 0;
2060         }
2061
2062         ZERO_STRUCT(info1);
2063
2064         info1.grpi1_name = argv[0];
2065         if (c->opt_comment && strlen(c->opt_comment) > 0) {
2066                 info1.grpi1_comment = c->opt_comment;
2067         }
2068
2069         status = NetGroupAdd(c->opt_host, 1, (uint8_t *)&info1, &parm_error);
2070
2071         if (status != 0) {
2072                 d_fprintf(stderr,
2073                         _("Failed to add group '%s' with error: %s.\n"),
2074                         argv[0], libnetapi_get_error_string(c->netapi_ctx,
2075                                                             status));
2076                 return -1;
2077         } else {
2078                 d_printf(_("Added group '%s'.\n"), argv[0]);
2079         }
2080
2081         return 0;
2082 }
2083
2084 static int rpc_alias_add_internals(struct net_context *c, int argc, const char **argv)
2085 {
2086         NET_API_STATUS status;
2087         struct LOCALGROUP_INFO_1 info1;
2088         uint32_t parm_error = 0;
2089
2090         if (argc != 1 || c->display_usage) {
2091                 rpc_group_usage(c, argc, argv);
2092                 return 0;
2093         }
2094
2095         ZERO_STRUCT(info1);
2096
2097         info1.lgrpi1_name = argv[0];
2098         if (c->opt_comment && strlen(c->opt_comment) > 0) {
2099                 info1.lgrpi1_comment = c->opt_comment;
2100         }
2101
2102         status = NetLocalGroupAdd(c->opt_host, 1, (uint8_t *)&info1, &parm_error);
2103
2104         if (status != 0) {
2105                 d_fprintf(stderr,
2106                         _("Failed to add alias '%s' with error: %s.\n"),
2107                         argv[0], libnetapi_get_error_string(c->netapi_ctx,
2108                                                             status));
2109                 return -1;
2110         } else {
2111                 d_printf(_("Added alias '%s'.\n"), argv[0]);
2112         }
2113
2114         return 0;
2115 }
2116
2117 static int rpc_group_add(struct net_context *c, int argc, const char **argv)
2118 {
2119         if (c->opt_localgroup)
2120                 return rpc_alias_add_internals(c, argc, argv);
2121
2122         return rpc_group_add_internals(c, argc, argv);
2123 }
2124
2125 static NTSTATUS get_sid_from_name(struct cli_state *cli,
2126                                 TALLOC_CTX *mem_ctx,
2127                                 const char *name,
2128                                 struct dom_sid *sid,
2129                                 enum lsa_SidType *type)
2130 {
2131         struct dom_sid *sids = NULL;
2132         enum lsa_SidType *types = NULL;
2133         struct rpc_pipe_client *pipe_hnd = NULL;
2134         struct policy_handle lsa_pol;
2135         NTSTATUS status, result;
2136         struct dcerpc_binding_handle *b;
2137
2138         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
2139                                           &pipe_hnd);
2140         if (!NT_STATUS_IS_OK(status)) {
2141                 goto done;
2142         }
2143
2144         b = pipe_hnd->binding_handle;
2145
2146         status = rpccli_lsa_open_policy(pipe_hnd, mem_ctx, false,
2147                                      SEC_FLAG_MAXIMUM_ALLOWED, &lsa_pol);
2148
2149         if (!NT_STATUS_IS_OK(status)) {
2150                 goto done;
2151         }
2152
2153         status = rpccli_lsa_lookup_names(pipe_hnd, mem_ctx, &lsa_pol, 1,
2154                                       &name, NULL, 1, &sids, &types);
2155
2156         if (NT_STATUS_IS_OK(status)) {
2157                 sid_copy(sid, &sids[0]);
2158                 *type = types[0];
2159         }
2160
2161         dcerpc_lsa_Close(b, mem_ctx, &lsa_pol, &result);
2162
2163  done:
2164         if (pipe_hnd) {
2165                 TALLOC_FREE(pipe_hnd);
2166         }
2167
2168         if (!NT_STATUS_IS_OK(status) && (strncasecmp_m(name, "S-", 2) == 0)) {
2169
2170                 /* Try as S-1-5-whatever */
2171
2172                 struct dom_sid tmp_sid;
2173
2174                 if (string_to_sid(&tmp_sid, name)) {
2175                         sid_copy(sid, &tmp_sid);
2176                         *type = SID_NAME_UNKNOWN;
2177                         status = NT_STATUS_OK;
2178                 }
2179         }
2180
2181         return status;
2182 }
2183
2184 static NTSTATUS rpc_add_groupmem(struct rpc_pipe_client *pipe_hnd,
2185                                 TALLOC_CTX *mem_ctx,
2186                                 const struct dom_sid *group_sid,
2187                                 const char *member)
2188 {
2189         struct policy_handle connect_pol, domain_pol;
2190         NTSTATUS status, result;
2191         uint32 group_rid;
2192         struct policy_handle group_pol;
2193         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
2194
2195         struct samr_Ids rids, rid_types;
2196         struct lsa_String lsa_acct_name;
2197
2198         struct dom_sid sid;
2199
2200         sid_copy(&sid, group_sid);
2201
2202         if (!sid_split_rid(&sid, &group_rid)) {
2203                 return NT_STATUS_UNSUCCESSFUL;
2204         }
2205
2206         /* Get sam policy handle */
2207         status = dcerpc_samr_Connect2(b, mem_ctx,
2208                                       pipe_hnd->desthost,
2209                                       MAXIMUM_ALLOWED_ACCESS,
2210                                       &connect_pol,
2211                                       &result);
2212         if (!NT_STATUS_IS_OK(status)) {
2213                 return status;
2214         }
2215         if (!NT_STATUS_IS_OK(result)) {
2216                 return result;
2217         }
2218
2219         /* Get domain policy handle */
2220         status = dcerpc_samr_OpenDomain(b, mem_ctx,
2221                                         &connect_pol,
2222                                         MAXIMUM_ALLOWED_ACCESS,
2223                                         &sid,
2224                                         &domain_pol,
2225                                         &result);
2226         if (!NT_STATUS_IS_OK(status)) {
2227                 return status;
2228         }
2229         if (!NT_STATUS_IS_OK(result)) {
2230                 return result;
2231         }
2232
2233         init_lsa_String(&lsa_acct_name, member);
2234
2235         status = dcerpc_samr_LookupNames(b, mem_ctx,
2236                                          &domain_pol,
2237                                          1,
2238                                          &lsa_acct_name,
2239                                          &rids,
2240                                          &rid_types,
2241                                          &result);
2242         if (!NT_STATUS_IS_OK(status)) {
2243                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
2244                           member);
2245                 goto done;
2246         }
2247
2248         if (!NT_STATUS_IS_OK(result)) {
2249                 status = result;
2250                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
2251                           member);
2252                 goto done;
2253         }
2254         if (rids.count != 1) {
2255                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
2256                 goto done;
2257         }
2258         if (rid_types.count != 1) {
2259                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
2260                 goto done;
2261         }
2262
2263         status = dcerpc_samr_OpenGroup(b, mem_ctx,
2264                                        &domain_pol,
2265                                        MAXIMUM_ALLOWED_ACCESS,
2266                                        group_rid,
2267                                        &group_pol,
2268                                        &result);
2269         if (!NT_STATUS_IS_OK(status)) {
2270                 goto done;
2271         }
2272
2273         if (!NT_STATUS_IS_OK(result)) {
2274                 status = result;
2275                 goto done;
2276         }
2277
2278         status = dcerpc_samr_AddGroupMember(b, mem_ctx,
2279                                             &group_pol,
2280                                             rids.ids[0],
2281                                             0x0005, /* unknown flags */
2282                                             &result);
2283         if (!NT_STATUS_IS_OK(status)) {
2284                 goto done;
2285         }
2286
2287         status = result;
2288
2289  done:
2290         dcerpc_samr_Close(b, mem_ctx, &connect_pol, &result);
2291         return status;
2292 }
2293
2294 static NTSTATUS rpc_add_aliasmem(struct rpc_pipe_client *pipe_hnd,
2295                                  struct cli_state *cli,
2296                                  TALLOC_CTX *mem_ctx,
2297                                  const struct dom_sid *alias_sid,
2298                                  const char *member)
2299 {
2300         struct policy_handle connect_pol, domain_pol;
2301         NTSTATUS status, result;
2302         uint32 alias_rid;
2303         struct policy_handle alias_pol;
2304         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
2305
2306         struct dom_sid member_sid;
2307         enum lsa_SidType member_type;
2308
2309         struct dom_sid sid;
2310
2311         sid_copy(&sid, alias_sid);
2312
2313         if (!sid_split_rid(&sid, &alias_rid)) {
2314                 return NT_STATUS_UNSUCCESSFUL;
2315         }
2316
2317         result = get_sid_from_name(cli, mem_ctx,
2318                                    member, &member_sid, &member_type);
2319
2320         if (!NT_STATUS_IS_OK(result)) {
2321                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
2322                           member);
2323                 return result;
2324         }
2325
2326         /* Get sam policy handle */
2327         status = dcerpc_samr_Connect2(b, mem_ctx,
2328                                       pipe_hnd->desthost,
2329                                       MAXIMUM_ALLOWED_ACCESS,
2330                                       &connect_pol,
2331                                       &result);
2332         if (!NT_STATUS_IS_OK(status)) {
2333                 goto done;
2334         }
2335         if (!NT_STATUS_IS_OK(result)) {
2336                 status = result;
2337                 goto done;
2338         }
2339
2340         /* Get domain policy handle */
2341         status = dcerpc_samr_OpenDomain(b, mem_ctx,
2342                                         &connect_pol,
2343                                         MAXIMUM_ALLOWED_ACCESS,
2344                                         &sid,
2345                                         &domain_pol,
2346                                         &result);
2347         if (!NT_STATUS_IS_OK(status)) {
2348                 goto done;
2349         }
2350         if (!NT_STATUS_IS_OK(result)) {
2351                 status = result;
2352                 goto done;
2353         }
2354
2355         status = dcerpc_samr_OpenAlias(b, mem_ctx,
2356                                        &domain_pol,
2357                                        MAXIMUM_ALLOWED_ACCESS,
2358                                        alias_rid,
2359                                        &alias_pol,
2360                                        &result);
2361         if (!NT_STATUS_IS_OK(status)) {
2362                 return status;
2363         }
2364         if (!NT_STATUS_IS_OK(result)) {
2365                 return result;
2366         }
2367
2368         status = dcerpc_samr_AddAliasMember(b, mem_ctx,
2369                                             &alias_pol,
2370                                             &member_sid,
2371                                             &result);
2372         if (!NT_STATUS_IS_OK(status)) {
2373                 return status;
2374         }
2375
2376         status = result;
2377
2378  done:
2379         dcerpc_samr_Close(b, mem_ctx, &connect_pol, &result);
2380         return status;
2381 }
2382
2383 static NTSTATUS rpc_group_addmem_internals(struct net_context *c,
2384                                         const struct dom_sid *domain_sid,
2385                                         const char *domain_name,
2386                                         struct cli_state *cli,
2387                                         struct rpc_pipe_client *pipe_hnd,
2388                                         TALLOC_CTX *mem_ctx,
2389                                         int argc,
2390                                         const char **argv)
2391 {
2392         struct dom_sid group_sid;
2393         enum lsa_SidType group_type;
2394
2395         if (argc != 2 || c->display_usage) {
2396                 d_printf("%s\n%s",
2397                          _("Usage:"),
2398                          _("net rpc group addmem <group> <member>\n"
2399                            "  Add a member to a group\n"
2400                            "    group\tGroup to add member to\n"
2401                            "    member\tMember to add to group\n"));
2402                 return NT_STATUS_UNSUCCESSFUL;
2403         }
2404
2405         if (!NT_STATUS_IS_OK(get_sid_from_name(cli, mem_ctx, argv[0],
2406                                                &group_sid, &group_type))) {
2407                 d_fprintf(stderr, _("Could not lookup group name %s\n"),
2408                           argv[0]);
2409                 return NT_STATUS_UNSUCCESSFUL;
2410         }
2411
2412         if (group_type == SID_NAME_DOM_GRP) {
2413                 NTSTATUS result = rpc_add_groupmem(pipe_hnd, mem_ctx,
2414                                                    &group_sid, argv[1]);
2415
2416                 if (!NT_STATUS_IS_OK(result)) {
2417                         d_fprintf(stderr, _("Could not add %s to %s: %s\n"),
2418                                  argv[1], argv[0], nt_errstr(result));
2419                 }
2420                 return result;
2421         }
2422
2423         if (group_type == SID_NAME_ALIAS) {
2424                 NTSTATUS result = rpc_add_aliasmem(pipe_hnd, cli, mem_ctx,
2425                                                    &group_sid, argv[1]);
2426
2427                 if (!NT_STATUS_IS_OK(result)) {
2428                         d_fprintf(stderr, _("Could not add %s to %s: %s\n"),
2429                                  argv[1], argv[0], nt_errstr(result));
2430                 }
2431                 return result;
2432         }
2433
2434         d_fprintf(stderr, _("Can only add members to global or local groups "
2435                  "which %s is not\n"), argv[0]);
2436
2437         return NT_STATUS_UNSUCCESSFUL;
2438 }
2439
2440 static int rpc_group_addmem(struct net_context *c, int argc, const char **argv)
2441 {
2442         return run_rpc_command(c, NULL, &ndr_table_samr, 0,
2443                                rpc_group_addmem_internals,
2444                                argc, argv);
2445 }
2446
2447 static NTSTATUS rpc_del_groupmem(struct net_context *c,
2448                                 struct rpc_pipe_client *pipe_hnd,
2449                                 TALLOC_CTX *mem_ctx,
2450                                 const struct dom_sid *group_sid,
2451                                 const char *member)
2452 {
2453         struct policy_handle connect_pol, domain_pol;
2454         NTSTATUS status, result;
2455         uint32 group_rid;
2456         struct policy_handle group_pol;
2457         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
2458
2459         struct samr_Ids rids, rid_types;
2460         struct lsa_String lsa_acct_name;
2461
2462         struct dom_sid sid;
2463
2464         sid_copy(&sid, group_sid);
2465
2466         if (!sid_split_rid(&sid, &group_rid))
2467                 return NT_STATUS_UNSUCCESSFUL;
2468
2469         /* Get sam policy handle */
2470         status = dcerpc_samr_Connect2(b, mem_ctx,
2471                                       pipe_hnd->desthost,
2472                                       MAXIMUM_ALLOWED_ACCESS,
2473                                       &connect_pol,
2474                                       &result);
2475         if (!NT_STATUS_IS_OK(status)) {
2476                 return status;
2477         }
2478         if (!NT_STATUS_IS_OK(result)) {
2479                 return result;
2480         }
2481
2482
2483         /* Get domain policy handle */
2484         status = dcerpc_samr_OpenDomain(b, mem_ctx,
2485                                         &connect_pol,
2486                                         MAXIMUM_ALLOWED_ACCESS,
2487                                         &sid,
2488                                         &domain_pol,
2489                                         &result);
2490         if (!NT_STATUS_IS_OK(status)) {
2491                 return status;
2492         }
2493         if (!NT_STATUS_IS_OK(result)) {
2494                 return result;
2495         }
2496
2497         init_lsa_String(&lsa_acct_name, member);
2498
2499         status = dcerpc_samr_LookupNames(b, mem_ctx,
2500                                          &domain_pol,
2501                                          1,
2502                                          &lsa_acct_name,
2503                                          &rids,
2504                                          &rid_types,
2505                                          &result);
2506         if (!NT_STATUS_IS_OK(status)) {
2507                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
2508                           member);
2509                 goto done;
2510         }
2511
2512         if (!NT_STATUS_IS_OK(result)) {
2513                 status = result;
2514                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
2515                           member);
2516                 goto done;
2517         }
2518         if (rids.count != 1) {
2519                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
2520                 goto done;
2521         }
2522         if (rid_types.count != 1) {
2523                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
2524                 goto done;
2525         }
2526
2527         status = dcerpc_samr_OpenGroup(b, mem_ctx,
2528                                        &domain_pol,
2529                                        MAXIMUM_ALLOWED_ACCESS,
2530                                        group_rid,
2531                                        &group_pol,
2532                                        &result);
2533         if (!NT_STATUS_IS_OK(status)) {
2534                 goto done;
2535         }
2536         if (!NT_STATUS_IS_OK(result)) {
2537                 status = result;
2538                 goto done;
2539         }
2540
2541         status = dcerpc_samr_DeleteGroupMember(b, mem_ctx,
2542                                                &group_pol,
2543                                                rids.ids[0],
2544                                                &result);
2545         if (!NT_STATUS_IS_OK(status)) {
2546                 goto done;
2547         }
2548
2549         status = result;
2550  done:
2551         dcerpc_samr_Close(b, mem_ctx, &connect_pol, &result);
2552         return status;
2553 }
2554
2555 static NTSTATUS rpc_del_aliasmem(struct rpc_pipe_client *pipe_hnd,
2556                                  struct cli_state *cli,
2557                                  TALLOC_CTX *mem_ctx,
2558                                  const struct dom_sid *alias_sid,
2559                                  const char *member)
2560 {
2561         struct policy_handle connect_pol, domain_pol;
2562         NTSTATUS status, result;
2563         uint32 alias_rid;
2564         struct policy_handle alias_pol;
2565         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
2566
2567         struct dom_sid member_sid;
2568         enum lsa_SidType member_type;
2569
2570         struct dom_sid sid;
2571
2572         sid_copy(&sid, alias_sid);
2573
2574         if (!sid_split_rid(&sid, &alias_rid))
2575                 return NT_STATUS_UNSUCCESSFUL;
2576
2577         result = get_sid_from_name(cli, mem_ctx,
2578                                    member, &member_sid, &member_type);
2579
2580         if (!NT_STATUS_IS_OK(result)) {
2581                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
2582                           member);
2583                 return result;
2584         }
2585
2586         /* Get sam policy handle */
2587         status = dcerpc_samr_Connect2(b, mem_ctx,
2588                                       pipe_hnd->desthost,
2589                                       MAXIMUM_ALLOWED_ACCESS,
2590                                       &connect_pol,
2591                                       &result);
2592         if (!NT_STATUS_IS_OK(status)) {
2593                 goto done;
2594         }
2595         if (!NT_STATUS_IS_OK(result)) {
2596                 status = result;
2597                 goto done;
2598         }
2599
2600         /* Get domain policy handle */
2601         status = dcerpc_samr_OpenDomain(b, mem_ctx,
2602                                         &connect_pol,
2603                                         MAXIMUM_ALLOWED_ACCESS,
2604                                         &sid,
2605                                         &domain_pol,
2606                                         &result);
2607         if (!NT_STATUS_IS_OK(status)) {
2608                 goto done;
2609         }
2610         if (!NT_STATUS_IS_OK(result)) {
2611                 status = result;
2612                 goto done;
2613         }
2614
2615         status = dcerpc_samr_OpenAlias(b, mem_ctx,
2616                                        &domain_pol,
2617                                        MAXIMUM_ALLOWED_ACCESS,
2618                                        alias_rid,
2619                                        &alias_pol,
2620                                        &result);
2621         if (!NT_STATUS_IS_OK(status)) {
2622                 return status;
2623         }
2624
2625         if (!NT_STATUS_IS_OK(result)) {
2626                 return result;
2627         }
2628
2629         status = dcerpc_samr_DeleteAliasMember(b, mem_ctx,
2630                                                &alias_pol,
2631                                                &member_sid,
2632                                                &result);
2633
2634         if (!NT_STATUS_IS_OK(status)) {
2635                 return status;
2636         }
2637
2638         status = result;
2639
2640  done:
2641         dcerpc_samr_Close(b, mem_ctx, &connect_pol, &result);
2642         return status;
2643 }
2644
2645 static NTSTATUS rpc_group_delmem_internals(struct net_context *c,
2646                                         const struct dom_sid *domain_sid,
2647                                         const char *domain_name,
2648                                         struct cli_state *cli,
2649                                         struct rpc_pipe_client *pipe_hnd,
2650                                         TALLOC_CTX *mem_ctx,
2651                                         int argc,
2652                                         const char **argv)
2653 {
2654         struct dom_sid group_sid;
2655         enum lsa_SidType group_type;
2656
2657         if (argc != 2 || c->display_usage) {
2658                 d_printf("%s\n%s",
2659                          _("Usage:"),
2660                          _("net rpc group delmem <group> <member>\n"
2661                            "  Delete a member from a group\n"
2662                            "    group\tGroup to delete member from\n"
2663                            "    member\tMember to delete from group\n"));
2664                 return NT_STATUS_UNSUCCESSFUL;
2665         }
2666
2667         if (!NT_STATUS_IS_OK(get_sid_from_name(cli, mem_ctx, argv[0],
2668                                                &group_sid, &group_type))) {
2669                 d_fprintf(stderr, _("Could not lookup group name %s\n"),
2670                           argv[0]);
2671                 return NT_STATUS_UNSUCCESSFUL;
2672         }
2673
2674         if (group_type == SID_NAME_DOM_GRP) {
2675                 NTSTATUS result = rpc_del_groupmem(c, pipe_hnd, mem_ctx,
2676                                                    &group_sid, argv[1]);
2677
2678                 if (!NT_STATUS_IS_OK(result)) {
2679                         d_fprintf(stderr, _("Could not del %s from %s: %s\n"),
2680                                  argv[1], argv[0], nt_errstr(result));
2681                 }
2682                 return result;
2683         }
2684
2685         if (group_type == SID_NAME_ALIAS) {
2686                 NTSTATUS result = rpc_del_aliasmem(pipe_hnd, cli, mem_ctx,
2687                                                    &group_sid, argv[1]);
2688
2689                 if (!NT_STATUS_IS_OK(result)) {
2690                         d_fprintf(stderr, _("Could not del %s from %s: %s\n"),
2691                                  argv[1], argv[0], nt_errstr(result));
2692                 }
2693                 return result;
2694         }
2695
2696         d_fprintf(stderr, _("Can only delete members from global or local "
2697                  "groups which %s is not\n"), argv[0]);
2698
2699         return NT_STATUS_UNSUCCESSFUL;
2700 }
2701
2702 static int rpc_group_delmem(struct net_context *c, int argc, const char **argv)
2703 {
2704         return run_rpc_command(c, NULL, &ndr_table_samr, 0,
2705                                rpc_group_delmem_internals,
2706                                argc, argv);
2707 }
2708
2709 /**
2710  * List groups on a remote RPC server.
2711  *
2712  * All parameters are provided by the run_rpc_command function, except for
2713  * argc, argv which are passes through.
2714  *
2715  * @param domain_sid The domain sid acquired from the remote server.
2716  * @param cli A cli_state connected to the server.
2717  * @param mem_ctx Talloc context, destroyed on completion of the function.
2718  * @param argc  Standard main() style argc.
2719  * @param argv  Standard main() style argv. Initial components are already
2720  *              stripped.
2721  *
2722  * @return Normal NTSTATUS return.
2723  **/
2724
2725 static NTSTATUS rpc_group_list_internals(struct net_context *c,
2726                                         const struct dom_sid *domain_sid,
2727                                         const char *domain_name,
2728                                         struct cli_state *cli,
2729                                         struct rpc_pipe_client *pipe_hnd,
2730                                         TALLOC_CTX *mem_ctx,
2731                                         int argc,
2732                                         const char **argv)
2733 {
2734         struct policy_handle connect_pol, domain_pol;
2735         NTSTATUS status, result;
2736         uint32 start_idx=0, max_entries=250, num_entries, i, loop_count = 0;
2737         struct samr_SamArray *groups = NULL;
2738         bool global = false;
2739         bool local = false;
2740         bool builtin = false;
2741         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
2742
2743         if (c->display_usage) {
2744                 d_printf("%s\n%s",
2745                          _("Usage:"),
2746                          _("net rpc group list [global] [local] [builtin]\n"
2747                            "  List groups on RPC server\n"
2748                            "    global\tList global groups\n"
2749                            "    local\tList local groups\n"
2750                            "    builtin\tList builtin groups\n"
2751                            "    If none of global, local or builtin is "
2752                            "specified, all three options are considered "
2753                            "set\n"));
2754                 return NT_STATUS_OK;
2755         }
2756
2757         if (argc == 0) {
2758                 global = true;
2759                 local = true;
2760                 builtin = true;
2761         }
2762
2763         for (i=0; i<argc; i++) {
2764                 if (strequal(argv[i], "global"))
2765                         global = true;
2766
2767                 if (strequal(argv[i], "local"))
2768                         local = true;
2769
2770                 if (strequal(argv[i], "builtin"))
2771                         builtin = true;
2772         }
2773
2774         /* Get sam policy handle */
2775
2776         status = dcerpc_samr_Connect2(b, mem_ctx,
2777                                       pipe_hnd->desthost,
2778                                       MAXIMUM_ALLOWED_ACCESS,
2779                                       &connect_pol,
2780                                       &result);
2781         if (!NT_STATUS_IS_OK(status)) {
2782                 goto done;
2783         }
2784         if (!NT_STATUS_IS_OK(result)) {
2785                 status = result;
2786                 goto done;
2787         }
2788
2789         /* Get domain policy handle */
2790
2791         status = dcerpc_samr_OpenDomain(b, mem_ctx,
2792                                         &connect_pol,
2793                                         MAXIMUM_ALLOWED_ACCESS,
2794                                         discard_const_p(struct dom_sid2, domain_sid),
2795                                         &domain_pol,
2796                                         &result);
2797         if (!NT_STATUS_IS_OK(status)) {
2798                 goto done;
2799         }
2800         if (!NT_STATUS_IS_OK(result)) {
2801                 status = result;
2802                 goto done;
2803         }
2804
2805         /* Query domain groups */
2806         if (c->opt_long_list_entries)
2807                 d_printf(_("\nGroup name            Comment"
2808                            "\n-----------------------------\n"));
2809         do {
2810                 uint32_t max_size, total_size, returned_size;
2811                 union samr_DispInfo info;
2812
2813                 if (!global) break;
2814
2815                 dcerpc_get_query_dispinfo_params(
2816                         loop_count, &max_entries, &max_size);
2817
2818                 status = dcerpc_samr_QueryDisplayInfo(b, mem_ctx,
2819                                                       &domain_pol,
2820                                                       3,
2821                                                       start_idx,
2822                                                       max_entries,
2823                                                       max_size,
2824                                                       &total_size,
2825                                                       &returned_size,
2826                                                       &info,
2827                                                       &result);
2828                 if (!NT_STATUS_IS_OK(status)) {
2829                         goto done;
2830                 }
2831                 num_entries = info.info3.count;
2832                 start_idx += info.info3.count;
2833
2834                 if (!NT_STATUS_IS_OK(result) &&
2835                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES))
2836                         break;
2837
2838                 for (i = 0; i < num_entries; i++) {
2839
2840                         const char *group = NULL;
2841                         const char *desc = NULL;
2842
2843                         group = info.info3.entries[i].account_name.string;
2844                         desc = info.info3.entries[i].description.string;
2845
2846                         if (c->opt_long_list_entries)
2847                                 printf("%-21.21s %-50.50s\n",
2848                                        group, desc);
2849                         else
2850                                 printf("%s\n", group);
2851                 }
2852         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
2853         /* query domain aliases */
2854         start_idx = 0;
2855         do {
2856                 if (!local) break;
2857
2858                 status = dcerpc_samr_EnumDomainAliases(b, mem_ctx,
2859                                                        &domain_pol,
2860                                                        &start_idx,
2861                                                        &groups,
2862                                                        0xffff,
2863                                                        &num_entries,
2864                                                        &result);
2865                 if (!NT_STATUS_IS_OK(status)) {
2866                         goto done;
2867                 }
2868                 if (!NT_STATUS_IS_OK(result) &&
2869                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES))
2870                         break;
2871
2872                 for (i = 0; i < num_entries; i++) {
2873
2874                         const char *description = NULL;
2875
2876                         if (c->opt_long_list_entries) {
2877
2878                                 struct policy_handle alias_pol;
2879                                 union samr_AliasInfo *info = NULL;
2880                                 NTSTATUS _result;
2881
2882                                 status = dcerpc_samr_OpenAlias(b, mem_ctx,
2883                                                                &domain_pol,
2884                                                                0x8,
2885                                                                groups->entries[i].idx,
2886                                                                &alias_pol,
2887                                                                &_result);
2888                                 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(_result)) {
2889                                         status = dcerpc_samr_QueryAliasInfo(b, mem_ctx,
2890                                                                             &alias_pol,
2891                                                                             3,
2892                                                                             &info,
2893                                                                             &_result);
2894                                         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(_result)) {
2895                                                 status = dcerpc_samr_Close(b, mem_ctx,
2896                                                                            &alias_pol,
2897                                                                            &_result);
2898                                                 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(_result)) {
2899                                                         description = info->description.string;
2900                                                 }
2901                                         }
2902                                 }
2903                         }
2904
2905                         if (description != NULL) {
2906                                 printf("%-21.21s %-50.50s\n",
2907                                        groups->entries[i].name.string,
2908                                        description);
2909                         } else {
2910                                 printf("%s\n", groups->entries[i].name.string);
2911                         }
2912                 }
2913         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
2914         dcerpc_samr_Close(b, mem_ctx, &domain_pol, &result);
2915         /* Get builtin policy handle */
2916
2917         status = dcerpc_samr_OpenDomain(b, mem_ctx,
2918                                         &connect_pol,
2919                                         MAXIMUM_ALLOWED_ACCESS,
2920                                         discard_const_p(struct dom_sid2, &global_sid_Builtin),
2921                                         &domain_pol,
2922                                         &result);
2923         if (!NT_STATUS_IS_OK(status)) {
2924                 goto done;
2925         }
2926         if (!NT_STATUS_IS_OK(result)) {
2927                 status = result;
2928                 goto done;
2929         }
2930
2931         /* query builtin aliases */
2932         start_idx = 0;
2933         do {
2934                 if (!builtin) break;
2935
2936                 status = dcerpc_samr_EnumDomainAliases(b, mem_ctx,
2937                                                        &domain_pol,
2938                                                        &start_idx,
2939                                                        &groups,
2940                                                        max_entries,
2941                                                        &num_entries,
2942                                                        &result);
2943                 if (!NT_STATUS_IS_OK(status)) {
2944                         break;
2945                 }
2946                 if (!NT_STATUS_IS_OK(result) &&
2947                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES)) {
2948                         status = result;
2949                         break;
2950                 }
2951
2952                 for (i = 0; i < num_entries; i++) {
2953
2954                         const char *description = NULL;
2955
2956                         if (c->opt_long_list_entries) {
2957
2958                                 struct policy_handle alias_pol;
2959                                 union samr_AliasInfo *info = NULL;
2960                                 NTSTATUS _result;
2961
2962                                 status = dcerpc_samr_OpenAlias(b, mem_ctx,
2963                                                                &domain_pol,
2964                                                                0x8,
2965                                                                groups->entries[i].idx,
2966                                                                &alias_pol,
2967                                                                &_result);
2968                                 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(_result)) {
2969                                         status = dcerpc_samr_QueryAliasInfo(b, mem_ctx,
2970                                                                             &alias_pol,
2971                                                                             3,
2972                                                                             &info,
2973                                                                             &_result);
2974                                         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(_result)) {
2975                                                 status = dcerpc_samr_Close(b, mem_ctx,
2976                                                                            &alias_pol,
2977                                                                            &_result);
2978                                                 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(_result)) {
2979                                                         description = info->description.string;
2980                                                 }
2981                                         }
2982                                 }
2983                         }
2984
2985                         if (description != NULL) {
2986                                 printf("%-21.21s %-50.50s\n",
2987                                        groups->entries[i].name.string,
2988                                        description);
2989                         } else {
2990                                 printf("%s\n", groups->entries[i].name.string);
2991                         }
2992                 }
2993         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
2994
2995         status = result;
2996
2997  done:
2998         return status;
2999 }
3000
3001 static int rpc_group_list(struct net_context *c, int argc, const char **argv)
3002 {
3003         return run_rpc_command(c, NULL, &ndr_table_samr, 0,
3004                                rpc_group_list_internals,
3005                                argc, argv);
3006 }
3007
3008 static NTSTATUS rpc_list_group_members(struct net_context *c,
3009                                         struct rpc_pipe_client *pipe_hnd,
3010                                         TALLOC_CTX *mem_ctx,
3011                                         const char *domain_name,
3012                                         const struct dom_sid *domain_sid,
3013                                         struct policy_handle *domain_pol,
3014                                         uint32 rid)
3015 {
3016         NTSTATUS result, status;
3017         struct policy_handle group_pol;
3018         uint32 num_members, *group_rids;
3019         int i;
3020         struct samr_RidAttrArray *rids = NULL;
3021         struct lsa_Strings names;
3022         struct samr_Ids types;
3023         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
3024
3025         fstring sid_str;
3026         sid_to_fstring(sid_str, domain_sid);
3027
3028         status = dcerpc_samr_OpenGroup(b, mem_ctx,
3029                                        domain_pol,
3030                                        MAXIMUM_ALLOWED_ACCESS,
3031                                        rid,
3032                                        &group_pol,
3033                                        &result);
3034         if (!NT_STATUS_IS_OK(status)) {
3035                 return status;
3036         }
3037         if (!NT_STATUS_IS_OK(result)) {
3038                 return result;
3039         }
3040
3041         status = dcerpc_samr_QueryGroupMember(b, mem_ctx,
3042                                               &group_pol,
3043                                               &rids,
3044                                               &result);
3045         if (!NT_STATUS_IS_OK(status)) {
3046                 return status;
3047         }
3048         if (!NT_STATUS_IS_OK(result)) {
3049                 return result;
3050         }
3051
3052         num_members = rids->count;
3053         group_rids = rids->rids;
3054
3055         while (num_members > 0) {
3056                 int this_time = 512;
3057
3058                 if (num_members < this_time)
3059                         this_time = num_members;
3060
3061                 status = dcerpc_samr_LookupRids(b, mem_ctx,
3062                                                 domain_pol,
3063                                                 this_time,
3064                                                 group_rids,
3065                                                 &names,
3066                                                 &types,
3067                                                 &result);
3068                 if (!NT_STATUS_IS_OK(status)) {
3069                         return status;
3070                 }
3071                 if (!NT_STATUS_IS_OK(result)) {
3072                         return result;
3073                 }
3074
3075                 /* We only have users as members, but make the output
3076                    the same as the output of alias members */
3077
3078                 for (i = 0; i < this_time; i++) {
3079
3080                         if (c->opt_long_list_entries) {
3081                                 printf("%s-%d %s\\%s %d\n", sid_str,
3082                                        group_rids[i], domain_name,
3083                                        names.names[i].string,
3084                                        SID_NAME_USER);
3085                         } else {
3086                                 printf("%s\\%s\n", domain_name,
3087                                         names.names[i].string);
3088                         }
3089                 }
3090
3091                 num_members -= this_time;
3092                 group_rids += 512;
3093         }
3094
3095         return NT_STATUS_OK;
3096 }
3097
3098 static NTSTATUS rpc_list_alias_members(struct net_context *c,
3099                                        struct rpc_pipe_client *pipe_hnd,
3100                                        struct cli_state *cli,
3101                                        TALLOC_CTX *mem_ctx,
3102                                        struct policy_handle *domain_pol,
3103                                        uint32 rid)
3104 {
3105         NTSTATUS result, status;
3106         struct rpc_pipe_client *lsa_pipe;
3107         struct policy_handle alias_pol, lsa_pol;
3108         uint32 num_members;
3109         struct dom_sid *alias_sids;
3110         char **domains;
3111         char **names;
3112         enum lsa_SidType *types;
3113         int i;
3114         struct lsa_SidArray sid_array;
3115         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
3116
3117         status = dcerpc_samr_OpenAlias(b, mem_ctx,
3118                                        domain_pol,
3119                                        MAXIMUM_ALLOWED_ACCESS,
3120                                        rid,
3121                                        &alias_pol,
3122                                        &result);
3123         if (!NT_STATUS_IS_OK(status)) {
3124                 return status;
3125         }
3126         if (!NT_STATUS_IS_OK(result)) {
3127                 return result;
3128         }
3129
3130         status = dcerpc_samr_GetMembersInAlias(b, mem_ctx,
3131                                                &alias_pol,
3132                                                &sid_array,
3133                                                &result);
3134         if (!NT_STATUS_IS_OK(status)) {
3135                 d_fprintf(stderr, _("Couldn't list alias members\n"));
3136                 return status;
3137         }
3138         if (!NT_STATUS_IS_OK(result)) {
3139                 d_fprintf(stderr, _("Couldn't list alias members\n"));
3140                 return result;
3141         }
3142
3143         num_members = sid_array.num_sids;
3144
3145         if (num_members == 0) {
3146                 return NT_STATUS_OK;
3147         }
3148
3149         result = cli_rpc_pipe_open_noauth(cli,
3150                                           &ndr_table_lsarpc,
3151                                           &lsa_pipe);
3152         if (!NT_STATUS_IS_OK(result)) {
3153                 d_fprintf(stderr, _("Couldn't open LSA pipe. Error was %s\n"),
3154                         nt_errstr(result) );
3155                 return result;
3156         }
3157
3158         result = rpccli_lsa_open_policy(lsa_pipe, mem_ctx, true,
3159                                      SEC_FLAG_MAXIMUM_ALLOWED, &lsa_pol);
3160
3161         if (!NT_STATUS_IS_OK(result)) {
3162                 d_fprintf(stderr, _("Couldn't open LSA policy handle\n"));
3163                 TALLOC_FREE(lsa_pipe);
3164                 return result;
3165         }
3166
3167         alias_sids = talloc_zero_array(mem_ctx, struct dom_sid, num_members);
3168         if (!alias_sids) {
3169                 d_fprintf(stderr, _("Out of memory\n"));
3170                 TALLOC_FREE(lsa_pipe);
3171                 return NT_STATUS_NO_MEMORY;
3172         }
3173
3174         for (i=0; i<num_members; i++) {
3175                 sid_copy(&alias_sids[i], sid_array.sids[i].sid);
3176         }
3177
3178         result = rpccli_lsa_lookup_sids(lsa_pipe, mem_ctx, &lsa_pol,
3179                                      num_members,  alias_sids,
3180                                      &domains, &names, &types);
3181
3182         if (!NT_STATUS_IS_OK(result) &&
3183             !NT_STATUS_EQUAL(result, STATUS_SOME_UNMAPPED)) {
3184                 d_fprintf(stderr, _("Couldn't lookup SIDs\n"));
3185                 TALLOC_FREE(lsa_pipe);
3186                 return result;
3187         }
3188
3189         for (i = 0; i < num_members; i++) {
3190                 fstring sid_str;
3191                 sid_to_fstring(sid_str, &alias_sids[i]);
3192
3193                 if (c->opt_long_list_entries) {
3194                         printf("%s %s\\%s %d\n", sid_str,
3195                                domains[i] ? domains[i] : _("*unknown*"),
3196                                names[i] ? names[i] : _("*unknown*"), types[i]);
3197                 } else {
3198                         if (domains[i])
3199                                 printf("%s\\%s\n", domains[i], names[i]);
3200                         else
3201                                 printf("%s\n", sid_str);
3202                 }
3203         }
3204
3205         TALLOC_FREE(lsa_pipe);
3206         return NT_STATUS_OK;
3207 }
3208
3209 static NTSTATUS rpc_group_members_internals(struct net_context *c,
3210                                         const struct dom_sid *domain_sid,
3211                                         const char *domain_name,
3212                                         struct cli_state *cli,
3213                                         struct rpc_pipe_client *pipe_hnd,
3214                                         TALLOC_CTX *mem_ctx,
3215                                         int argc,
3216                                         const char **argv)
3217 {
3218         NTSTATUS result, status;
3219         struct policy_handle connect_pol, domain_pol;
3220         struct samr_Ids rids, rid_types;
3221         struct lsa_String lsa_acct_name;
3222         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
3223
3224         /* Get sam policy handle */
3225
3226         status = dcerpc_samr_Connect2(b, mem_ctx,
3227                                       pipe_hnd->desthost,
3228                                       MAXIMUM_ALLOWED_ACCESS,
3229                                       &connect_pol,
3230                                       &result);
3231         if (!NT_STATUS_IS_OK(status)) {
3232                 return status;
3233         }
3234         if (!NT_STATUS_IS_OK(result)) {
3235                 return result;
3236         }
3237
3238         /* Get domain policy handle */
3239
3240         status = dcerpc_samr_OpenDomain(b, mem_ctx,
3241                                         &connect_pol,
3242                                         MAXIMUM_ALLOWED_ACCESS,
3243                                         discard_const_p(struct dom_sid2, domain_sid),
3244                                         &domain_pol,
3245                                         &result);
3246         if (!NT_STATUS_IS_OK(status)) {
3247                 return status;
3248         }
3249         if (!NT_STATUS_IS_OK(result)) {
3250                 return result;
3251         }
3252
3253         init_lsa_String(&lsa_acct_name, argv[0]); /* sure? */
3254
3255         status = dcerpc_samr_LookupNames(b, mem_ctx,
3256                                          &domain_pol,
3257                                          1,
3258                                          &lsa_acct_name,
3259                                          &rids,
3260                                          &rid_types,
3261                                          &result);
3262         if (!NT_STATUS_IS_OK(status)) {
3263                 return status;
3264         }
3265
3266         if (!NT_STATUS_IS_OK(result)) {
3267
3268                 /* Ok, did not find it in the global sam, try with builtin */
3269
3270                 struct dom_sid sid_Builtin;
3271
3272                 dcerpc_samr_Close(b, mem_ctx, &domain_pol, &result);
3273
3274                 sid_copy(&sid_Builtin, &global_sid_Builtin);
3275
3276                 status = dcerpc_samr_OpenDomain(b, mem_ctx,
3277                                                 &connect_pol,
3278                                                 MAXIMUM_ALLOWED_ACCESS,
3279                                                 &sid_Builtin,
3280                                                 &domain_pol,
3281                                                 &result);
3282                 if (!NT_STATUS_IS_OK(status)) {
3283                         return status;
3284                 }
3285                 if (!NT_STATUS_IS_OK(result)) {
3286                         d_fprintf(stderr, _("Couldn't find group %s\n"),
3287                                   argv[0]);
3288                         return result;
3289                 }
3290
3291                 status = dcerpc_samr_LookupNames(b, mem_ctx,
3292                                                  &domain_pol,
3293                                                  1,
3294                                                  &lsa_acct_name,
3295                                                  &rids,
3296                                                  &rid_types,
3297                                                  &result);
3298                 if (!NT_STATUS_IS_OK(status)) {
3299                         return status;
3300                 }
3301                 if (!NT_STATUS_IS_OK(result)) {
3302                         d_fprintf(stderr, _("Couldn't find group %s\n"),
3303                                   argv[0]);
3304                         return result;
3305                 }
3306         }
3307
3308         if (rids.count != 1) {
3309                 d_fprintf(stderr, _("Couldn't find group %s\n"),
3310                           argv[0]);
3311                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
3312         }
3313         if (rid_types.count != 1) {
3314                 d_fprintf(stderr, _("Couldn't find group %s\n"),
3315                           argv[0]);
3316                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
3317         }
3318
3319
3320         if (rid_types.ids[0] == SID_NAME_DOM_GRP) {
3321                 return rpc_list_group_members(c, pipe_hnd, mem_ctx, domain_name,
3322                                               domain_sid, &domain_pol,
3323                                               rids.ids[0]);
3324         }
3325
3326         if (rid_types.ids[0] == SID_NAME_ALIAS) {
3327                 return rpc_list_alias_members(c, pipe_hnd, cli, mem_ctx, &domain_pol,
3328                                               rids.ids[0]);
3329         }
3330
3331         return NT_STATUS_NO_SUCH_GROUP;
3332 }
3333
3334 static int rpc_group_members(struct net_context *c, int argc, const char **argv)
3335 {
3336         if (argc != 1 || c->display_usage) {
3337                 return rpc_group_usage(c, argc, argv);
3338         }
3339
3340         return run_rpc_command(c, NULL, &ndr_table_samr, 0,
3341                                rpc_group_members_internals,
3342                                argc, argv);
3343 }
3344
3345 static int rpc_group_rename_internals(struct net_context *c, int argc, const char **argv)
3346 {
3347         NET_API_STATUS status;
3348         struct GROUP_INFO_0 g0;
3349         uint32_t parm_err;
3350
3351         if (argc != 2) {
3352                 d_printf(_("Usage:\n"));
3353                 d_printf("net rpc group rename group newname\n");
3354                 return -1;
3355         }
3356
3357         g0.grpi0_name = argv[1];
3358
3359         status = NetGroupSetInfo(c->opt_host,
3360                                  argv[0],
3361                                  0,
3362                                  (uint8_t *)&g0,
3363                                  &parm_err);
3364
3365         if (status != 0) {
3366                 d_fprintf(stderr, _("Renaming group %s failed with: %s\n"),
3367                         argv[0], libnetapi_get_error_string(c->netapi_ctx,
3368                         status));
3369                 return -1;
3370         }
3371
3372         return 0;
3373 }
3374
3375 static int rpc_group_rename(struct net_context *c, int argc, const char **argv)
3376 {
3377         if (argc != 2 || c->display_usage) {
3378                 return rpc_group_usage(c, argc, argv);
3379         }
3380
3381         return rpc_group_rename_internals(c, argc, argv);
3382 }
3383
3384 /**
3385  * 'net rpc group' entrypoint.
3386  * @param argc  Standard main() style argc.
3387  * @param argv  Standard main() style argv. Initial components are already
3388  *              stripped.
3389  **/
3390
3391 int net_rpc_group(struct net_context *c, int argc, const char **argv)
3392 {
3393         NET_API_STATUS status;
3394
3395         struct functable func[] = {
3396                 {
3397                         "add",
3398                         rpc_group_add,
3399                         NET_TRANSPORT_RPC,
3400                         N_("Create specified group"),
3401                         N_("net rpc group add\n"
3402                            "    Create specified group")
3403                 },
3404                 {
3405                         "delete",
3406                         rpc_group_delete,
3407                         NET_TRANSPORT_RPC,
3408                         N_("Delete specified group"),
3409                         N_("net rpc group delete\n"
3410                            "    Delete specified group")
3411                 },
3412                 {
3413                         "addmem",
3414                         rpc_group_addmem,
3415                         NET_TRANSPORT_RPC,
3416                         N_("Add member to group"),
3417                         N_("net rpc group addmem\n"
3418                            "    Add member to group")
3419                 },
3420                 {
3421                         "delmem",
3422                         rpc_group_delmem,
3423                         NET_TRANSPORT_RPC,
3424                         N_("Remove member from group"),
3425                         N_("net rpc group delmem\n"
3426                            "    Remove member from group")
3427                 },
3428                 {
3429                         "list",
3430                         rpc_group_list,
3431                         NET_TRANSPORT_RPC,
3432                         N_("List groups"),
3433                         N_("net rpc group list\n"
3434                            "    List groups")
3435                 },
3436                 {
3437                         "members",
3438                         rpc_group_members,
3439                         NET_TRANSPORT_RPC,
3440                         N_("List group members"),
3441                         N_("net rpc group members\n"
3442                            "    List group members")
3443                 },
3444                 {
3445                         "rename",
3446                         rpc_group_rename,
3447                         NET_TRANSPORT_RPC,
3448                         N_("Rename group"),
3449                         N_("net rpc group rename\n"
3450                            "    Rename group")
3451                 },
3452                 {NULL, NULL, 0, NULL, NULL}
3453         };
3454
3455         status = libnetapi_net_init(&c->netapi_ctx);
3456         if (status != 0) {
3457                 return -1;
3458         }
3459         libnetapi_set_username(c->netapi_ctx, c->opt_user_name);
3460         libnetapi_set_password(c->netapi_ctx, c->opt_password);
3461         if (c->opt_kerberos) {
3462                 libnetapi_set_use_kerberos(c->netapi_ctx);
3463         }
3464
3465         if (argc == 0) {
3466                 if (c->display_usage) {
3467                         d_printf(_("Usage:\n"));
3468                         d_printf(_("net rpc group\n"
3469                                    "    Alias for net rpc group list global "
3470                                    "local builtin\n"));
3471                         net_display_usage_from_functable(func);
3472                         return 0;
3473                 }
3474
3475                 return run_rpc_command(c, NULL, &ndr_table_samr, 0,
3476                                        rpc_group_list_internals,
3477                                        argc, argv);
3478         }
3479
3480         return net_run_function(c, argc, argv, "net rpc group", func);
3481 }
3482
3483 /****************************************************************************/
3484
3485 static int rpc_share_usage(struct net_context *c, int argc, const char **argv)
3486 {
3487         return net_share_usage(c, argc, argv);
3488 }
3489
3490 /**
3491  * Add a share on a remote RPC server.
3492  *
3493  * @param argc  Standard main() style argc.
3494  * @param argv  Standard main() style argv. Initial components are already
3495  *              stripped.
3496  *
3497  * @return A shell status integer (0 for success).
3498  **/
3499
3500 static int rpc_share_add(struct net_context *c, int argc, const char **argv)
3501 {
3502         NET_API_STATUS status;
3503         char *sharename;
3504         char *path;
3505         uint32 type = STYPE_DISKTREE; /* only allow disk shares to be added */
3506         uint32 num_users=0, perms=0;
3507         char *password=NULL; /* don't allow a share password */
3508         struct SHARE_INFO_2 i2;
3509         uint32_t parm_error = 0;
3510
3511         if ((argc < 1) || !strchr(argv[0], '=') || c->display_usage) {
3512                 return rpc_share_usage(c, argc, argv);
3513         }
3514
3515         if ((sharename = talloc_strdup(c, argv[0])) == NULL) {
3516                 return -1;
3517         }
3518
3519         path = strchr(sharename, '=');
3520         if (!path) {
3521                 return -1;
3522         }
3523
3524         *path++ = '\0';
3525
3526         i2.shi2_netname         = sharename;
3527         i2.shi2_type            = type;
3528         i2.shi2_remark          = c->opt_comment;
3529         i2.shi2_permissions     = perms;
3530         i2.shi2_max_uses        = c->opt_maxusers;
3531         i2.shi2_current_uses    = num_users;
3532         i2.shi2_path            = path;
3533         i2.shi2_passwd          = password;
3534
3535         status = NetShareAdd(c->opt_host,
3536                              2,
3537                              (uint8_t *)&i2,
3538                              &parm_error);
3539         if (status != 0) {
3540                 printf(_("NetShareAdd failed with: %s\n"),
3541                         libnetapi_get_error_string(c->netapi_ctx, status));
3542         }
3543
3544         return status;
3545 }
3546
3547 /**
3548  * Delete a share on a remote RPC server.
3549  *
3550  * @param domain_sid The domain sid acquired from the remote server.
3551  * @param argc  Standard main() style argc.
3552  * @param argv  Standard main() style argv. Initial components are already
3553  *              stripped.
3554  *
3555  * @return A shell status integer (0 for success).
3556  **/
3557 static int rpc_share_delete(struct net_context *c, int argc, const char **argv)
3558 {
3559         if (argc < 1 || c->display_usage) {
3560                 return rpc_share_usage(c, argc, argv);
3561         }
3562
3563         return NetShareDel(c->opt_host, argv[0], 0);
3564 }
3565
3566 /**
3567  * Formatted print of share info
3568  *
3569  * @param r  pointer to SHARE_INFO_1 to format
3570  **/
3571
3572 static void display_share_info_1(struct net_context *c,
3573                                  struct SHARE_INFO_1 *r)
3574 {
3575         if (c->opt_long_list_entries) {
3576                 d_printf("%-12s %-8.8s %-50s\n",
3577                          r->shi1_netname,
3578                          net_share_type_str(r->shi1_type & ~(STYPE_TEMPORARY|STYPE_HIDDEN)),
3579                          r->shi1_remark);
3580         } else {
3581                 d_printf("%s\n", r->shi1_netname);
3582         }
3583 }
3584
3585 static WERROR get_share_info(struct net_context *c,
3586                              struct rpc_pipe_client *pipe_hnd,
3587                              TALLOC_CTX *mem_ctx,
3588                              uint32 level,
3589                              int argc,
3590                              const char **argv,
3591                              struct srvsvc_NetShareInfoCtr *info_ctr)
3592 {
3593         WERROR result;
3594         NTSTATUS status;
3595         union srvsvc_NetShareInfo info;
3596         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
3597
3598         /* no specific share requested, enumerate all */
3599         if (argc == 0) {
3600
3601                 uint32_t preferred_len = 0xffffffff;
3602                 uint32_t total_entries = 0;
3603                 uint32_t resume_handle = 0;
3604
3605                 info_ctr->level = level;
3606
3607                 status = dcerpc_srvsvc_NetShareEnumAll(b, mem_ctx,
3608                                                        pipe_hnd->desthost,
3609                                                        info_ctr,
3610                                                        preferred_len,
3611                                                        &total_entries,
3612                                                        &resume_handle,
3613                                                        &result);
3614                 if (!NT_STATUS_IS_OK(status)) {
3615                         return ntstatus_to_werror(status);
3616                 }
3617                 return result;
3618         }
3619
3620         /* request just one share */
3621         status = dcerpc_srvsvc_NetShareGetInfo(b, mem_ctx,
3622                                                pipe_hnd->desthost,
3623                                                argv[0],
3624                                                level,
3625                                                &info,
3626                                                &result);
3627
3628         if (!NT_STATUS_IS_OK(status)) {
3629                 result = ntstatus_to_werror(status);
3630                 goto done;
3631         }
3632
3633         if (!W_ERROR_IS_OK(result)) {
3634                 goto done;
3635         }
3636
3637         /* construct ctr */
3638         ZERO_STRUCTP(info_ctr);
3639
3640         info_ctr->level = level;
3641
3642         switch (level) {
3643         case 1:
3644         {
3645                 struct srvsvc_NetShareCtr1 *ctr1;
3646
3647                 ctr1 = talloc_zero(mem_ctx, struct srvsvc_NetShareCtr1);
3648                 W_ERROR_HAVE_NO_MEMORY(ctr1);
3649
3650                 ctr1->count = 1;
3651                 ctr1->array = info.info1;
3652
3653                 info_ctr->ctr.ctr1 = ctr1;
3654
3655                 break;
3656         }
3657         case 2:
3658         {
3659                 struct srvsvc_NetShareCtr2 *ctr2;
3660
3661                 ctr2 = talloc_zero(mem_ctx, struct srvsvc_NetShareCtr2);
3662                 W_ERROR_HAVE_NO_MEMORY(ctr2);
3663
3664                 ctr2->count = 1;
3665                 ctr2->array = info.info2;
3666
3667                 info_ctr->ctr.ctr2 = ctr2;
3668
3669                 break;
3670         }
3671         case 502:
3672         {
3673                 struct srvsvc_NetShareCtr502 *ctr502;
3674
3675                 ctr502 = talloc_zero(mem_ctx, struct srvsvc_NetShareCtr502);
3676                 W_ERROR_HAVE_NO_MEMORY(ctr502);
3677
3678                 ctr502->count = 1;
3679                 ctr502->array = info.info502;
3680
3681                 info_ctr->ctr.ctr502 = ctr502;
3682
3683                 break;
3684         }
3685         } /* switch */
3686 done:
3687         return result;
3688 }
3689
3690 /***
3691  * 'net rpc share list' entrypoint.
3692  * @param argc  Standard main() style argc.
3693  * @param argv  Standard main() style argv. Initial components are already
3694  *              stripped.
3695  **/
3696 static int rpc_share_list(struct net_context *c, int argc, const char **argv)
3697 {
3698         NET_API_STATUS status;
3699         struct SHARE_INFO_1 *i1 = NULL;
3700         uint32_t entries_read = 0;
3701         uint32_t total_entries = 0;
3702         uint32_t resume_handle = 0;
3703         uint32_t i, level = 1;
3704
3705         if (c->display_usage) {
3706                 d_printf(  "%s\n"
3707                            "net rpc share list\n"
3708                            "    %s\n",
3709                          _("Usage:"),
3710                          _("List shares on remote server"));
3711                 return 0;
3712         }
3713
3714         status = NetShareEnum(c->opt_host,
3715                               level,
3716                               (uint8_t **)(void *)&i1,
3717                               (uint32_t)-1,
3718                               &entries_read,
3719                               &total_entries,
3720                               &resume_handle);
3721         if (status != 0) {
3722                 goto done;
3723         }
3724
3725         /* Display results */
3726
3727         if (c->opt_long_list_entries) {
3728                 d_printf(_(
3729         "\nEnumerating shared resources (exports) on remote server:\n\n"
3730         "\nShare name   Type     Description\n"
3731         "----------   ----     -----------\n"));
3732         }
3733         for (i = 0; i < entries_read; i++)
3734                 display_share_info_1(c, &i1[i]);
3735  done:
3736         return status;
3737 }
3738
3739 static bool check_share_availability(struct cli_state *cli, const char *netname)
3740 {
3741         NTSTATUS status;
3742
3743         status = cli_tree_connect(cli, netname, "A:", "", 0);
3744         if (!NT_STATUS_IS_OK(status)) {
3745                 d_printf(_("skipping   [%s]: not a file share.\n"), netname);
3746                 return false;
3747         }
3748
3749         status = cli_tdis(cli);
3750         if (!NT_STATUS_IS_OK(status)) {
3751                 d_printf(_("cli_tdis returned %s\n"), nt_errstr(status));
3752                 return false;
3753         }
3754
3755         return true;
3756 }
3757
3758 static bool check_share_sanity(struct net_context *c, struct cli_state *cli,
3759                                const char *netname, uint32 type)
3760 {
3761         /* only support disk shares */
3762         if (! ( type == STYPE_DISKTREE || type == (STYPE_DISKTREE | STYPE_HIDDEN)) ) {
3763                 printf(_("share [%s] is not a diskshare (type: %x)\n"), netname,
3764                        type);
3765                 return false;
3766         }
3767
3768         /* skip builtin shares */
3769         /* FIXME: should print$ be added too ? */
3770         if (strequal(netname,"IPC$") || strequal(netname,"ADMIN$") ||
3771             strequal(netname,"global"))
3772                 return false;
3773
3774         if (c->opt_exclude && in_list(netname, c->opt_exclude, false)) {
3775                 printf(_("excluding  [%s]\n"), netname);
3776                 return false;
3777         }
3778
3779         return check_share_availability(cli, netname);
3780 }
3781
3782 /**
3783  * Migrate shares from a remote RPC server to the local RPC server.
3784  *
3785  * All parameters are provided by the run_rpc_command function, except for
3786  * argc, argv which are passed through.
3787  *
3788  * @param domain_sid The domain sid acquired from the remote server.
3789  * @param cli A cli_state connected to the server.
3790  * @param mem_ctx Talloc context, destroyed on completion of the function.
3791  * @param argc  Standard main() style argc.
3792  * @param argv  Standard main() style argv. Initial components are already
3793  *              stripped.
3794  *
3795  * @return Normal NTSTATUS return.
3796  **/
3797
3798 static NTSTATUS rpc_share_migrate_shares_internals(struct net_context *c,
3799                                                 const struct dom_sid *domain_sid,
3800                                                 const char *domain_name,
3801                                                 struct cli_state *cli,
3802                                                 struct rpc_pipe_client *pipe_hnd,
3803                                                 TALLOC_CTX *mem_ctx,
3804                                                 int argc,
3805                                                 const char **argv)
3806 {
3807         WERROR result;
3808         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
3809         struct srvsvc_NetShareInfoCtr ctr_src;
3810         uint32 i;
3811         struct rpc_pipe_client *srvsvc_pipe = NULL;
3812         struct cli_state *cli_dst = NULL;
3813         uint32 level = 502; /* includes secdesc */
3814         uint32_t parm_error = 0;
3815         struct dcerpc_binding_handle *b;
3816
3817         result = get_share_info(c, pipe_hnd, mem_ctx, level, argc, argv,
3818                                 &ctr_src);
3819         if (!W_ERROR_IS_OK(result))
3820                 goto done;
3821
3822         /* connect destination PI_SRVSVC */
3823         nt_status = connect_dst_pipe(c, &cli_dst, &srvsvc_pipe,
3824                                      &ndr_table_srvsvc);
3825         if (!NT_STATUS_IS_OK(nt_status))
3826                 return nt_status;
3827
3828         b = srvsvc_pipe->binding_handle;
3829
3830         for (i = 0; i < ctr_src.ctr.ctr502->count; i++) {
3831
3832                 union srvsvc_NetShareInfo info;
3833                 struct srvsvc_NetShareInfo502 info502 =
3834                         ctr_src.ctr.ctr502->array[i];
3835
3836                 /* reset error-code */
3837                 nt_status = NT_STATUS_UNSUCCESSFUL;
3838
3839                 if (!check_share_sanity(c, cli, info502.name, info502.type))
3840                         continue;
3841
3842                 /* finally add the share on the dst server */
3843
3844                 printf(_("migrating: [%s], path: %s, comment: %s, without "
3845                          "share-ACLs\n"),
3846                         info502.name, info502.path, info502.comment);
3847
3848                 info.info502 = &info502;
3849
3850                 nt_status = dcerpc_srvsvc_NetShareAdd(b, mem_ctx,
3851                                                       srvsvc_pipe->desthost,
3852                                                       502,
3853                                                       &info,
3854                                                       &parm_error,
3855                                                       &result);
3856                 if (!NT_STATUS_IS_OK(nt_status)) {
3857                         printf(_("cannot add share: %s\n"),
3858                                 nt_errstr(nt_status));
3859                         goto done;
3860                 }
3861                 if (W_ERROR_V(result) == W_ERROR_V(WERR_FILE_EXISTS)) {
3862                         printf(_("           [%s] does already exist\n"),
3863                                 info502.name);
3864                         continue;
3865                 }
3866
3867                 if (!W_ERROR_IS_OK(result)) {
3868                         nt_status = werror_to_ntstatus(result);
3869                         printf(_("cannot add share: %s\n"),
3870                                 win_errstr(result));
3871                         goto done;
3872                 }
3873
3874         }
3875
3876         nt_status = NT_STATUS_OK;
3877
3878 done:
3879         if (cli_dst) {
3880                 cli_shutdown(cli_dst);
3881         }
3882
3883         return nt_status;
3884
3885 }
3886
3887 /**
3888  * Migrate shares from a RPC server to another.
3889  *
3890  * @param argc  Standard main() style argc.
3891  * @param argv  Standard main() style argv. Initial components are already
3892  *              stripped.
3893  *
3894  * @return A shell status integer (0 for success).
3895  **/
3896 static int rpc_share_migrate_shares(struct net_context *c, int argc,
3897                                     const char **argv)
3898 {
3899         if (c->display_usage) {
3900                 d_printf(  "%s\n"
3901                            "net rpc share migrate shares\n"
3902                            "    %s\n",
3903                          _("Usage:"),
3904                          _("Migrate shares to local server"));
3905                 return 0;
3906         }
3907
3908         if (!c->opt_host) {
3909                 printf(_("no server to migrate\n"));
3910                 return -1;
3911         }
3912
3913         return run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
3914                                rpc_share_migrate_shares_internals,
3915                                argc, argv);
3916 }
3917
3918 /**
3919  * Copy a file/dir
3920  *
3921  * @param f     file_info
3922  * @param mask  current search mask
3923  * @param state arg-pointer
3924  *
3925  **/
3926 static NTSTATUS copy_fn(const char *mnt, struct file_info *f,
3927                     const char *mask, void *state)
3928 {
3929         static NTSTATUS nt_status;
3930         static struct copy_clistate *local_state;
3931         static fstring filename, new_mask;
3932         fstring dir;
3933         char *old_dir;
3934         struct net_context *c;
3935
3936         local_state = (struct copy_clistate *)state;
3937         nt_status = NT_STATUS_UNSUCCESSFUL;
3938
3939         c = local_state->c;
3940
3941         if (strequal(f->name, ".") || strequal(f->name, ".."))
3942                 return NT_STATUS_OK;
3943
3944         DEBUG(3,("got mask: %s, name: %s\n", mask, f->name));
3945
3946         /* DIRECTORY */
3947         if (f->mode & FILE_ATTRIBUTE_DIRECTORY) {
3948
3949                 DEBUG(3,("got dir: %s\n", f->name));
3950
3951                 fstrcpy(dir, local_state->cwd);
3952                 fstrcat(dir, "\\");
3953                 fstrcat(dir, f->name);
3954
3955                 switch (net_mode_share)
3956                 {
3957                 case NET_MODE_SHARE_MIGRATE:
3958                         /* create that directory */
3959                         nt_status = net_copy_file(c, local_state->mem_ctx,
3960                                                   local_state->cli_share_src,
3961                                                   local_state->cli_share_dst,
3962                                                   dir, dir,
3963                                                   c->opt_acls? true : false,
3964                                                   c->opt_attrs? true : false,
3965                                                   c->opt_timestamps? true:false,
3966                                                   false);
3967                         break;
3968                 default:
3969                         d_fprintf(stderr, _("Unsupported mode %d\n"), net_mode_share);
3970                         return NT_STATUS_INTERNAL_ERROR;
3971                 }
3972
3973                 if (!NT_STATUS_IS_OK(nt_status)) {
3974                         printf(_("could not handle dir %s: %s\n"),
3975                                 dir, nt_errstr(nt_status));
3976                         return nt_status;
3977                 }
3978
3979                 /* search below that directory */
3980                 if (strlcpy(new_mask, dir, sizeof(new_mask)) >= sizeof(new_mask)) {
3981                         return NT_STATUS_NO_MEMORY;
3982                 }
3983                 if (strlcat(new_mask, "\\*", sizeof(new_mask)) >= sizeof(new_mask)) {
3984                         return NT_STATUS_NO_MEMORY;
3985                 }
3986
3987                 old_dir = local_state->cwd;
3988                 local_state->cwd = dir;
3989                 nt_status = sync_files(local_state, new_mask);
3990                 if (!NT_STATUS_IS_OK(nt_status)) {
3991                         printf(_("could not handle files\n"));
3992                 }
3993                 local_state->cwd = old_dir;
3994
3995                 return nt_status;
3996         }
3997
3998
3999         /* FILE */
4000         fstrcpy(filename, local_state->cwd);
4001         fstrcat(filename, "\\");
4002         fstrcat(filename, f->name);
4003
4004         DEBUG(3,("got file: %s\n", filename));
4005
4006         switch (net_mode_share)
4007         {
4008         case NET_MODE_SHARE_MIGRATE:
4009                 nt_status = net_copy_file(c, local_state->mem_ctx,
4010                                           local_state->cli_share_src,
4011                                           local_state->cli_share_dst,
4012                                           filename, filename,
4013                                           c->opt_acls? true : false,
4014                                           c->opt_attrs? true : false,
4015                                           c->opt_timestamps? true: false,
4016                                           true);
4017                 break;
4018         default:
4019                 d_fprintf(stderr, _("Unsupported file mode %d\n"),
4020                           net_mode_share);
4021                 return NT_STATUS_INTERNAL_ERROR;
4022         }
4023
4024         if (!NT_STATUS_IS_OK(nt_status))
4025                 printf(_("could not handle file %s: %s\n"),
4026                         filename, nt_errstr(nt_status));
4027         return nt_status;
4028 }
4029
4030 /**
4031  * sync files, can be called recursivly to list files
4032  * and then call copy_fn for each file
4033  *
4034  * @param cp_clistate   pointer to the copy_clistate we work with
4035  * @param mask          the current search mask
4036  *
4037  * @return              Boolean result
4038  **/
4039 static NTSTATUS sync_files(struct copy_clistate *cp_clistate, const char *mask)
4040 {
4041         struct cli_state *targetcli;
4042         char *targetpath = NULL;
4043         NTSTATUS status;
4044
4045         DEBUG(3,("calling cli_list with mask: %s\n", mask));
4046
4047         status = cli_resolve_path(talloc_tos(), "", NULL,
4048                                   cp_clistate->cli_share_src,
4049                                   mask, &targetcli, &targetpath);
4050         if (!NT_STATUS_IS_OK(status)) {
4051                 d_fprintf(stderr, _("cli_resolve_path %s failed with error: "
4052                                     "%s\n"),
4053                         mask, nt_errstr(status));
4054                 return status;
4055         }
4056
4057         status = cli_list(targetcli, targetpath, cp_clistate->attribute,
4058                           copy_fn, cp_clistate);
4059         if (!NT_STATUS_IS_OK(status)) {
4060                 d_fprintf(stderr, _("listing %s failed with error: %s\n"),
4061                           mask, nt_errstr(status));
4062         }
4063
4064         return status;
4065 }
4066
4067
4068 /**
4069  * Set the top level directory permissions before we do any further copies.
4070  * Should set up ACL inheritance.
4071  **/
4072
4073 bool copy_top_level_perms(struct net_context *c,
4074                                 struct copy_clistate *cp_clistate,
4075                                 const char *sharename)
4076 {
4077         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
4078
4079         switch (net_mode_share) {
4080         case NET_MODE_SHARE_MIGRATE:
4081                 DEBUG(3,("calling net_copy_fileattr for '.' directory in share %s\n", sharename));
4082                 nt_status = net_copy_fileattr(c,
4083                                                 cp_clistate->mem_ctx,
4084                                                 cp_clistate->cli_share_src,
4085                                                 cp_clistate->cli_share_dst,
4086                                                 "\\", "\\",
4087                                                 c->opt_acls? true : false,
4088                                                 c->opt_attrs? true : false,
4089                                                 c->opt_timestamps? true: false,
4090                                                 false);
4091                 break;
4092         default:
4093                 d_fprintf(stderr, _("Unsupported mode %d\n"), net_mode_share);
4094                 break;
4095         }
4096
4097         if (!NT_STATUS_IS_OK(nt_status))  {
4098                 printf(_("Could handle directory attributes for top level "
4099                          "directory of share %s. Error %s\n"),
4100                         sharename, nt_errstr(nt_status));
4101                 return false;
4102         }
4103
4104         return true;
4105 }
4106
4107 /**
4108  * Sync all files inside a remote share to another share (over smb).
4109  *
4110  * All parameters are provided by the run_rpc_command function, except for
4111  * argc, argv which are passed through.
4112  *
4113  * @param domain_sid The domain sid acquired from the remote server.
4114  * @param cli A cli_state connected to the server.
4115  * @param mem_ctx Talloc context, destroyed on completion of the function.
4116  * @param argc  Standard main() style argc.
4117  * @param argv  Standard main() style argv. Initial components are already
4118  *              stripped.
4119  *
4120  * @return Normal NTSTATUS return.
4121  **/
4122
4123 static NTSTATUS rpc_share_migrate_files_internals(struct net_context *c,
4124                                                 const struct dom_sid *domain_sid,
4125                                                 const char *domain_name,
4126                                                 struct cli_state *cli,
4127                                                 struct rpc_pipe_client *pipe_hnd,
4128                                                 TALLOC_CTX *mem_ctx,
4129                                                 int argc,
4130                                                 const char **argv)
4131 {
4132         WERROR result;
4133         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
4134         struct srvsvc_NetShareInfoCtr ctr_src;
4135         uint32 i;
4136         uint32 level = 502;
4137         struct copy_clistate cp_clistate;
4138         bool got_src_share = false;
4139         bool got_dst_share = false;
4140         const char *mask = "\\*";
4141         char *dst = NULL;
4142
4143         dst = SMB_STRDUP(c->opt_destination?c->opt_destination:"127.0.0.1");
4144         if (dst == NULL) {
4145                 nt_status = NT_STATUS_NO_MEMORY;
4146                 goto done;
4147         }
4148
4149         result = get_share_info(c, pipe_hnd, mem_ctx, level, argc, argv,
4150                                 &ctr_src);
4151
4152         if (!W_ERROR_IS_OK(result))
4153                 goto done;
4154
4155         for (i = 0; i < ctr_src.ctr.ctr502->count; i++) {
4156
4157                 struct srvsvc_NetShareInfo502 info502 =
4158                         ctr_src.ctr.ctr502->array[i];
4159
4160                 if (!check_share_sanity(c, cli, info502.name, info502.type))
4161                         continue;
4162
4163                 /* one might not want to mirror whole discs :) */
4164                 if (strequal(info502.name, "print$") || info502.name[1] == '$') {
4165                         d_printf(_("skipping   [%s]: builtin/hidden share\n"),
4166                                  info502.name);
4167                         continue;
4168                 }
4169
4170                 switch (net_mode_share)
4171                 {
4172                 case NET_MODE_SHARE_MIGRATE:
4173                         printf("syncing");
4174                         break;
4175                 default:
4176                         d_fprintf(stderr, _("Unsupported mode %d\n"),
4177                                   net_mode_share);
4178                         break;
4179                 }
4180                 printf(_("    [%s] files and directories %s ACLs, %s DOS "
4181                          "Attributes %s\n"),
4182                         info502.name,
4183                         c->opt_acls ? _("including") : _("without"),
4184                         c->opt_attrs ? _("including") : _("without"),
4185                         c->opt_timestamps ? _("(preserving timestamps)") : "");
4186
4187                 cp_clistate.mem_ctx = mem_ctx;
4188                 cp_clistate.cli_share_src = NULL;
4189                 cp_clistate.cli_share_dst = NULL;
4190                 cp_clistate.cwd = NULL;
4191                 cp_clistate.attribute = FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_DIRECTORY;
4192                 cp_clistate.c = c;
4193
4194                 /* open share source */
4195                 nt_status = connect_to_service(c, &cp_clistate.cli_share_src,
4196                                                smbXcli_conn_remote_sockaddr(cli->conn),
4197                                                smbXcli_conn_remote_name(cli->conn),
4198                                                info502.name, "A:");
4199                 if (!NT_STATUS_IS_OK(nt_status))
4200                         goto done;
4201
4202                 got_src_share = true;
4203
4204                 if (net_mode_share == NET_MODE_SHARE_MIGRATE) {
4205                         /* open share destination */
4206                         nt_status = connect_to_service(c, &cp_clistate.cli_share_dst,
4207                                                        NULL, dst, info502.name, "A:");
4208                         if (!NT_STATUS_IS_OK(nt_status))
4209                                 goto done;
4210
4211                         got_dst_share = true;
4212                 }
4213
4214                 if (!copy_top_level_perms(c, &cp_clistate, info502.name)) {
4215                         d_fprintf(stderr, _("Could not handle the top level "
4216                                             "directory permissions for the "
4217                                             "share: %s\n"), info502.name);
4218                         nt_status = NT_STATUS_UNSUCCESSFUL;
4219                         goto done;
4220                 }
4221
4222                 nt_status = sync_files(&cp_clistate, mask);
4223                 if (!NT_STATUS_IS_OK(nt_status)) {
4224                         d_fprintf(stderr, _("could not handle files for share: "
4225                                             "%s\n"), info502.name);
4226                         goto done;
4227                 }
4228         }
4229
4230         nt_status = NT_STATUS_OK;
4231
4232 done:
4233
4234         if (got_src_share)
4235                 cli_shutdown(cp_clistate.cli_share_src);
4236
4237         if (got_dst_share)
4238                 cli_shutdown(cp_clistate.cli_share_dst);
4239
4240         SAFE_FREE(dst);
4241         return nt_status;
4242
4243 }
4244
4245 static int rpc_share_migrate_files(struct net_context *c, int argc, const char **argv)
4246 {
4247         if (c->display_usage) {
4248                 d_printf(  "%s\n"
4249                            "net share migrate files\n"
4250                            "    %s\n",
4251                          _("Usage:"),
4252                          _("Migrate files to local server"));
4253                 return 0;
4254         }
4255
4256         if (!c->opt_host) {
4257                 d_printf(_("no server to migrate\n"));
4258                 return -1;
4259         }
4260
4261         return run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
4262                                rpc_share_migrate_files_internals,
4263                                argc, argv);
4264 }
4265
4266 /**
4267  * Migrate share-ACLs from a remote RPC server to the local RPC server.
4268  *
4269  * All parameters are provided by the run_rpc_command function, except for
4270  * argc, argv which are passed through.
4271  *
4272  * @param domain_sid The domain sid acquired from the remote server.
4273  * @param cli A cli_state connected to the server.
4274  * @param mem_ctx Talloc context, destroyed on completion of the function.
4275  * @param argc  Standard main() style argc.
4276  * @param argv  Standard main() style argv. Initial components are already
4277  *              stripped.
4278  *
4279  * @return Normal NTSTATUS return.
4280  **/
4281
4282 static NTSTATUS rpc_share_migrate_security_internals(struct net_context *c,
4283                                                 const struct dom_sid *domain_sid,
4284                                                 const char *domain_name,
4285                                                 struct cli_state *cli,
4286                                                 struct rpc_pipe_client *pipe_hnd,
4287                                                 TALLOC_CTX *mem_ctx,
4288                                                 int argc,
4289                                                 const char **argv)
4290 {
4291         WERROR result;
4292         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
4293         struct srvsvc_NetShareInfoCtr ctr_src;
4294         union srvsvc_NetShareInfo info;
4295         uint32 i;
4296         struct rpc_pipe_client *srvsvc_pipe = NULL;
4297         struct cli_state *cli_dst = NULL;
4298         uint32 level = 502; /* includes secdesc */
4299         uint32_t parm_error = 0;
4300         struct dcerpc_binding_handle *b;
4301
4302         result = get_share_info(c, pipe_hnd, mem_ctx, level, argc, argv,
4303                                 &ctr_src);
4304
4305         if (!W_ERROR_IS_OK(result))
4306                 goto done;
4307
4308         /* connect destination PI_SRVSVC */
4309         nt_status = connect_dst_pipe(c, &cli_dst, &srvsvc_pipe,
4310                                      &ndr_table_srvsvc);
4311         if (!NT_STATUS_IS_OK(nt_status))
4312                 return nt_status;
4313
4314         b = srvsvc_pipe->binding_handle;
4315
4316         for (i = 0; i < ctr_src.ctr.ctr502->count; i++) {
4317
4318                 struct srvsvc_NetShareInfo502 info502 =
4319                         ctr_src.ctr.ctr502->array[i];
4320
4321                 /* reset error-code */
4322                 nt_status = NT_STATUS_UNSUCCESSFUL;
4323
4324                 if (!check_share_sanity(c, cli, info502.name, info502.type))
4325                         continue;
4326
4327                 printf(_("migrating: [%s], path: %s, comment: %s, including "
4328                          "share-ACLs\n"),
4329                         info502.name, info502.path, info502.comment);
4330
4331                 if (c->opt_verbose)
4332                         display_sec_desc(info502.sd_buf.sd);
4333
4334                 /* FIXME: shouldn't we be able to just set the security descriptor ? */
4335                 info.info502 = &info502;
4336
4337                 /* finally modify the share on the dst server */
4338                 nt_status = dcerpc_srvsvc_NetShareSetInfo(b, mem_ctx,
4339                                                           srvsvc_pipe->desthost,
4340                                                           info502.name,
4341                                                           level,
4342                                                           &info,
4343                                                           &parm_error,
4344                                                           &result);
4345                 if (!NT_STATUS_IS_OK(nt_status)) {
4346                         printf(_("cannot set share-acl: %s\n"),
4347                                nt_errstr(nt_status));
4348                         goto done;
4349                 }
4350                 if (!W_ERROR_IS_OK(result)) {
4351                         nt_status = werror_to_ntstatus(result);
4352                         printf(_("cannot set share-acl: %s\n"),
4353                                win_errstr(result));
4354                         goto done;
4355                 }
4356
4357         }
4358
4359         nt_status = NT_STATUS_OK;
4360
4361 done:
4362         if (cli_dst) {
4363                 cli_shutdown(cli_dst);
4364         }
4365
4366         return nt_status;
4367
4368 }
4369
4370 /**
4371  * Migrate share-acls from a RPC server to another.
4372  *
4373  * @param argc  Standard main() style argc.
4374  * @param argv  Standard main() style argv. Initial components are already
4375  *              stripped.
4376  *
4377  * @return A shell status integer (0 for success).
4378  **/
4379 static int rpc_share_migrate_security(struct net_context *c, int argc,
4380                                       const char **argv)
4381 {
4382         if (c->display_usage) {
4383                 d_printf(  "%s\n"
4384                            "net rpc share migrate security\n"
4385                            "    %s\n",
4386                          _("Usage:"),
4387                          _("Migrate share-acls to local server"));
4388                 return 0;
4389         }
4390
4391         if (!c->opt_host) {
4392                 d_printf(_("no server to migrate\n"));
4393                 return -1;
4394         }
4395
4396         return run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
4397                                rpc_share_migrate_security_internals,
4398                                argc, argv);
4399 }
4400
4401 /**
4402  * Migrate shares (including share-definitions, share-acls and files with acls/attrs)
4403  * from one server to another.
4404  *
4405  * @param argc  Standard main() style argc.
4406  * @param argv  Standard main() style argv. Initial components are already
4407  *              stripped.
4408  *
4409  * @return A shell status integer (0 for success).
4410  *
4411  **/
4412 static int rpc_share_migrate_all(struct net_context *c, int argc,
4413                                  const char **argv)
4414 {
4415         int ret;
4416
4417         if (c->display_usage) {
4418                 d_printf(  "%s\n"
4419                            "net rpc share migrate all\n"
4420                            "    %s\n",
4421                          _("Usage:"),
4422                          _("Migrates shares including all share settings"));
4423                 return 0;
4424         }
4425
4426         if (!c->opt_host) {
4427                 d_printf(_("no server to migrate\n"));
4428                 return -1;
4429         }
4430
4431         /* order is important. we don't want to be locked out by the share-acl
4432          * before copying files - gd */
4433
4434         ret = run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
4435                               rpc_share_migrate_shares_internals, argc, argv);
4436         if (ret)
4437                 return ret;
4438
4439         ret = run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
4440                               rpc_share_migrate_files_internals, argc, argv);
4441         if (ret)
4442                 return ret;
4443
4444         return run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
4445                                rpc_share_migrate_security_internals, argc,
4446                                argv);
4447 }
4448
4449
4450 /**
4451  * 'net rpc share migrate' entrypoint.
4452  * @param argc  Standard main() style argc.
4453  * @param argv  Standard main() style argv. Initial components are already
4454  *              stripped.
4455  **/
4456 static int rpc_share_migrate(struct net_context *c, int argc, const char **argv)
4457 {
4458
4459         struct functable func[] = {
4460                 {
4461                         "all",
4462                         rpc_share_migrate_all,
4463                         NET_TRANSPORT_RPC,
4464                         N_("Migrate shares from remote to local server"),
4465                         N_("net rpc share migrate all\n"
4466                            "    Migrate shares from remote to local server")
4467                 },
4468                 {
4469                         "files",
4470                         rpc_share_migrate_files,
4471                         NET_TRANSPORT_RPC,
4472                         N_("Migrate files from remote to local server"),
4473                         N_("net rpc share migrate files\n"
4474                            "    Migrate files from remote to local server")
4475                 },
4476                 {
4477                         "security",
4478                         rpc_share_migrate_security,
4479                         NET_TRANSPORT_RPC,
4480                         N_("Migrate share-ACLs from remote to local server"),
4481                         N_("net rpc share migrate security\n"
4482                            "    Migrate share-ACLs from remote to local server")
4483                 },
4484                 {
4485                         "shares",
4486                         rpc_share_migrate_shares,
4487                         NET_TRANSPORT_RPC,
4488                         N_("Migrate shares from remote to local server"),
4489                         N_("net rpc share migrate shares\n"
4490                            "    Migrate shares from remote to local server")
4491                 },
4492                 {NULL, NULL, 0, NULL, NULL}
4493         };
4494
4495         net_mode_share = NET_MODE_SHARE_MIGRATE;
4496
4497         return net_run_function(c, argc, argv, "net rpc share migrate", func);
4498 }
4499
4500 struct full_alias {
4501         struct dom_sid sid;
4502         uint32 num_members;
4503         struct dom_sid *members;
4504 };
4505
4506 static int num_server_aliases;
4507 static struct full_alias *server_aliases;
4508
4509 /*
4510  * Add an alias to the static list.
4511  */
4512 static void push_alias(TALLOC_CTX *mem_ctx, struct full_alias *alias)
4513 {
4514         if (server_aliases == NULL)
4515                 server_aliases = SMB_MALLOC_ARRAY(struct full_alias, 100);
4516
4517         server_aliases[num_server_aliases] = *alias;
4518         num_server_aliases += 1;
4519 }
4520
4521 /*
4522  * For a specific domain on the server, fetch all the aliases
4523  * and their members. Add all of them to the server_aliases.
4524  */
4525
4526 static NTSTATUS rpc_fetch_domain_aliases(struct rpc_pipe_client *pipe_hnd,
4527                                         TALLOC_CTX *mem_ctx,
4528                                         struct policy_handle *connect_pol,
4529                                         const struct dom_sid *domain_sid)
4530 {
4531         uint32 start_idx, max_entries, num_entries, i;
4532         struct samr_SamArray *groups = NULL;
4533         NTSTATUS result, status;
4534         struct policy_handle domain_pol;
4535         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
4536
4537         /* Get domain policy handle */
4538
4539         status = dcerpc_samr_OpenDomain(b, mem_ctx,
4540                                         connect_pol,
4541                                         MAXIMUM_ALLOWED_ACCESS,
4542                                         discard_const_p(struct dom_sid2, domain_sid),
4543                                         &domain_pol,
4544                                         &result);
4545         if (!NT_STATUS_IS_OK(status)) {
4546                 return status;
4547         }
4548         if (!NT_STATUS_IS_OK(result)) {
4549                 return result;
4550         }
4551
4552         start_idx = 0;
4553         max_entries = 250;
4554
4555         do {
4556                 status = dcerpc_samr_EnumDomainAliases(b, mem_ctx,
4557                                                        &domain_pol,
4558                                                        &start_idx,
4559                                                        &groups,
4560                                                        max_entries,
4561                                                        &num_entries,
4562                                                        &result);
4563                 if (!NT_STATUS_IS_OK(status)) {
4564                         goto done;
4565                 }
4566                 for (i = 0; i < num_entries; i++) {
4567
4568                         struct policy_handle alias_pol;
4569                         struct full_alias alias;
4570                         struct lsa_SidArray sid_array;
4571                         int j;
4572                         NTSTATUS _result;
4573
4574                         status = dcerpc_samr_OpenAlias(b, mem_ctx,
4575                                                        &domain_pol,
4576                                                        MAXIMUM_ALLOWED_ACCESS,
4577                                                        groups->entries[i].idx,
4578                                                        &alias_pol,
4579                                                        &_result);
4580                         if (!NT_STATUS_IS_OK(status)) {
4581                                 goto done;
4582                         }
4583                         if (!NT_STATUS_IS_OK(_result)) {
4584                                 status = _result;
4585                                 goto done;
4586                         }
4587
4588                         status = dcerpc_samr_GetMembersInAlias(b, mem_ctx,
4589                                                                &alias_pol,
4590                                                                &sid_array,
4591                                                                &_result);
4592                         if (!NT_STATUS_IS_OK(status)) {
4593                                 goto done;
4594                         }
4595                         if (!NT_STATUS_IS_OK(_result)) {
4596                                 status = _result;
4597                                 goto done;
4598                         }
4599
4600                         alias.num_members = sid_array.num_sids;
4601
4602                         status = dcerpc_samr_Close(b, mem_ctx, &alias_pol, &_result);
4603                         if (!NT_STATUS_IS_OK(status)) {
4604                                 goto done;
4605                         }
4606                         if (!NT_STATUS_IS_OK(_result)) {
4607                                 status = _result;
4608                                 goto done;
4609                         }
4610
4611                         alias.members = NULL;
4612
4613                         if (alias.num_members > 0) {
4614                                 alias.members = SMB_MALLOC_ARRAY(struct dom_sid, alias.num_members);
4615
4616                                 for (j = 0; j < alias.num_members; j++)
4617                                         sid_copy(&alias.members[j],
4618                                                  sid_array.sids[j].sid);
4619                         }
4620
4621                         sid_compose(&alias.sid, domain_sid,
4622                                     groups->entries[i].idx);
4623
4624                         push_alias(mem_ctx, &alias);
4625                 }
4626         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
4627
4628         status = NT_STATUS_OK;
4629
4630  done:
4631         dcerpc_samr_Close(b, mem_ctx, &domain_pol, &result);
4632
4633         return status;
4634 }
4635
4636 /*
4637  * Dump server_aliases as names for debugging purposes.
4638  */
4639
4640 static NTSTATUS rpc_aliaslist_dump(struct net_context *c,
4641                                 const struct dom_sid *domain_sid,
4642                                 const char *domain_name,
4643                                 struct cli_state *cli,
4644                                 struct rpc_pipe_client *pipe_hnd,
4645                                 TALLOC_CTX *mem_ctx,
4646                                 int argc,
4647                                 const char **argv)
4648 {
4649         int i;
4650         NTSTATUS result;
4651         struct policy_handle lsa_pol;
4652         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
4653
4654         result = rpccli_lsa_open_policy(pipe_hnd, mem_ctx, true,
4655                                      SEC_FLAG_MAXIMUM_ALLOWED,
4656                                      &lsa_pol);
4657         if (!NT_STATUS_IS_OK(result))
4658                 return result;
4659
4660         for (i=0; i<num_server_aliases; i++) {
4661                 char **names;
4662                 char **domains;
4663                 enum lsa_SidType *types;
4664                 int j;
4665
4666                 struct full_alias *alias = &server_aliases[i];
4667
4668                 result = rpccli_lsa_lookup_sids(pipe_hnd, mem_ctx, &lsa_pol, 1,
4669                                              &alias->sid,
4670                                              &domains, &names, &types);
4671                 if (!NT_STATUS_IS_OK(result))
4672                         continue;
4673
4674                 DEBUG(1, ("%s\\%s %d: ", domains[0], names[0], types[0]));
4675
4676                 if (alias->num_members == 0) {
4677                         DEBUG(1, ("\n"));
4678                         continue;
4679                 }
4680
4681                 result = rpccli_lsa_lookup_sids(pipe_hnd, mem_ctx, &lsa_pol,
4682                                              alias->num_members,
4683                                              alias->members,
4684                                              &domains, &names, &types);
4685
4686                 if (!NT_STATUS_IS_OK(result) &&
4687                     !NT_STATUS_EQUAL(result, STATUS_SOME_UNMAPPED))
4688                         continue;
4689
4690                 for (j=0; j<alias->num_members; j++)
4691                         DEBUG(1, ("%s\\%s (%d); ",
4692                                   domains[j] ? domains[j] : "*unknown*",
4693                                   names[j] ? names[j] : "*unknown*",types[j]));
4694                 DEBUG(1, ("\n"));
4695         }
4696
4697         dcerpc_lsa_Close(b, mem_ctx, &lsa_pol, &result);
4698
4699         return NT_STATUS_OK;
4700 }
4701
4702 /*
4703  * Fetch a list of all server aliases and their members into
4704  * server_aliases.
4705  */
4706
4707 static NTSTATUS rpc_aliaslist_internals(struct net_context *c,
4708                                         const struct dom_sid *domain_sid,
4709                                         const char *domain_name,
4710                                         struct cli_state *cli,
4711                                         struct rpc_pipe_client *pipe_hnd,
4712                                         TALLOC_CTX *mem_ctx,
4713                                         int argc,
4714                                         const char **argv)
4715 {
4716         NTSTATUS result, status;
4717         struct policy_handle connect_pol;
4718         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
4719
4720         status = dcerpc_samr_Connect2(b, mem_ctx,
4721                                       pipe_hnd->desthost,
4722                                       MAXIMUM_ALLOWED_ACCESS,
4723                                       &connect_pol,
4724                                       &result);
4725         if (!NT_STATUS_IS_OK(status)) {
4726                 goto done;
4727         }
4728         if (!NT_STATUS_IS_OK(result)) {
4729                 status = result;
4730                 goto done;
4731         }
4732
4733         status = rpc_fetch_domain_aliases(pipe_hnd, mem_ctx, &connect_pol,
4734                                           &global_sid_Builtin);
4735         if (!NT_STATUS_IS_OK(status)) {
4736                 goto done;
4737         }
4738
4739         status = rpc_fetch_domain_aliases(pipe_hnd, mem_ctx, &connect_pol,
4740                                           domain_sid);
4741
4742         dcerpc_samr_Close(b, mem_ctx, &connect_pol, &result);
4743  done:
4744         return status;
4745 }
4746
4747 static void init_user_token(struct security_token *token, struct dom_sid *user_sid)
4748 {
4749         token->num_sids = 4;
4750
4751         if (!(token->sids = SMB_MALLOC_ARRAY(struct dom_sid, 4))) {
4752                 d_fprintf(stderr, "malloc %s\n",_("failed"));
4753                 token->num_sids = 0;
4754                 return;
4755         }
4756
4757         token->sids[0] = *user_sid;
4758         sid_copy(&token->sids[1], &global_sid_World);
4759         sid_copy(&token->sids[2], &global_sid_Network);
4760         sid_copy(&token->sids[3], &global_sid_Authenticated_Users);
4761 }
4762
4763 static void free_user_token(struct security_token *token)
4764 {
4765         SAFE_FREE(token->sids);
4766 }
4767
4768 static void add_sid_to_token(struct security_token *token, struct dom_sid *sid)
4769 {
4770         if (security_token_has_sid(token, sid))
4771                 return;
4772
4773         token->sids = SMB_REALLOC_ARRAY(token->sids, struct dom_sid, token->num_sids+1);
4774         if (!token->sids) {
4775                 return;
4776         }
4777
4778         sid_copy(&token->sids[token->num_sids], sid);
4779
4780         token->num_sids += 1;
4781 }
4782
4783 struct user_token {
4784         fstring name;
4785         struct security_token token;
4786 };
4787
4788 static void dump_user_token(struct user_token *token)
4789 {
4790         int i;
4791
4792         d_printf("%s\n", token->name);
4793
4794         for (i=0; i<token->token.num_sids; i++) {
4795                 d_printf(" %s\n", sid_string_tos(&token->token.sids[i]));
4796         }
4797 }
4798
4799 static bool is_alias_member(struct dom_sid *sid, struct full_alias *alias)
4800 {
4801         int i;
4802
4803         for (i=0; i<alias->num_members; i++) {
4804                 if (dom_sid_compare(sid, &alias->members[i]) == 0)
4805                         return true;
4806         }
4807
4808         return false;
4809 }
4810
4811 static void collect_sid_memberships(struct security_token *token, struct dom_sid sid)
4812 {
4813         int i;
4814
4815         for (i=0; i<num_server_aliases; i++) {
4816                 if (is_alias_member(&sid, &server_aliases[i]))
4817                         add_sid_to_token(token, &server_aliases[i].sid);
4818         }
4819 }
4820
4821 /*
4822  * We got a user token with all the SIDs we can know about without asking the
4823  * server directly. These are the user and domain group sids. All of these can
4824  * be members of aliases. So scan the list of aliases for each of the SIDs and
4825  * add them to the token.
4826  */
4827
4828 static void collect_alias_memberships(struct security_token *token)
4829 {
4830         int num_global_sids = token->num_sids;
4831         int i;
4832
4833         for (i=0; i<num_global_sids; i++) {
4834                 collect_sid_memberships(token, token->sids[i]);
4835         }
4836 }
4837
4838 static bool get_user_sids(const char *domain, const char *user, struct security_token *token)
4839 {
4840         wbcErr wbc_status = WBC_ERR_UNKNOWN_FAILURE;
4841         enum wbcSidType type;
4842         fstring full_name;
4843         struct wbcDomainSid wsid;
4844         char sid_str[WBC_SID_STRING_BUFLEN];
4845         struct dom_sid user_sid;
4846         uint32_t num_groups;
4847         gid_t *groups = NULL;
4848         uint32_t i;
4849
4850         fstr_sprintf(full_name, "%s%c%s",
4851                      domain, *lp_winbind_separator(), user);
4852
4853         /* First let's find out the user sid */
4854
4855         wbc_status = wbcLookupName(domain, user, &wsid, &type);
4856
4857         if (!WBC_ERROR_IS_OK(wbc_status)) {
4858                 DEBUG(1, ("winbind could not find %s: %s\n",
4859                           full_name, wbcErrorString(wbc_status)));
4860                 return false;
4861         }
4862
4863         wbcSidToStringBuf(&wsid, sid_str, sizeof(sid_str));
4864
4865         if (type != WBC_SID_NAME_USER) {
4866                 DEBUG(1, ("%s is not a user\n", full_name));
4867                 return false;
4868         }
4869
4870         if (!string_to_sid(&user_sid, sid_str)) {
4871                 DEBUG(1,("Could not convert sid %s from string\n", sid_str));
4872                 return false;
4873         }
4874
4875         init_user_token(token, &user_sid);
4876
4877         /* And now the groups winbind knows about */
4878
4879         wbc_status = wbcGetGroups(full_name, &num_groups, &groups);
4880         if (!WBC_ERROR_IS_OK(wbc_status)) {
4881                 DEBUG(1, ("winbind could not get groups of %s: %s\n",
4882                         full_name, wbcErrorString(wbc_status)));
4883                 return false;
4884         }
4885
4886         for (i = 0; i < num_groups; i++) {
4887                 gid_t gid = groups[i];
4888                 struct dom_sid sid;
4889                 bool ok;
4890
4891                 wbc_status = wbcGidToSid(gid, &wsid);
4892                 if (!WBC_ERROR_IS_OK(wbc_status)) {
4893                         DEBUG(1, ("winbind could not find SID of gid %u: %s\n",
4894                                   (unsigned int)gid, wbcErrorString(wbc_status)));
4895                         wbcFreeMemory(groups);
4896                         return false;
4897                 }
4898
4899                 wbcSidToStringBuf(&wsid, sid_str, sizeof(sid_str));
4900
4901                 DEBUG(3, (" %s\n", sid_str));
4902
4903                 ok = string_to_sid(&sid, sid_str);
4904                 if (!ok) {
4905                         DEBUG(1, ("Failed to convert string to SID\n"));
4906                         wbcFreeMemory(groups);
4907                         return false;
4908                 }
4909                 add_sid_to_token(token, &sid);
4910         }
4911         wbcFreeMemory(groups);
4912
4913         return true;
4914 }
4915
4916 /**
4917  * Get a list of all user tokens we want to look at
4918  **/
4919
4920 static bool get_user_tokens(struct net_context *c, int *num_tokens,
4921                             struct user_token **user_tokens)
4922 {
4923         wbcErr wbc_status = WBC_ERR_UNKNOWN_FAILURE;
4924         uint32_t i, num_users;
4925         const char **users;
4926         struct user_token *result;
4927         TALLOC_CTX *frame = NULL;
4928
4929         if (lp_winbind_use_default_domain() &&
4930             (c->opt_target_workgroup == NULL)) {
4931                 d_fprintf(stderr, _("winbind use default domain = yes set, "
4932                          "please specify a workgroup\n"));
4933                 return false;
4934         }
4935
4936         /* Send request to winbind daemon */
4937
4938         wbc_status = wbcListUsers(NULL, &num_users, &users);
4939         if (!WBC_ERROR_IS_OK(wbc_status)) {
4940                 DEBUG(1, (_("winbind could not list users: %s\n"),
4941                           wbcErrorString(wbc_status)));
4942                 return false;
4943         }
4944
4945         result = SMB_MALLOC_ARRAY(struct user_token, num_users);
4946
4947         if (result == NULL) {
4948                 DEBUG(1, ("Could not malloc sid array\n"));
4949                 wbcFreeMemory(users);
4950                 return false;
4951         }
4952
4953         frame = talloc_stackframe();
4954         for (i=0; i < num_users; i++) {
4955                 fstring domain, user;
4956                 char *p;
4957
4958                 fstrcpy(result[i].name, users[i]);
4959
4960                 p = strchr(users[i], *lp_winbind_separator());
4961
4962                 DEBUG(3, ("%s\n", users[i]));
4963
4964                 if (p == NULL) {
4965                         fstrcpy(domain, c->opt_target_workgroup);
4966                         fstrcpy(user, users[i]);
4967                 } else {
4968                         *p++ = '\0';
4969                         fstrcpy(domain, users[i]);
4970                         if (!strupper_m(domain)) {
4971                                 DEBUG(1, ("strupper_m %s failed\n", domain));
4972                                 wbcFreeMemory(users);
4973                                 return false;
4974                         }
4975                         fstrcpy(user, p);
4976                 }
4977
4978                 get_user_sids(domain, user, &(result[i].token));
4979         }
4980         TALLOC_FREE(frame);
4981         wbcFreeMemory(users);
4982
4983         *num_tokens = num_users;
4984         *user_tokens = result;
4985
4986         return true;
4987 }
4988
4989 static bool get_user_tokens_from_file(FILE *f,
4990                                       int *num_tokens,
4991                                       struct user_token **tokens)
4992 {
4993         struct user_token *token = NULL;
4994
4995         while (!feof(f)) {
4996                 fstring line;
4997
4998                 if (fgets(line, sizeof(line)-1, f) == NULL) {
4999                         return true;
5000                 }
5001
5002                 if ((strlen(line) > 0) && (line[strlen(line)-1] == '\n')) {
5003                         line[strlen(line)-1] = '\0';
5004                 }
5005
5006                 if (line[0] == ' ') {
5007                         /* We have a SID */
5008
5009                         struct dom_sid sid;
5010                         if(!string_to_sid(&sid, &line[1])) {
5011                                 DEBUG(1,("get_user_tokens_from_file: Could "
5012                                         "not convert sid %s \n",&line[1]));
5013                                 return false;
5014                         }
5015
5016                         if (token == NULL) {
5017                                 DEBUG(0, ("File does not begin with username"));
5018                                 return false;
5019                         }
5020
5021                         add_sid_to_token(&token->token, &sid);
5022                         continue;
5023                 }
5024
5025                 /* And a new user... */
5026
5027                 *num_tokens += 1;
5028                 *tokens = SMB_REALLOC_ARRAY(*tokens, struct user_token, *num_tokens);
5029                 if (*tokens == NULL) {
5030                         DEBUG(0, ("Could not realloc tokens\n"));
5031                         return false;
5032                 }
5033
5034                 token = &((*tokens)[*num_tokens-1]);
5035
5036                 if (strlcpy(token->name, line, sizeof(token->name)) >= sizeof(token->name)) {
5037                         return false;
5038                 }
5039                 token->token.num_sids = 0;
5040                 token->token.sids = NULL;
5041                 continue;
5042         }
5043
5044         return false;
5045 }
5046
5047
5048 /*
5049  * Show the list of all users that have access to a share
5050  */
5051
5052 static void show_userlist(struct rpc_pipe_client *pipe_hnd,
5053                           struct cli_state *cli,
5054                           TALLOC_CTX *mem_ctx,
5055                           const char *netname,
5056                           int num_tokens,
5057                           struct user_token *tokens)
5058 {
5059         uint16_t fnum;
5060         struct security_descriptor *share_sd = NULL;
5061         struct security_descriptor *root_sd = NULL;
5062         int i;
5063         union srvsvc_NetShareInfo info;
5064         WERROR result;
5065         NTSTATUS status;
5066         uint16 cnum;
5067         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
5068
5069         status = dcerpc_srvsvc_NetShareGetInfo(b, mem_ctx,
5070                                                pipe_hnd->desthost,
5071                                                netname,
5072                                                502,
5073                                                &info,
5074                                                &result);
5075
5076         if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(result)) {
5077                 DEBUG(1, ("Coult not query secdesc for share %s\n",
5078                           netname));
5079                 return;
5080         }
5081
5082         share_sd = info.info502->sd_buf.sd;
5083         if (share_sd == NULL) {
5084                 DEBUG(1, ("Got no secdesc for share %s\n",
5085                           netname));
5086         }
5087
5088         cnum = cli_state_get_tid(cli);
5089
5090         if (!NT_STATUS_IS_OK(cli_tree_connect(cli, netname, "A:", "", 0))) {
5091                 return;
5092         }
5093
5094         if (!NT_STATUS_IS_OK(cli_ntcreate(cli, "\\", 0, READ_CONTROL_ACCESS, 0,
5095                         FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN, 0x0, 0x0, &fnum))) {
5096                 cli_query_secdesc(cli, fnum, mem_ctx, &root_sd);
5097         }
5098
5099         for (i=0; i<num_tokens; i++) {
5100                 uint32 acc_granted;
5101
5102                 if (share_sd != NULL) {
5103                         status = se_access_check(share_sd, &tokens[i].token,
5104                                              1, &acc_granted);
5105
5106                         if (!NT_STATUS_IS_OK(status)) {
5107                                 DEBUG(1, ("Could not check share_sd for "
5108                                           "user %s\n",
5109                                           tokens[i].name));
5110                                 continue;
5111                         }
5112                 }
5113
5114                 if (root_sd == NULL) {
5115                         d_printf(" %s\n", tokens[i].name);
5116                         continue;
5117                 }
5118
5119                 status = se_access_check(root_sd, &tokens[i].token,
5120                                      1, &acc_granted);
5121                 if (!NT_STATUS_IS_OK(status)) {
5122                         DEBUG(1, ("Could not check root_sd for user %s\n",
5123                                   tokens[i].name));
5124                         continue;
5125                 }
5126                 d_printf(" %s\n", tokens[i].name);
5127         }
5128
5129         if (fnum != (uint16_t)-1)
5130                 cli_close(cli, fnum);
5131         cli_tdis(cli);
5132         cli_state_set_tid(cli, cnum);
5133
5134         return;
5135 }
5136
5137 /**
5138  * List shares on a remote RPC server, including the security descriptors.
5139  *
5140  * All parameters are provided by the run_rpc_command function, except for
5141  * argc, argv which are passed through.
5142  *
5143  * @param domain_sid The domain sid acquired from the remote server.
5144  * @param cli A cli_state connected to the server.
5145  * @param mem_ctx Talloc context, destroyed on completion of the function.
5146  * @param argc  Standard main() style argc.
5147  * @param argv  Standard main() style argv. Initial components are already
5148  *              stripped.
5149  *
5150  * @return Normal NTSTATUS return.
5151  **/
5152
5153 static NTSTATUS rpc_share_allowedusers_internals(struct net_context *c,
5154                                                 const struct dom_sid *domain_sid,
5155                                                 const char *domain_name,
5156                                                 struct cli_state *cli,
5157                                                 struct rpc_pipe_client *pipe_hnd,
5158                                                 TALLOC_CTX *mem_ctx,
5159                                                 int argc,
5160                                                 const char **argv)
5161 {
5162         bool r;
5163         FILE *f;
5164         NTSTATUS nt_status = NT_STATUS_OK;
5165         uint32_t total_entries = 0;
5166         uint32_t resume_handle = 0;
5167         uint32_t preferred_len = 0xffffffff;
5168         uint32_t i;
5169         struct dcerpc_binding_handle *b = NULL;
5170         struct srvsvc_NetShareInfoCtr info_ctr;
5171         struct srvsvc_NetShareCtr1 ctr1;
5172         WERROR result;
5173
5174         struct user_token *tokens = NULL;
5175         int num_tokens = 0;
5176
5177         if (argc == 0) {
5178                 f = stdin;
5179         } else {
5180                 f = fopen(argv[0], "r");
5181         }
5182
5183         if (f == NULL) {
5184                 DEBUG(0, ("Could not open userlist: %s\n", strerror(errno)));
5185                 return NT_STATUS_UNSUCCESSFUL;
5186         }
5187
5188         r = get_user_tokens_from_file(f, &num_tokens, &tokens);
5189
5190         if (f != stdin)
5191                 fclose(f);
5192
5193         if (!r) {
5194                 DEBUG(0, ("Could not read users from file\n"));
5195                 return NT_STATUS_UNSUCCESSFUL;
5196         }
5197
5198         for (i=0; i<num_tokens; i++)
5199                 collect_alias_memberships(&tokens[i].token);
5200
5201         ZERO_STRUCT(info_ctr);
5202         ZERO_STRUCT(ctr1);
5203
5204         info_ctr.level = 1;
5205         info_ctr.ctr.ctr1 = &ctr1;
5206
5207         b = pipe_hnd->binding_handle;
5208
5209         /* Issue the NetShareEnum RPC call and retrieve the response */
5210         nt_status = dcerpc_srvsvc_NetShareEnumAll(b,
5211                                         talloc_tos(),
5212                                         pipe_hnd->desthost,
5213                                         &info_ctr,
5214                                         preferred_len,
5215                                         &total_entries,
5216                                         &resume_handle,
5217                                         &result);
5218
5219         /* Was it successful? */
5220         if (!NT_STATUS_IS_OK(nt_status)) {
5221                 /*  Nope.  Go clean up. */
5222                 goto done;
5223         }
5224
5225         if (!W_ERROR_IS_OK(result)) {
5226                 /*  Nope.  Go clean up. */
5227                 nt_status = werror_to_ntstatus(result);
5228                 goto done;
5229         }
5230
5231         if (total_entries == 0) {
5232                 goto done;
5233         }
5234
5235         /* For each returned entry... */
5236         for (i = 0; i < info_ctr.ctr.ctr1->count; i++) {
5237                 const char *netname = info_ctr.ctr.ctr1->array[i].name;
5238
5239                 if (info_ctr.ctr.ctr1->array[i].type != STYPE_DISKTREE) {
5240                         continue;
5241                 }
5242
5243                 d_printf("%s\n", netname);
5244
5245                 show_userlist(pipe_hnd, cli, mem_ctx, netname,
5246                               num_tokens, tokens);
5247         }
5248  done:
5249         for (i=0; i<num_tokens; i++) {
5250                 free_user_token(&tokens[i].token);
5251         }
5252         SAFE_FREE(tokens);
5253
5254         return nt_status;
5255 }
5256
5257 static int rpc_share_allowedusers(struct net_context *c, int argc,
5258                                   const char **argv)
5259 {
5260         int result;
5261
5262         if (c->display_usage) {
5263                 d_printf(  "%s\n"
5264                            "net rpc share allowedusers\n"
5265                             "    %s\n",
5266                           _("Usage:"),
5267                           _("List allowed users"));
5268                 return 0;
5269         }
5270
5271         result = run_rpc_command(c, NULL, &ndr_table_samr, 0,
5272                                  rpc_aliaslist_internals,
5273                                  argc, argv);
5274         if (result != 0)
5275                 return result;
5276
5277         result = run_rpc_command(c, NULL, &ndr_table_lsarpc, 0,
5278                                  rpc_aliaslist_dump,
5279                                  argc, argv);
5280         if (result != 0)
5281                 return result;
5282
5283         return run_rpc_command(c, NULL, &ndr_table_srvsvc, 0,
5284                                rpc_share_allowedusers_internals,
5285                                argc, argv);
5286 }
5287
5288 int net_usersidlist(struct net_context *c, int argc, const char **argv)
5289 {
5290         int num_tokens = 0;
5291         struct user_token *tokens = NULL;
5292         int i;
5293
5294         if (argc != 0) {
5295                 net_usersidlist_usage(c, argc, argv);
5296                 return 0;
5297         }
5298
5299         if (!get_user_tokens(c, &num_tokens, &tokens)) {
5300                 DEBUG(0, ("Could not get the user/sid list\n"));
5301                 return -1;
5302         }
5303
5304         for (i=0; i<num_tokens; i++) {
5305                 dump_user_token(&tokens[i]);
5306                 free_user_token(&tokens[i].token);
5307         }
5308
5309         SAFE_FREE(tokens);
5310         return 0;
5311 }
5312
5313 int net_usersidlist_usage(struct net_context *c, int argc, const char **argv)
5314 {
5315         d_printf(_("net usersidlist\n"
5316                    "\tprints out a list of all users the running winbind knows\n"
5317                    "\tabout, together with all their SIDs. This is used as\n"
5318                    "\tinput to the 'net rpc share allowedusers' command.\n\n"));
5319
5320         net_common_flags_usage(c, argc, argv);
5321         return -1;
5322 }
5323
5324 /**
5325  * 'net rpc share' entrypoint.
5326  * @param argc  Standard main() style argc.
5327  * @param argv  Standard main() style argv. Initial components are already
5328  *              stripped.
5329  **/
5330
5331 int net_rpc_share(struct net_context *c, int argc, const char **argv)
5332 {
5333         NET_API_STATUS status;
5334
5335         struct functable func[] = {
5336                 {
5337                         "add",
5338                         rpc_share_add,
5339                         NET_TRANSPORT_RPC,
5340                         N_("Add share"),
5341                         N_("net rpc share add\n"
5342                            "    Add share")
5343                 },
5344                 {
5345                         "delete",
5346                         rpc_share_delete,
5347                         NET_TRANSPORT_RPC,
5348                         N_("Remove share"),
5349                         N_("net rpc share delete\n"
5350                            "    Remove share")
5351                 },
5352                 {
5353                         "allowedusers",
5354                         rpc_share_allowedusers,
5355                         NET_TRANSPORT_RPC,
5356                         N_("Modify allowed users"),
5357                         N_("net rpc share allowedusers\n"
5358                            "    Modify allowed users")
5359                 },
5360                 {
5361                         "migrate",
5362                         rpc_share_migrate,
5363                         NET_TRANSPORT_RPC,
5364                         N_("Migrate share to local server"),
5365                         N_("net rpc share migrate\n"
5366                            "    Migrate share to local server")
5367                 },
5368                 {
5369                         "list",
5370                         rpc_share_list,
5371                         NET_TRANSPORT_RPC,
5372                         N_("List shares"),
5373                         N_("net rpc share list\n"
5374                            "    List shares")
5375                 },
5376                 {NULL, NULL, 0, NULL, NULL}
5377         };
5378
5379         status = libnetapi_net_init(&c->netapi_ctx);
5380         if (status != 0) {
5381                 return -1;
5382         }
5383         libnetapi_set_username(c->netapi_ctx, c->opt_user_name);
5384         libnetapi_set_password(c->netapi_ctx, c->opt_password);
5385         if (c->opt_kerberos) {
5386                 libnetapi_set_use_kerberos(c->netapi_ctx);
5387         }
5388
5389         if (argc == 0) {
5390                 if (c->display_usage) {
5391                         d_printf("%s\n%s",
5392                                  _("Usage:"),
5393                                  _("net rpc share\n"
5394                                    "    List shares\n"
5395                                    "    Alias for net rpc share list\n"));
5396                         net_display_usage_from_functable(func);
5397                         return 0;
5398                 }
5399
5400                 return rpc_share_list(c, argc, argv);
5401         }
5402
5403         return net_run_function(c, argc, argv, "net rpc share", func);
5404 }
5405
5406 static NTSTATUS rpc_sh_share_list(struct net_context *c,
5407                                   TALLOC_CTX *mem_ctx,
5408                                   struct rpc_sh_ctx *ctx,
5409                                   struct rpc_pipe_client *pipe_hnd,
5410                                   int argc, const char **argv)
5411 {
5412
5413         return werror_to_ntstatus(W_ERROR(rpc_share_list(c, argc, argv)));
5414 }
5415
5416 static NTSTATUS rpc_sh_share_add(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         NET_API_STATUS status;
5423         uint32_t parm_err = 0;
5424         struct SHARE_INFO_2 i2;
5425
5426         if ((argc < 2) || (argc > 3)) {
5427                 d_fprintf(stderr, _("Usage: %s <share> <path> [comment]\n"),
5428                           ctx->whoami);
5429                 return NT_STATUS_INVALID_PARAMETER;
5430         }
5431
5432         i2.shi2_netname         = argv[0];
5433         i2.shi2_type            = STYPE_DISKTREE;
5434         i2.shi2_remark          = (argc == 3) ? argv[2] : "";
5435         i2.shi2_permissions     = 0;
5436         i2.shi2_max_uses        = 0;
5437         i2.shi2_current_uses    = 0;
5438         i2.shi2_path            = argv[1];
5439         i2.shi2_passwd          = NULL;
5440
5441         status = NetShareAdd(pipe_hnd->desthost,
5442                              2,
5443                              (uint8_t *)&i2,
5444                              &parm_err);
5445
5446         return werror_to_ntstatus(W_ERROR(status));
5447 }
5448
5449 static NTSTATUS rpc_sh_share_delete(struct net_context *c,
5450                                     TALLOC_CTX *mem_ctx,
5451                                     struct rpc_sh_ctx *ctx,
5452                                     struct rpc_pipe_client *pipe_hnd,
5453                                     int argc, const char **argv)
5454 {
5455         if (argc != 1) {
5456                 d_fprintf(stderr, "%s %s <share>\n", _("Usage:"), ctx->whoami);
5457                 return NT_STATUS_INVALID_PARAMETER;
5458         }
5459
5460         return werror_to_ntstatus(W_ERROR(NetShareDel(pipe_hnd->desthost, argv[0], 0)));
5461 }
5462
5463 static NTSTATUS rpc_sh_share_info(struct net_context *c,
5464                                   TALLOC_CTX *mem_ctx,
5465                                   struct rpc_sh_ctx *ctx,
5466                                   struct rpc_pipe_client *pipe_hnd,
5467                                   int argc, const char **argv)
5468 {
5469         union srvsvc_NetShareInfo info;
5470         WERROR result;
5471         NTSTATUS status;
5472         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
5473
5474         if (argc != 1) {
5475                 d_fprintf(stderr, "%s %s <share>\n", _("Usage:"), ctx->whoami);
5476                 return NT_STATUS_INVALID_PARAMETER;
5477         }
5478
5479         status = dcerpc_srvsvc_NetShareGetInfo(b, mem_ctx,
5480                                                pipe_hnd->desthost,
5481                                                argv[0],
5482                                                2,
5483                                                &info,
5484                                                &result);
5485         if (!NT_STATUS_IS_OK(status)) {
5486                 result = ntstatus_to_werror(status);
5487                 goto done;
5488         }
5489         if (!W_ERROR_IS_OK(result)) {
5490                 goto done;
5491         }
5492
5493         d_printf(_("Name:     %s\n"), info.info2->name);
5494         d_printf(_("Comment:  %s\n"), info.info2->comment);
5495         d_printf(_("Path:     %s\n"), info.info2->path);
5496         d_printf(_("Password: %s\n"), info.info2->password);
5497
5498  done:
5499         return werror_to_ntstatus(result);
5500 }
5501
5502 struct rpc_sh_cmd *net_rpc_share_cmds(struct net_context *c, TALLOC_CTX *mem_ctx,
5503                                       struct rpc_sh_ctx *ctx)
5504 {
5505         static struct rpc_sh_cmd cmds[] = {
5506
5507         { "list", NULL, &ndr_table_srvsvc, rpc_sh_share_list,
5508           N_("List available shares") },
5509
5510         { "add", NULL, &ndr_table_srvsvc, rpc_sh_share_add,
5511           N_("Add a share") },
5512
5513         { "delete", NULL, &ndr_table_srvsvc, rpc_sh_share_delete,
5514           N_("Delete a share") },
5515
5516         { "info", NULL, &ndr_table_srvsvc, rpc_sh_share_info,
5517           N_("Get information about a share") },
5518
5519         { NULL, NULL, 0, NULL, NULL }
5520         };
5521
5522         return cmds;
5523 }
5524
5525 /****************************************************************************/
5526
5527 static int rpc_file_usage(struct net_context *c, int argc, const char **argv)
5528 {
5529         return net_file_usage(c, argc, argv);
5530 }
5531
5532 /**
5533  * Close a file on a remote RPC server.
5534  *
5535  * @param argc  Standard main() style argc.
5536  * @param argv  Standard main() style argv. Initial components are already
5537  *              stripped.
5538  *
5539  * @return A shell status integer (0 for success).
5540  **/
5541 static int rpc_file_close(struct net_context *c, int argc, const char **argv)
5542 {
5543         if (argc < 1 || c->display_usage) {
5544                 return rpc_file_usage(c, argc, argv);
5545         }
5546
5547         return NetFileClose(c->opt_host, atoi(argv[0]));
5548 }
5549
5550 /**
5551  * Formatted print of open file info
5552  *
5553  * @param r  struct FILE_INFO_3 contents
5554  **/
5555
5556 static void display_file_info_3(struct FILE_INFO_3 *r)
5557 {
5558         d_printf("%-7.1d %-20.20s 0x%-4.2x %-6.1d %s\n",
5559                  r->fi3_id, r->fi3_username, r->fi3_permissions,
5560                  r->fi3_num_locks, r->fi3_pathname);
5561 }
5562
5563 /**
5564  * List files for a user on a remote RPC server.
5565  *
5566  * @param argc  Standard main() style argc.
5567  * @param argv  Standard main() style argv. Initial components are already
5568  *              stripped.
5569  *
5570  * @return A shell status integer (0 for success)..
5571  **/
5572
5573 static int rpc_file_user(struct net_context *c, int argc, const char **argv)
5574 {
5575         NET_API_STATUS status;
5576         uint32 preferred_len = 0xffffffff, i;
5577         char *username=NULL;
5578         uint32_t total_entries = 0;
5579         uint32_t entries_read = 0;
5580         uint32_t resume_handle = 0;
5581         struct FILE_INFO_3 *i3 = NULL;
5582
5583         if (c->display_usage) {
5584                 return rpc_file_usage(c, argc, argv);
5585         }
5586
5587         /* if argc > 0, must be user command */
5588         if (argc > 0) {
5589                 username = smb_xstrdup(argv[0]);
5590         }
5591
5592         status = NetFileEnum(c->opt_host,
5593                              NULL,
5594                              username,
5595                              3,
5596                              (uint8_t **)(void *)&i3,
5597                              preferred_len,
5598                              &entries_read,
5599                              &total_entries,
5600                              &resume_handle);
5601
5602         if (status != 0) {
5603                 goto done;
5604         }
5605
5606         /* Display results */
5607
5608         d_printf(_(
5609                  "\nEnumerating open files on remote server:\n\n"
5610                  "\nFileId  Opened by            Perms  Locks  Path"
5611                  "\n------  ---------            -----  -----  ---- \n"));
5612         for (i = 0; i < entries_read; i++) {
5613                 display_file_info_3(&i3[i]);
5614         }
5615  done:
5616         SAFE_FREE(username);
5617         return status;
5618 }
5619
5620 /**
5621  * 'net rpc file' entrypoint.
5622  * @param argc  Standard main() style argc.
5623  * @param argv  Standard main() style argv. Initial components are already
5624  *              stripped.
5625  **/
5626
5627 int net_rpc_file(struct net_context *c, int argc, const char **argv)
5628 {
5629         NET_API_STATUS status;
5630
5631         struct functable func[] = {
5632                 {
5633                         "close",
5634                         rpc_file_close,
5635                         NET_TRANSPORT_RPC,
5636                         N_("Close opened file"),
5637                         N_("net rpc file close\n"
5638                            "    Close opened file")
5639                 },
5640                 {
5641                         "user",
5642                         rpc_file_user,
5643                         NET_TRANSPORT_RPC,
5644                         N_("List files opened by user"),
5645                         N_("net rpc file user\n"
5646                            "    List files opened by user")
5647                 },
5648 #if 0
5649                 {
5650                         "info",
5651                         rpc_file_info,
5652                         NET_TRANSPORT_RPC,
5653                         N_("Display information about opened file"),
5654                         N_("net rpc file info\n"
5655                            "    Display information about opened file")
5656                 },
5657 #endif
5658                 {NULL, NULL, 0, NULL, NULL}
5659         };
5660
5661         status = libnetapi_net_init(&c->netapi_ctx);
5662         if (status != 0) {
5663                 return -1;
5664         }
5665         libnetapi_set_username(c->netapi_ctx, c->opt_user_name);
5666         libnetapi_set_password(c->netapi_ctx, c->opt_password);
5667         if (c->opt_kerberos) {
5668                 libnetapi_set_use_kerberos(c->netapi_ctx);
5669         }
5670
5671         if (argc == 0) {
5672                 if (c->display_usage) {
5673                         d_printf(_("Usage:\n"));
5674                         d_printf(_("net rpc file\n"
5675                                    "    List opened files\n"));
5676                         net_display_usage_from_functable(func);
5677                         return 0;
5678                 }
5679
5680                 return rpc_file_user(c, argc, argv);
5681         }
5682
5683         return net_run_function(c, argc, argv, "net rpc file", func);
5684 }
5685
5686 /**
5687  * ABORT the shutdown of a remote RPC Server, over initshutdown pipe.
5688  *
5689  * All parameters are provided by the run_rpc_command function, except for
5690  * argc, argv which are passed through.
5691  *
5692  * @param c     A net_context structure.
5693  * @param domain_sid The domain sid acquired from the remote server.
5694  * @param cli A cli_state connected to the server.
5695  * @param mem_ctx Talloc context, destroyed on completion of the function.
5696  * @param argc  Standard main() style argc.
5697  * @param argv  Standard main() style argv. Initial components are already
5698  *              stripped.
5699  *
5700  * @return Normal NTSTATUS return.
5701  **/
5702
5703 static NTSTATUS rpc_shutdown_abort_internals(struct net_context *c,
5704                                         const struct dom_sid *domain_sid,
5705                                         const char *domain_name,
5706                                         struct cli_state *cli,
5707                                         struct rpc_pipe_client *pipe_hnd,
5708                                         TALLOC_CTX *mem_ctx,
5709                                         int argc,
5710                                         const char **argv)
5711 {
5712         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
5713         WERROR result;
5714         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
5715
5716         status = dcerpc_initshutdown_Abort(b, mem_ctx, NULL, &result);
5717         if (!NT_STATUS_IS_OK(status)) {
5718                 return status;
5719         }
5720         if (W_ERROR_IS_OK(result)) {
5721                 d_printf(_("\nShutdown successfully aborted\n"));
5722                 DEBUG(5,("cmd_shutdown_abort: query succeeded\n"));
5723         } else
5724                 DEBUG(5,("cmd_shutdown_abort: query failed\n"));
5725
5726         return werror_to_ntstatus(result);
5727 }
5728
5729 /**
5730  * ABORT the shutdown of a remote RPC Server, over winreg pipe.
5731  *
5732  * All parameters are provided by the run_rpc_command function, except for
5733  * argc, argv which are passed through.
5734  *
5735  * @param c     A net_context structure.
5736  * @param domain_sid The domain sid acquired from the remote server.
5737  * @param cli A cli_state connected to the server.
5738  * @param mem_ctx Talloc context, destroyed on completion of the function.
5739  * @param argc  Standard main() style argc.
5740  * @param argv  Standard main() style argv. Initial components are already
5741  *              stripped.
5742  *
5743  * @return Normal NTSTATUS return.
5744  **/
5745
5746 static NTSTATUS rpc_reg_shutdown_abort_internals(struct net_context *c,
5747                                                 const struct dom_sid *domain_sid,
5748                                                 const char *domain_name,
5749                                                 struct cli_state *cli,
5750                                                 struct rpc_pipe_client *pipe_hnd,
5751                                                 TALLOC_CTX *mem_ctx,
5752                                                 int argc,
5753                                                 const char **argv)
5754 {
5755         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
5756         WERROR werr;
5757         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
5758
5759         result = dcerpc_winreg_AbortSystemShutdown(b, mem_ctx, NULL, &werr);
5760
5761         if (!NT_STATUS_IS_OK(result)) {
5762                 DEBUG(5,("cmd_reg_abort_shutdown: query failed\n"));
5763                 return result;
5764         }
5765         if (W_ERROR_IS_OK(werr)) {
5766                 d_printf(_("\nShutdown successfully aborted\n"));
5767                 DEBUG(5,("cmd_reg_abort_shutdown: query succeeded\n"));
5768         } else
5769                 DEBUG(5,("cmd_reg_abort_shutdown: query failed\n"));
5770
5771         return werror_to_ntstatus(werr);
5772 }
5773
5774 /**
5775  * ABORT the shutdown of a remote RPC server.
5776  *
5777  * @param argc  Standard main() style argc.
5778  * @param argv  Standard main() style argv. Initial components are already
5779  *              stripped.
5780  *
5781  * @return A shell status integer (0 for success).
5782  **/
5783
5784 static int rpc_shutdown_abort(struct net_context *c, int argc,
5785                               const char **argv)
5786 {
5787         int rc = -1;
5788
5789         if (c->display_usage) {
5790                 d_printf(  "%s\n"
5791                            "net rpc abortshutdown\n"
5792                            "    %s\n",
5793                          _("Usage:"),
5794                          _("Abort a scheduled shutdown"));
5795                 return 0;
5796         }
5797
5798         rc = run_rpc_command(c, NULL, &ndr_table_initshutdown, 0,
5799                              rpc_shutdown_abort_internals, argc, argv);
5800
5801         if (rc == 0)
5802                 return rc;
5803
5804         DEBUG(1, ("initshutdown pipe didn't work, trying winreg pipe\n"));
5805
5806         return run_rpc_command(c, NULL, &ndr_table_winreg, 0,
5807                                rpc_reg_shutdown_abort_internals,
5808                                argc, argv);
5809 }
5810
5811 /**
5812  * Shut down a remote RPC Server via initshutdown pipe.
5813  *
5814  * All parameters are provided by the run_rpc_command function, except for
5815  * argc, argv which are passed through.
5816  *
5817  * @param c     A net_context structure.
5818  * @param domain_sid The domain sid acquired from the remote server.
5819  * @param cli A cli_state connected to the server.
5820  * @param mem_ctx Talloc context, destroyed on completion of the function.
5821  * @param argc  Standard main() style argc.
5822  * @param argv  Standard main() style argv. Initial components are already
5823  *              stripped.
5824  *
5825  * @return Normal NTSTATUS return.
5826  **/
5827
5828 NTSTATUS rpc_init_shutdown_internals(struct net_context *c,
5829                                      const struct dom_sid *domain_sid,
5830                                      const char *domain_name,
5831                                      struct cli_state *cli,
5832                                      struct rpc_pipe_client *pipe_hnd,
5833                                      TALLOC_CTX *mem_ctx,
5834                                      int argc,
5835                                      const char **argv)
5836 {
5837         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
5838         WERROR result;
5839         const char *msg = N_("This machine will be shutdown shortly");
5840         uint32 timeout = 20;
5841         struct lsa_StringLarge msg_string;
5842         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
5843
5844         if (c->opt_comment) {
5845                 msg = c->opt_comment;
5846         }
5847         if (c->opt_timeout) {
5848                 timeout = c->opt_timeout;
5849         }
5850
5851         msg_string.string = msg;
5852
5853         /* create an entry */
5854         status = dcerpc_initshutdown_Init(b, mem_ctx, NULL,
5855                         &msg_string, timeout, c->opt_force, c->opt_reboot,
5856                         &result);
5857         if (!NT_STATUS_IS_OK(status)) {
5858                 return status;
5859         }
5860         if (W_ERROR_IS_OK(result)) {
5861                 d_printf(_("\nShutdown of remote machine succeeded\n"));
5862                 DEBUG(5,("Shutdown of remote machine succeeded\n"));
5863         } else {
5864                 DEBUG(1,("Shutdown of remote machine failed!\n"));
5865         }
5866         return werror_to_ntstatus(result);
5867 }
5868
5869 /**
5870  * Shut down a remote RPC Server via winreg pipe.
5871  *
5872  * All parameters are provided by the run_rpc_command function, except for
5873  * argc, argv which are passed through.
5874  *
5875  * @param c     A net_context structure.
5876  * @param domain_sid The domain sid acquired from the remote server.
5877  * @param cli A cli_state connected to the server.
5878  * @param mem_ctx Talloc context, destroyed on completion of the function.
5879  * @param argc  Standard main() style argc.
5880  * @param argv  Standard main() style argv. Initial components are already
5881  *              stripped.
5882  *
5883  * @return Normal NTSTATUS return.
5884  **/
5885
5886 NTSTATUS rpc_reg_shutdown_internals(struct net_context *c,
5887                                     const struct dom_sid *domain_sid,
5888                                     const char *domain_name,
5889                                     struct cli_state *cli,
5890                                     struct rpc_pipe_client *pipe_hnd,
5891                                     TALLOC_CTX *mem_ctx,
5892                                     int argc,
5893                                     const char **argv)
5894 {
5895         const char *msg = N_("This machine will be shutdown shortly");
5896         uint32 timeout = 20;
5897         struct lsa_StringLarge msg_string;
5898         NTSTATUS result;
5899         WERROR werr;
5900         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
5901
5902         if (c->opt_comment) {
5903                 msg = c->opt_comment;
5904         }
5905         msg_string.string = msg;
5906
5907         if (c->opt_timeout) {
5908                 timeout = c->opt_timeout;
5909         }
5910
5911         /* create an entry */
5912         result = dcerpc_winreg_InitiateSystemShutdown(b, mem_ctx, NULL,
5913                         &msg_string, timeout, c->opt_force, c->opt_reboot,
5914                         &werr);
5915         if (!NT_STATUS_IS_OK(result)) {
5916                 d_fprintf(stderr, "\nShutdown of remote machine failed\n");
5917                 return result;
5918         }
5919
5920         if (W_ERROR_IS_OK(werr)) {
5921                 d_printf(_("\nShutdown of remote machine succeeded\n"));
5922         } else {
5923                 d_fprintf(stderr, "\nShutdown of remote machine failed\n");
5924                 if ( W_ERROR_EQUAL(werr, WERR_MACHINE_LOCKED) )
5925                         d_fprintf(stderr, "\nMachine locked, use -f switch to force\n");
5926                 else
5927                         d_fprintf(stderr, "\nresult was: %s\n", win_errstr(werr));
5928         }
5929
5930         return werror_to_ntstatus(werr);
5931 }
5932
5933 /**
5934  * Shut down a remote RPC server.
5935  *
5936  * @param argc  Standard main() style argc.
5937  * @param argv  Standard main() style argv. Initial components are already
5938  *              stripped.
5939  *
5940  * @return A shell status integer (0 for success).
5941  **/
5942
5943 static int rpc_shutdown(struct net_context *c, int argc, const char **argv)
5944 {
5945         int rc =  -1;
5946
5947         if (c->display_usage) {
5948                 d_printf(  "%s\n"
5949                            "net rpc shutdown\n"
5950                            "    %s\n",
5951                          _("Usage:"),
5952                          _("Shut down a remote RPC server"));
5953                 return 0;
5954         }
5955
5956         rc = run_rpc_command(c, NULL, &ndr_table_initshutdown, 0,
5957                              rpc_init_shutdown_internals, argc, argv);
5958
5959         if (rc) {
5960                 DEBUG(1, ("initshutdown pipe failed, trying winreg pipe\n"));
5961                 rc = run_rpc_command(c, NULL, &ndr_table_winreg, 0,
5962                                      rpc_reg_shutdown_internals, argc, argv);
5963         }
5964
5965         return rc;
5966 }
5967
5968 /***************************************************************************
5969   NT Domain trusts code (i.e. 'net rpc trustdom' functionality)
5970  ***************************************************************************/
5971
5972 /**
5973  * Add interdomain trust account to the RPC server.
5974  * All parameters (except for argc and argv) are passed by run_rpc_command
5975  * function.
5976  *
5977  * @param c     A net_context structure.
5978  * @param domain_sid The domain sid acquired from the server.
5979  * @param cli A cli_state connected to the server.
5980  * @param mem_ctx Talloc context, destroyed on completion of the function.
5981  * @param argc  Standard main() style argc.
5982  * @param argv  Standard main() style argv. Initial components are already
5983  *              stripped.
5984  *
5985  * @return normal NTSTATUS return code.
5986  */
5987
5988 static NTSTATUS rpc_trustdom_add_internals(struct net_context *c,
5989                                                 const struct dom_sid *domain_sid,
5990                                                 const char *domain_name,
5991                                                 struct cli_state *cli,
5992                                                 struct rpc_pipe_client *pipe_hnd,
5993                                                 TALLOC_CTX *mem_ctx,
5994                                                 int argc,
5995                                                 const char **argv)
5996 {
5997         struct policy_handle connect_pol, domain_pol, user_pol;
5998         NTSTATUS status, result;
5999         char *acct_name;
6000         struct lsa_String lsa_acct_name;
6001         uint32 acb_info;
6002         uint32 acct_flags=0;
6003         uint32 user_rid;
6004         uint32_t access_granted = 0;
6005         union samr_UserInfo info;
6006         unsigned int orig_timeout;
6007         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
6008         DATA_BLOB session_key = data_blob_null;
6009
6010         if (argc != 2) {
6011                 d_printf("%s\n%s",
6012                          _("Usage:"),
6013                          _(" net rpc trustdom add <domain_name> "
6014                            "<trust password>\n"));
6015                 return NT_STATUS_INVALID_PARAMETER;
6016         }
6017
6018         /*
6019          * Make valid trusting domain account (ie. uppercased and with '$' appended)
6020          */
6021
6022         if (asprintf(&acct_name, "%s$", argv[0]) < 0) {
6023                 return NT_STATUS_NO_MEMORY;
6024         }
6025
6026         if (!strupper_m(acct_name)) {
6027                 SAFE_FREE(acct_name);
6028                 return NT_STATUS_INVALID_PARAMETER;
6029         }
6030
6031         init_lsa_String(&lsa_acct_name, acct_name);
6032
6033         status = cli_get_session_key(mem_ctx, pipe_hnd, &session_key);
6034         if (!NT_STATUS_IS_OK(status)) {
6035                 DEBUG(0,("Error getting session_key of SAM pipe. Error was %s\n",
6036                         nt_errstr(status)));
6037                 goto done;
6038         }
6039
6040         /* Get samr policy handle */
6041         status = dcerpc_samr_Connect2(b, mem_ctx,
6042                                       pipe_hnd->desthost,
6043                                       MAXIMUM_ALLOWED_ACCESS,
6044                                       &connect_pol,
6045                                       &result);
6046         if (!NT_STATUS_IS_OK(status)) {
6047                 goto done;
6048         }
6049         if (!NT_STATUS_IS_OK(result)) {
6050                 status = result;
6051                 goto done;
6052         }
6053
6054         /* Get domain policy handle */
6055         status = dcerpc_samr_OpenDomain(b, mem_ctx,
6056                                         &connect_pol,
6057                                         MAXIMUM_ALLOWED_ACCESS,
6058                                         discard_const_p(struct dom_sid2, domain_sid),
6059                                         &domain_pol,
6060                                         &result);
6061         if (!NT_STATUS_IS_OK(status)) {
6062                 goto done;
6063         }
6064         if (!NT_STATUS_IS_OK(result)) {
6065                 status = result;
6066                 goto done;
6067         }
6068
6069         /* This call can take a long time - allow the server to time out.
6070          * 35 seconds should do it. */
6071
6072         orig_timeout = rpccli_set_timeout(pipe_hnd, 35000);
6073
6074         /* Create trusting domain's account */
6075         acb_info = ACB_NORMAL;
6076         acct_flags = SEC_GENERIC_READ | SEC_GENERIC_WRITE | SEC_GENERIC_EXECUTE |
6077                      SEC_STD_WRITE_DAC | SEC_STD_DELETE |
6078                      SAMR_USER_ACCESS_SET_PASSWORD |
6079                      SAMR_USER_ACCESS_GET_ATTRIBUTES |
6080                      SAMR_USER_ACCESS_SET_ATTRIBUTES;
6081
6082         status = dcerpc_samr_CreateUser2(b, mem_ctx,
6083                                          &domain_pol,
6084                                          &lsa_acct_name,
6085                                          acb_info,
6086                                          acct_flags,
6087                                          &user_pol,
6088                                          &access_granted,
6089                                          &user_rid,
6090                                          &result);
6091         if (!NT_STATUS_IS_OK(status)) {
6092                 goto done;
6093         }
6094         /* And restore our original timeout. */
6095         rpccli_set_timeout(pipe_hnd, orig_timeout);
6096
6097         if (!NT_STATUS_IS_OK(result)) {
6098                 status = result;
6099                 d_printf(_("net rpc trustdom add: create user %s failed %s\n"),
6100                         acct_name, nt_errstr(result));
6101                 goto done;
6102         }
6103
6104         {
6105                 struct samr_CryptPassword crypt_pwd;
6106
6107                 ZERO_STRUCT(info.info23);
6108
6109                 init_samr_CryptPassword(argv[1],
6110                                         &session_key,
6111                                         &crypt_pwd);
6112
6113                 info.info23.info.fields_present = SAMR_FIELD_ACCT_FLAGS |
6114                                                   SAMR_FIELD_NT_PASSWORD_PRESENT;
6115                 info.info23.info.acct_flags = ACB_DOMTRUST;
6116                 info.info23.password = crypt_pwd;
6117
6118                 status = dcerpc_samr_SetUserInfo2(b, mem_ctx,
6119                                                   &user_pol,
6120                                                   23,
6121                                                   &info,
6122                                                   &result);
6123                 if (!NT_STATUS_IS_OK(status)) {
6124                         goto done;
6125                 }
6126
6127                 if (!NT_STATUS_IS_OK(result)) {
6128                         status = result;
6129                         DEBUG(0,("Could not set trust account password: %s\n",
6130                                  nt_errstr(result)));
6131                         goto done;
6132                 }
6133         }
6134
6135  done:
6136         SAFE_FREE(acct_name);
6137         data_blob_clear_free(&session_key);
6138         return status;
6139 }
6140
6141 /**
6142  * Create interdomain trust account for a remote domain.
6143  *
6144  * @param argc Standard argc.
6145  * @param argv Standard argv without initial components.
6146  *
6147  * @return Integer status (0 means success).
6148  **/
6149
6150 static int rpc_trustdom_add(struct net_context *c, int argc, const char **argv)
6151 {
6152         if (argc > 0 && !c->display_usage) {
6153                 return run_rpc_command(c, NULL, &ndr_table_samr, 0,
6154                                        rpc_trustdom_add_internals, argc, argv);
6155         } else {
6156                 d_printf("%s\n%s",
6157                          _("Usage:"),
6158                          _("net rpc trustdom add <domain_name> <trust "
6159                            "password>\n"));
6160                 return -1;
6161         }
6162 }
6163
6164
6165 /**
6166  * Remove interdomain trust account from the RPC server.
6167  * All parameters (except for argc and argv) are passed by run_rpc_command
6168  * function.
6169  *
6170  * @param c     A net_context structure.
6171  * @param domain_sid The domain sid acquired from the server.
6172  * @param cli A cli_state connected to the server.
6173  * @param mem_ctx Talloc context, destroyed on completion of the function.
6174  * @param argc  Standard main() style argc.
6175  * @param argv  Standard main() style argv. Initial components are already
6176  *              stripped.
6177  *
6178  * @return normal NTSTATUS return code.
6179  */
6180
6181 static NTSTATUS rpc_trustdom_del_internals(struct net_context *c,
6182                                         const struct dom_sid *domain_sid,
6183                                         const char *domain_name,
6184                                         struct cli_state *cli,
6185                                         struct rpc_pipe_client *pipe_hnd,
6186                                         TALLOC_CTX *mem_ctx,
6187                                         int argc,
6188                                         const char **argv)
6189 {
6190         struct policy_handle connect_pol, domain_pol, user_pol;
6191         NTSTATUS status, result;
6192         char *acct_name;
6193         struct dom_sid trust_acct_sid;
6194         struct samr_Ids user_rids, name_types;
6195         struct lsa_String lsa_acct_name;
6196         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
6197
6198         if (argc != 1) {
6199                 d_printf("%s\n%s",
6200                          _("Usage:"),
6201                          _(" net rpc trustdom del <domain_name>\n"));
6202                 return NT_STATUS_INVALID_PARAMETER;
6203         }
6204
6205         /*
6206          * Make valid trusting domain account (ie. uppercased and with '$' appended)
6207          */
6208         acct_name = talloc_asprintf(mem_ctx, "%s$", argv[0]);
6209
6210         if (acct_name == NULL)
6211                 return NT_STATUS_NO_MEMORY;
6212
6213         if (!strupper_m(acct_name)) {
6214                 TALLOC_FREE(acct_name);
6215                 return NT_STATUS_INVALID_PARAMETER;
6216         }
6217
6218         /* Get samr policy handle */
6219         status = dcerpc_samr_Connect2(b, mem_ctx,
6220                                       pipe_hnd->desthost,
6221                                       MAXIMUM_ALLOWED_ACCESS,
6222                                       &connect_pol,
6223                                       &result);
6224         if (!NT_STATUS_IS_OK(status)) {
6225                 goto done;
6226         }
6227         if (!NT_STATUS_IS_OK(result)) {
6228                 status = result;
6229                 goto done;
6230         }
6231
6232         /* Get domain policy handle */
6233         status = dcerpc_samr_OpenDomain(b, mem_ctx,
6234                                         &connect_pol,
6235                                         MAXIMUM_ALLOWED_ACCESS,
6236                                         discard_const_p(struct dom_sid2, domain_sid),
6237                                         &domain_pol,
6238                                         &result);
6239         if (!NT_STATUS_IS_OK(status)) {
6240                 goto done;
6241         }
6242         if (!NT_STATUS_IS_OK(result)) {
6243                 status = result;
6244                 goto done;
6245         }
6246
6247         init_lsa_String(&lsa_acct_name, acct_name);
6248
6249         status = dcerpc_samr_LookupNames(b, mem_ctx,
6250                                          &domain_pol,
6251                                          1,
6252                                          &lsa_acct_name,
6253                                          &user_rids,
6254                                          &name_types,
6255                                          &result);
6256         if (!NT_STATUS_IS_OK(status)) {
6257                 d_printf(_("net rpc trustdom del: LookupNames on user %s "
6258                            "failed %s\n"),
6259                         acct_name, nt_errstr(status));
6260                 goto done;
6261         }
6262         if (!NT_STATUS_IS_OK(result)) {
6263                 status = result;
6264                 d_printf(_("net rpc trustdom del: LookupNames on user %s "
6265                            "failed %s\n"),
6266                         acct_name, nt_errstr(result) );
6267                 goto done;
6268         }
6269         if (user_rids.count != 1) {
6270                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
6271                 goto done;
6272         }
6273         if (name_types.count != 1) {
6274                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
6275                 goto done;
6276         }
6277
6278         status = dcerpc_samr_OpenUser(b, mem_ctx,
6279                                       &domain_pol,
6280                                       MAXIMUM_ALLOWED_ACCESS,
6281                                       user_rids.ids[0],
6282                                       &user_pol,
6283                                       &result);
6284         if (!NT_STATUS_IS_OK(status)) {
6285                 d_printf(_("net rpc trustdom del: OpenUser on user %s failed "
6286                            "%s\n"),
6287                         acct_name, nt_errstr(status) );
6288                 goto done;
6289         }
6290
6291         if (!NT_STATUS_IS_OK(result)) {
6292                 status = result;
6293                 d_printf(_("net rpc trustdom del: OpenUser on user %s failed "
6294                            "%s\n"),
6295                         acct_name, nt_errstr(result) );
6296                 goto done;
6297         }
6298
6299         /* append the rid to the domain sid */
6300         if (!sid_compose(&trust_acct_sid, domain_sid, user_rids.ids[0])) {
6301                 goto done;
6302         }
6303
6304         /* remove the sid */
6305
6306         status = dcerpc_samr_RemoveMemberFromForeignDomain(b, mem_ctx,
6307                                                            &user_pol,
6308                                                            &trust_acct_sid,
6309                                                            &result);
6310         if (!NT_STATUS_IS_OK(status)) {
6311                 d_printf(_("net rpc trustdom del: RemoveMemberFromForeignDomain"
6312                            " on user %s failed %s\n"),
6313                         acct_name, nt_errstr(status));
6314                 goto done;
6315         }
6316         if (!NT_STATUS_IS_OK(result)) {
6317                 status = result;
6318                 d_printf(_("net rpc trustdom del: RemoveMemberFromForeignDomain"
6319                            " on user %s failed %s\n"),
6320                         acct_name, nt_errstr(result) );
6321                 goto done;
6322         }
6323
6324
6325         /* Delete user */
6326
6327         status = dcerpc_samr_DeleteUser(b, mem_ctx,
6328                                         &user_pol,
6329                                         &result);
6330         if (!NT_STATUS_IS_OK(status)) {
6331                 d_printf(_("net rpc trustdom del: DeleteUser on user %s failed "
6332                            "%s\n"),
6333                         acct_name, nt_errstr(status));
6334                 goto done;
6335         }
6336
6337         if (!NT_STATUS_IS_OK(result)) {
6338                 result = status;
6339                 d_printf(_("net rpc trustdom del: DeleteUser on user %s failed "
6340                            "%s\n"),
6341                         acct_name, nt_errstr(result) );
6342                 goto done;
6343         }
6344
6345         if (!NT_STATUS_IS_OK(result)) {
6346                 d_printf(_("Could not set trust account password: %s\n"),
6347                    nt_errstr(result));
6348                 goto done;
6349         }
6350
6351  done:
6352         return status;
6353 }
6354
6355 /**
6356  * Delete interdomain trust account for a remote domain.
6357  *
6358  * @param argc Standard argc.
6359  * @param argv Standard argv without initial components.
6360  *
6361  * @return Integer status (0 means success).
6362  **/
6363
6364 static int rpc_trustdom_del(struct net_context *c, int argc, const char **argv)
6365 {
6366         if (argc > 0 && !c->display_usage) {
6367                 return run_rpc_command(c, NULL, &ndr_table_samr, 0,
6368                                        rpc_trustdom_del_internals, argc, argv);
6369         } else {
6370                 d_printf("%s\n%s",
6371                          _("Usage:"),
6372                          _("net rpc trustdom del <domain>\n"));
6373                 return -1;
6374         }
6375 }
6376
6377 static NTSTATUS rpc_trustdom_get_pdc(struct net_context *c,
6378                                      struct cli_state *cli,
6379                                      TALLOC_CTX *mem_ctx,
6380                                      const char *domain_name)
6381 {
6382         char *dc_name = NULL;
6383         const char *buffer = NULL;
6384         struct rpc_pipe_client *netr;
6385         NTSTATUS status;
6386         WERROR result;
6387         struct dcerpc_binding_handle *b;
6388
6389         /* Use NetServerEnum2 */
6390
6391         if (cli_get_pdc_name(cli, domain_name, &dc_name)) {
6392                 SAFE_FREE(dc_name);
6393                 return NT_STATUS_OK;
6394         }
6395
6396         DEBUG(1,("NetServerEnum2 error: Couldn't find primary domain controller\
6397                  for domain %s\n", domain_name));
6398
6399         /* Try netr_GetDcName */
6400
6401         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_netlogon,
6402                                           &netr);
6403         if (!NT_STATUS_IS_OK(status)) {
6404                 return status;
6405         }
6406
6407         b = netr->binding_handle;
6408
6409         status = dcerpc_netr_GetDcName(b, mem_ctx,
6410                                        netr->desthost,
6411                                        domain_name,
6412                                        &buffer,
6413                                        &result);
6414         TALLOC_FREE(netr);
6415
6416         if (NT_STATUS_IS_OK(status) && W_ERROR_IS_OK(result)) {
6417                 return status;
6418         }
6419
6420         DEBUG(1,("netr_GetDcName error: Couldn't find primary domain controller\
6421                  for domain %s\n", domain_name));
6422
6423         if (!NT_STATUS_IS_OK(status)) {
6424                 return status;
6425         }
6426
6427         return werror_to_ntstatus(result);
6428 }
6429
6430 /**
6431  * Establish trust relationship to a trusting domain.
6432  * Interdomain account must already be created on remote PDC.
6433  *
6434  * @param c    A net_context structure.
6435  * @param argc Standard argc.
6436  * @param argv Standard argv without initial components.
6437  *
6438  * @return Integer status (0 means success).
6439  **/
6440
6441 static int rpc_trustdom_establish(struct net_context *c, int argc,
6442                                   const char **argv)
6443 {
6444         struct cli_state *cli = NULL;
6445         struct sockaddr_storage server_ss;
6446         struct rpc_pipe_client *pipe_hnd = NULL;
6447         struct policy_handle connect_hnd;
6448         TALLOC_CTX *mem_ctx;
6449         NTSTATUS nt_status, result;
6450         struct dom_sid *domain_sid;
6451
6452         char* domain_name;
6453         char* acct_name;
6454         fstring pdc_name;
6455         union lsa_PolicyInformation *info = NULL;
6456         struct dcerpc_binding_handle *b;
6457
6458         /*
6459          * Connect to \\server\ipc$ as 'our domain' account with password
6460          */
6461
6462         if (argc != 1 || c->display_usage) {
6463                 d_printf("%s\n%s",
6464                          _("Usage:"),
6465                          _("net rpc trustdom establish <domain_name>\n"));
6466                 return -1;
6467         }
6468
6469         domain_name = smb_xstrdup(argv[0]);
6470         if (!strupper_m(domain_name)) {
6471                 SAFE_FREE(domain_name);
6472                 return -1;
6473         }
6474
6475         /* account name used at first is our domain's name with '$' */
6476         if (asprintf(&acct_name, "%s$", lp_workgroup()) == -1) {
6477                 return -1;
6478         }
6479         if (!strupper_m(acct_name)) {
6480                 SAFE_FREE(domain_name);
6481                 SAFE_FREE(acct_name);
6482                 return -1;
6483         }
6484
6485         /*
6486          * opt_workgroup will be used by connection functions further,
6487          * hence it should be set to remote domain name instead of ours
6488          */
6489         if (c->opt_workgroup) {
6490                 c->opt_workgroup = smb_xstrdup(domain_name);
6491         };
6492
6493         c->opt_user_name = acct_name;
6494
6495         /* find the domain controller */
6496         if (!net_find_pdc(&server_ss, pdc_name, domain_name)) {
6497                 DEBUG(0, ("Couldn't find domain controller for domain %s\n", domain_name));
6498                 return -1;
6499         }
6500
6501         /* connect to ipc$ as username/password */
6502         nt_status = connect_to_ipc(c, &cli, &server_ss, pdc_name);
6503         if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT)) {
6504
6505                 /* Is it trusting domain account for sure ? */
6506                 DEBUG(0, ("Couldn't verify trusting domain account. Error was %s\n",
6507                         nt_errstr(nt_status)));
6508                 return -1;
6509         }
6510
6511         /* store who we connected to */
6512
6513         saf_store( domain_name, pdc_name );
6514
6515         /*
6516          * Connect to \\server\ipc$ again (this time anonymously)
6517          */
6518
6519         nt_status = connect_to_ipc_anonymous(c, &cli, &server_ss,
6520                                              (char*)pdc_name);
6521
6522         if (NT_STATUS_IS_ERR(nt_status)) {
6523                 DEBUG(0, ("Couldn't connect to domain %s controller. Error was %s.\n",
6524                         domain_name, nt_errstr(nt_status)));
6525                 return -1;
6526         }
6527
6528         if (!(mem_ctx = talloc_init("establishing trust relationship to "
6529                                     "domain %s", domain_name))) {
6530                 DEBUG(0, ("talloc_init() failed\n"));
6531                 cli_shutdown(cli);
6532                 return -1;
6533         }
6534
6535         /* Make sure we're talking to a proper server */
6536
6537         nt_status = rpc_trustdom_get_pdc(c, cli, mem_ctx, domain_name);
6538         if (!NT_STATUS_IS_OK(nt_status)) {
6539                 cli_shutdown(cli);
6540                 talloc_destroy(mem_ctx);
6541                 return -1;
6542         }
6543
6544         /*
6545          * Call LsaOpenPolicy and LsaQueryInfo
6546          */
6547
6548         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
6549                                              &pipe_hnd);
6550         if (!NT_STATUS_IS_OK(nt_status)) {
6551                 DEBUG(0, ("Could not initialise lsa pipe. Error was %s\n", nt_errstr(nt_status) ));
6552                 cli_shutdown(cli);
6553                 talloc_destroy(mem_ctx);
6554                 return -1;
6555         }
6556
6557         b = pipe_hnd->binding_handle;
6558
6559         nt_status = rpccli_lsa_open_policy2(pipe_hnd, mem_ctx, true, KEY_QUERY_VALUE,
6560                                          &connect_hnd);
6561         if (NT_STATUS_IS_ERR(nt_status)) {
6562                 DEBUG(0, ("Couldn't open policy handle. Error was %s\n",
6563                         nt_errstr(nt_status)));
6564                 cli_shutdown(cli);
6565                 talloc_destroy(mem_ctx);
6566                 return -1;
6567         }
6568
6569         /* Querying info level 5 */
6570
6571         nt_status = dcerpc_lsa_QueryInfoPolicy(b, mem_ctx,
6572                                                &connect_hnd,
6573                                                LSA_POLICY_INFO_ACCOUNT_DOMAIN,
6574                                                &info,
6575                                                &result);
6576         if (NT_STATUS_IS_ERR(nt_status)) {
6577                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
6578                         nt_errstr(nt_status)));
6579                 cli_shutdown(cli);
6580                 talloc_destroy(mem_ctx);
6581                 return -1;
6582         }
6583         if (NT_STATUS_IS_ERR(result)) {
6584                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
6585                         nt_errstr(result)));
6586                 cli_shutdown(cli);
6587                 talloc_destroy(mem_ctx);
6588                 return -1;
6589         }
6590
6591         domain_sid = info->account_domain.sid;
6592
6593         /* There should be actually query info level 3 (following nt serv behaviour),
6594            but I still don't know if it's _really_ necessary */
6595
6596         /*
6597          * Store the password in secrets db
6598          */
6599
6600         if (!pdb_set_trusteddom_pw(domain_name, c->opt_password, domain_sid)) {
6601                 DEBUG(0, ("Storing password for trusted domain failed.\n"));
6602                 cli_shutdown(cli);
6603                 talloc_destroy(mem_ctx);
6604                 return -1;
6605         }
6606
6607         /*
6608          * Close the pipes and clean up
6609          */
6610
6611         nt_status = dcerpc_lsa_Close(b, mem_ctx, &connect_hnd, &result);
6612         if (NT_STATUS_IS_ERR(nt_status)) {
6613                 DEBUG(0, ("Couldn't close LSA pipe. Error was %s\n",
6614                         nt_errstr(nt_status)));
6615                 cli_shutdown(cli);
6616                 talloc_destroy(mem_ctx);
6617                 return -1;
6618         }
6619
6620         cli_shutdown(cli);
6621
6622         talloc_destroy(mem_ctx);
6623
6624         d_printf(_("Trust to domain %s established\n"), domain_name);
6625         return 0;
6626 }
6627
6628 /**
6629  * Revoke trust relationship to the remote domain.
6630  *
6631  * @param c    A net_context structure.
6632  * @param argc Standard argc.
6633  * @param argv Standard argv without initial components.
6634  *
6635  * @return Integer status (0 means success).
6636  **/
6637
6638 static int rpc_trustdom_revoke(struct net_context *c, int argc,
6639                                const char **argv)
6640 {
6641         char* domain_name;
6642         int rc = -1;
6643
6644         if (argc < 1 || c->display_usage) {
6645                 d_printf("%s\n%s",
6646                          _("Usage:"),
6647                          _("net rpc trustdom revoke <domain_name>\n"
6648                            "  Revoke trust relationship\n"
6649                            "    domain_name\tName of domain to revoke trust\n"));
6650                 return -1;
6651         }
6652
6653         /* generate upper cased domain name */
6654         domain_name = smb_xstrdup(argv[0]);
6655         if (!strupper_m(domain_name)) {
6656                 SAFE_FREE(domain_name);
6657                 return -1;
6658         }
6659
6660         /* delete password of the trust */
6661         if (!pdb_del_trusteddom_pw(domain_name)) {
6662                 DEBUG(0, ("Failed to revoke relationship to the trusted domain %s\n",
6663                           domain_name));
6664                 goto done;
6665         };
6666
6667         rc = 0;
6668 done:
6669         SAFE_FREE(domain_name);
6670         return rc;
6671 }
6672
6673 static NTSTATUS rpc_query_domain_sid(struct net_context *c,
6674                                         const struct dom_sid *domain_sid,
6675                                         const char *domain_name,
6676                                         struct cli_state *cli,
6677                                         struct rpc_pipe_client *pipe_hnd,
6678                                         TALLOC_CTX *mem_ctx,
6679                                         int argc,
6680                                         const char **argv)
6681 {
6682         fstring str_sid;
6683         if (!sid_to_fstring(str_sid, domain_sid)) {
6684                 return NT_STATUS_UNSUCCESSFUL;
6685         }
6686         d_printf("%s\n", str_sid);
6687         return NT_STATUS_OK;
6688 }
6689
6690 static void print_trusted_domain(struct dom_sid *dom_sid, const char *trusted_dom_name)
6691 {
6692         fstring ascii_sid;
6693
6694         /* convert sid into ascii string */
6695         sid_to_fstring(ascii_sid, dom_sid);
6696
6697         d_printf("%-20s%s\n", trusted_dom_name, ascii_sid);
6698 }
6699
6700 static NTSTATUS vampire_trusted_domain(struct rpc_pipe_client *pipe_hnd,
6701                                       TALLOC_CTX *mem_ctx,
6702                                       struct policy_handle *pol,
6703                                       struct dom_sid dom_sid,
6704                                       const char *trusted_dom_name)
6705 {
6706         NTSTATUS nt_status, result;
6707         union lsa_TrustedDomainInfo *info = NULL;
6708         char *cleartextpwd = NULL;
6709         DATA_BLOB session_key;
6710         DATA_BLOB data = data_blob_null;
6711         struct dcerpc_binding_handle *b = pipe_hnd->binding_handle;
6712
6713         nt_status = dcerpc_lsa_QueryTrustedDomainInfoBySid(b, mem_ctx,
6714                                                            pol,
6715                                                            &dom_sid,
6716                                                            LSA_TRUSTED_DOMAIN_INFO_PASSWORD,
6717                                                            &info,
6718                                                            &result);
6719         if (NT_STATUS_IS_ERR(nt_status)) {
6720                 DEBUG(0,("Could not query trusted domain info. Error was %s\n",
6721                 nt_errstr(nt_status)));
6722                 goto done;
6723         }
6724         if (NT_STATUS_IS_ERR(result)) {
6725                 nt_status = result;
6726                 DEBUG(0,("Could not query trusted domain info. Error was %s\n",
6727                 nt_errstr(result)));
6728                 goto done;
6729         }
6730
6731         data = data_blob(info->password.password->data,
6732                          info->password.password->length);
6733
6734         nt_status = cli_get_session_key(mem_ctx, pipe_hnd, &session_key);
6735         if (!NT_STATUS_IS_OK(nt_status)) {
6736                 DEBUG(0, ("Could not retrieve session key: %s\n", nt_errstr(nt_status)));
6737                 goto done;
6738         }
6739
6740         cleartextpwd = sess_decrypt_string(mem_ctx, &data, &session_key);
6741         data_blob_free(&session_key);
6742
6743         if (cleartextpwd == NULL) {
6744                 DEBUG(0,("retrieved NULL password\n"));
6745                 nt_status = NT_STATUS_UNSUCCESSFUL;
6746                 goto done;
6747         }
6748
6749         if (!pdb_set_trusteddom_pw(trusted_dom_name, cleartextpwd, &dom_sid)) {
6750                 DEBUG(0, ("Storing password for trusted domain failed.\n"));
6751                 nt_status = NT_STATUS_UNSUCCESSFUL;
6752                 goto done;
6753         }
6754
6755 #ifdef DEBUG_PASSWORD
6756         DEBUG(100,("successfully vampired trusted domain [%s], sid: [%s], "
6757                    "password: [%s]\n", trusted_dom_name,
6758                    sid_string_dbg(&dom_sid), cleartextpwd));
6759 #endif
6760
6761 done:
6762         SAFE_FREE(cleartextpwd);
6763         data_blob_free(&data);
6764
6765         return nt_status;
6766 }
6767
6768 static int rpc_trustdom_vampire(struct net_context *c, int argc,
6769                                 const char **argv)
6770 {
6771         /* common variables */
6772         TALLOC_CTX* mem_ctx;
6773         struct cli_state *cli = NULL;
6774         struct rpc_pipe_client *pipe_hnd = NULL;
6775         NTSTATUS nt_status, result;
6776         const char *domain_name = NULL;
6777         struct policy_handle connect_hnd;
6778         union lsa_PolicyInformation *info = NULL;
6779
6780         /* trusted domains listing variables */
6781         unsigned int enum_ctx = 0;
6782         int i;
6783         struct lsa_DomainList dom_list;
6784         fstring pdc_name;
6785         struct dcerpc_binding_handle *b;
6786
6787         if (c->display_usage) {
6788                 d_printf(  "%s\n"
6789                            "net rpc trustdom vampire\n"
6790                            "  %s\n",
6791                          _("Usage:"),
6792                          _("Vampire trust relationship from remote server"));
6793                 return 0;
6794         }
6795
6796         /*
6797          * Listing trusted domains (stored in secrets.tdb, if local)
6798          */
6799
6800         mem_ctx = talloc_init("trust relationships vampire");
6801
6802         /*
6803          * set domain and pdc name to local samba server (default)
6804          * or to remote one given in command line
6805          */
6806
6807         if (strcasecmp_m(c->opt_workgroup, lp_workgroup())) {
6808                 domain_name = c->opt_workgroup;
6809                 c->opt_target_workgroup = c->opt_workgroup;
6810         } else {
6811                 fstrcpy(pdc_name, lp_netbios_name());
6812                 domain_name = talloc_strdup(mem_ctx, lp_workgroup());
6813                 c->opt_target_workgroup = domain_name;
6814         };
6815
6816         /* open \PIPE\lsarpc and open policy handle */
6817         nt_status = net_make_ipc_connection(c, NET_FLAGS_PDC, &cli);
6818         if (!NT_STATUS_IS_OK(nt_status)) {
6819                 DEBUG(0, ("Couldn't connect to domain controller: %s\n",
6820                           nt_errstr(nt_status)));
6821                 talloc_destroy(mem_ctx);
6822                 return -1;
6823         };
6824
6825         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
6826                                              &pipe_hnd);
6827         if (!NT_STATUS_IS_OK(nt_status)) {
6828                 DEBUG(0, ("Could not initialise lsa pipe. Error was %s\n",
6829                         nt_errstr(nt_status) ));
6830                 cli_shutdown(cli);
6831                 talloc_destroy(mem_ctx);
6832                 return -1;
6833         };
6834
6835         b = pipe_hnd->binding_handle;
6836
6837         nt_status = rpccli_lsa_open_policy2(pipe_hnd, mem_ctx, false, KEY_QUERY_VALUE,
6838                                         &connect_hnd);
6839         if (NT_STATUS_IS_ERR(nt_status)) {
6840                 DEBUG(0, ("Couldn't open policy handle. Error was %s\n",
6841                         nt_errstr(nt_status)));
6842                 cli_shutdown(cli);
6843                 talloc_destroy(mem_ctx);
6844                 return -1;
6845         };
6846
6847         /* query info level 5 to obtain sid of a domain being queried */
6848         nt_status = dcerpc_lsa_QueryInfoPolicy(b, mem_ctx,
6849                                                &connect_hnd,
6850                                                LSA_POLICY_INFO_ACCOUNT_DOMAIN,
6851                                                &info,
6852                                                &result);
6853
6854         if (NT_STATUS_IS_ERR(nt_status)) {
6855                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
6856                         nt_errstr(nt_status)));
6857                 cli_shutdown(cli);
6858                 talloc_destroy(mem_ctx);
6859                 return -1;
6860         }
6861         if (NT_STATUS_IS_ERR(result)) {
6862                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
6863                         nt_errstr(result)));
6864                 cli_shutdown(cli);
6865                 talloc_destroy(mem_ctx);
6866                 return -1;
6867         }
6868
6869         /*
6870          * Keep calling LsaEnumTrustdom over opened pipe until
6871          * the end of enumeration is reached
6872          */
6873
6874         d_printf(_("Vampire trusted domains:\n\n"));
6875
6876         do {
6877                 nt_status = dcerpc_lsa_EnumTrustDom(b, mem_ctx,
6878                                                     &connect_hnd,
6879                                                     &enum_ctx,
6880                                                     &dom_list,
6881                                                     (uint32_t)-1,
6882                                                     &result);
6883                 if (NT_STATUS_IS_ERR(nt_status)) {
6884                         DEBUG(0, ("Couldn't enumerate trusted domains. Error was %s\n",
6885                                 nt_errstr(nt_status)));
6886                         cli_shutdown(cli);
6887                         talloc_destroy(mem_ctx);
6888                         return -1;
6889                 };
6890                 if (NT_STATUS_IS_ERR(result)) {
6891                         nt_status = result;
6892                         DEBUG(0, ("Couldn't enumerate trusted domains. Error was %s\n",
6893                                 nt_errstr(result)));
6894                         cli_shutdown(cli);
6895                         talloc_destroy(mem_ctx);
6896                         return -1;
6897                 };
6898
6899
6900                 for (i = 0; i < dom_list.count; i++) {
6901
6902                         print_trusted_domain(dom_list.domains[i].sid,
6903                                              dom_list.domains[i].name.string);
6904
6905                         nt_status = vampire_trusted_domain(pipe_hnd, mem_ctx, &connect_hnd,
6906                                                            *dom_list.domains[i].sid,
6907                                                            dom_list.domains[i].name.string);
6908                         if (!NT_STATUS_IS_OK(nt_status)) {
6909                                 cli_shutdown(cli);
6910                                 talloc_destroy(mem_ctx);
6911                                 return -1;
6912                         }
6913                 };
6914
6915                 /*
6916                  * in case of no trusted domains say something rather
6917                  * than just display blank line
6918                  */
6919                 if (!dom_list.count) d_printf(_("none\n"));
6920
6921         } while (NT_STATUS_EQUAL(nt_status, STATUS_MORE_ENTRIES));
6922
6923         /* close this connection before doing next one */
6924         nt_status = dcerpc_lsa_Close(b, mem_ctx, &connect_hnd, &result);
6925         if (NT_STATUS_IS_ERR(nt_status)) {
6926                 DEBUG(0, ("Couldn't properly close lsa policy handle. Error was %s\n",
6927                         nt_errstr(nt_status)));
6928                 cli_shutdown(cli);
6929                 talloc_destroy(mem_ctx);
6930                 return -1;
6931         };
6932
6933         /* close lsarpc pipe and connection to IPC$ */
6934         cli_shutdown(cli);
6935
6936         talloc_destroy(mem_ctx);
6937         return 0;
6938 }
6939
6940 static int rpc_trustdom_list(struct net_context *c, int argc, const char **argv)
6941 {
6942         /* common variables */
6943         TALLOC_CTX* mem_ctx;
6944         struct cli_state *cli = NULL, *remote_cli = NULL;
6945         struct rpc_pipe_client *pipe_hnd = NULL;
6946         NTSTATUS nt_status, result;
6947         const char *domain_name = NULL;
6948         struct dom_sid *queried_dom_sid;
6949         int ascii_dom_name_len;
6950         struct policy_handle connect_hnd;
6951         union lsa_PolicyInformation *info = NULL;
6952         struct dcerpc_binding_handle *b = NULL;
6953
6954         /* trusted domains listing variables */
6955         unsigned int num_domains, enum_ctx = 0;
6956         int i;
6957         struct lsa_DomainList dom_list;
6958         fstring pdc_name;
6959         bool found_domain;
6960
6961         /* trusting domains listing variables */
6962         struct policy_handle domain_hnd;
6963         struct samr_SamArray *trusts = NULL;
6964
6965         if (c->display_usage) {
6966                 d_printf(  "%s\n"
6967                            "net rpc trustdom list\n"
6968                            "    %s\n",
6969                          _("Usage:"),
6970                          _("List incoming and outgoing trust relationships"));
6971                 return 0;
6972         }
6973
6974         /*
6975          * Listing trusted domains (stored in secrets.tdb, if local)
6976          */
6977
6978         mem_ctx = talloc_init("trust relationships listing");
6979
6980         /*
6981          * set domain and pdc name to local samba server (default)
6982          * or to remote one given in command line
6983          */
6984
6985         if (strcasecmp_m(c->opt_workgroup, lp_workgroup())) {
6986                 domain_name = c->opt_workgroup;
6987                 c->opt_target_workgroup = c->opt_workgroup;
6988         } else {
6989                 fstrcpy(pdc_name, lp_netbios_name());
6990                 domain_name = talloc_strdup(mem_ctx, lp_workgroup());
6991                 c->opt_target_workgroup = domain_name;
6992         };
6993
6994         /* open \PIPE\lsarpc and open policy handle */
6995         nt_status = net_make_ipc_connection(c, NET_FLAGS_PDC, &cli);
6996         if (!NT_STATUS_IS_OK(nt_status)) {
6997                 DEBUG(0, ("Couldn't connect to domain controller: %s\n",
6998                           nt_errstr(nt_status)));
6999                 talloc_destroy(mem_ctx);
7000                 return -1;
7001         };
7002
7003         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
7004                                              &pipe_hnd);
7005         if (!NT_STATUS_IS_OK(nt_status)) {
7006                 DEBUG(0, ("Could not initialise lsa pipe. Error was %s\n",
7007                         nt_errstr(nt_status) ));
7008                 cli_shutdown(cli);
7009                 talloc_destroy(mem_ctx);
7010                 return -1;
7011         };
7012
7013         b = pipe_hnd->binding_handle;
7014
7015         nt_status = rpccli_lsa_open_policy2(pipe_hnd, mem_ctx, false, KEY_QUERY_VALUE,
7016                                         &connect_hnd);
7017         if (NT_STATUS_IS_ERR(nt_status)) {
7018                 DEBUG(0, ("Couldn't open policy handle. Error was %s\n",
7019                         nt_errstr(nt_status)));
7020                 cli_shutdown(cli);
7021                 talloc_destroy(mem_ctx);
7022                 return -1;
7023         };
7024
7025         /* query info level 5 to obtain sid of a domain being queried */
7026         nt_status = dcerpc_lsa_QueryInfoPolicy(b, mem_ctx,
7027                                                &connect_hnd,
7028                                                LSA_POLICY_INFO_ACCOUNT_DOMAIN,
7029                                                &info,
7030                                                &result);
7031
7032         if (NT_STATUS_IS_ERR(nt_status)) {
7033                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
7034                         nt_errstr(nt_status)));
7035                 cli_shutdown(cli);
7036                 talloc_destroy(mem_ctx);
7037                 return -1;
7038         }
7039         if (NT_STATUS_IS_ERR(result)) {
7040                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
7041                         nt_errstr(result)));
7042                 cli_shutdown(cli);
7043                 talloc_destroy(mem_ctx);
7044                 return -1;
7045         }
7046
7047         queried_dom_sid = info->account_domain.sid;
7048
7049         /*
7050          * Keep calling LsaEnumTrustdom over opened pipe until
7051          * the end of enumeration is reached
7052          */
7053
7054         d_printf(_("Trusted domains list:\n\n"));
7055
7056         found_domain = false;
7057
7058         do {
7059                 nt_status = dcerpc_lsa_EnumTrustDom(b, mem_ctx,
7060                                                     &connect_hnd,
7061                                                     &enum_ctx,
7062                                                     &dom_list,
7063                                                     (uint32_t)-1,
7064                                                     &result);
7065                 if (NT_STATUS_IS_ERR(nt_status)) {
7066                         DEBUG(0, ("Couldn't enumerate trusted domains. Error was %s\n",
7067                                 nt_errstr(nt_status)));
7068                         cli_shutdown(cli);
7069                         talloc_destroy(mem_ctx);
7070                         return -1;
7071                 };
7072                 if (NT_STATUS_IS_ERR(result)) {
7073                         DEBUG(0, ("Couldn't enumerate trusted domains. Error was %s\n",
7074                                 nt_errstr(result)));
7075                         cli_shutdown(cli);
7076                         talloc_destroy(mem_ctx);
7077                         return -1;
7078                 };
7079
7080
7081                 for (i = 0; i < dom_list.count; i++) {
7082                         print_trusted_domain(dom_list.domains[i].sid,
7083                                              dom_list.domains[i].name.string);
7084                         found_domain = true;
7085                 };
7086
7087
7088         } while (NT_STATUS_EQUAL(nt_status, STATUS_MORE_ENTRIES));
7089
7090         /*
7091          * in case of no trusted domains say something rather
7092          * than just display blank line
7093          */
7094         if (!found_domain) {
7095                 d_printf(_("none\n"));
7096         }
7097
7098         /* close this connection before doing next one */
7099         nt_status = dcerpc_lsa_Close(b, mem_ctx, &connect_hnd, &result);
7100         if (NT_STATUS_IS_ERR(nt_status)) {
7101                 DEBUG(0, ("Couldn't properly close lsa policy handle. Error was %s\n",
7102                         nt_errstr(nt_status)));
7103                 cli_shutdown(cli);
7104                 talloc_destroy(mem_ctx);
7105                 return -1;
7106         };
7107
7108         TALLOC_FREE(pipe_hnd);
7109
7110         /*
7111          * Listing trusting domains (stored in passdb backend, if local)
7112          */
7113
7114         d_printf(_("\nTrusting domains list:\n\n"));
7115
7116         /*
7117          * Open \PIPE\samr and get needed policy handles
7118          */
7119         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_samr,
7120                                              &pipe_hnd);
7121         if (!NT_STATUS_IS_OK(nt_status)) {
7122                 DEBUG(0, ("Could not initialise samr pipe. Error was %s\n", nt_errstr(nt_status)));
7123                 cli_shutdown(cli);
7124                 talloc_destroy(mem_ctx);
7125                 return -1;
7126         };
7127
7128         b = pipe_hnd->binding_handle;
7129
7130         /* SamrConnect2 */
7131         nt_status = dcerpc_samr_Connect2(b, mem_ctx,
7132                                          pipe_hnd->desthost,
7133                                          SAMR_ACCESS_LOOKUP_DOMAIN,
7134                                          &connect_hnd,
7135                                          &result);
7136         if (!NT_STATUS_IS_OK(nt_status)) {
7137                 DEBUG(0, ("Couldn't open SAMR policy handle. Error was %s\n",
7138                         nt_errstr(nt_status)));
7139                 cli_shutdown(cli);
7140                 talloc_destroy(mem_ctx);
7141                 return -1;
7142         };
7143         if (!NT_STATUS_IS_OK(result)) {
7144                 nt_status = result;
7145                 DEBUG(0, ("Couldn't open SAMR policy handle. Error was %s\n",
7146                         nt_errstr(result)));
7147                 cli_shutdown(cli);
7148                 talloc_destroy(mem_ctx);
7149                 return -1;
7150         };
7151
7152         /* SamrOpenDomain - we have to open domain policy handle in order to be
7153            able to enumerate accounts*/
7154         nt_status = dcerpc_samr_OpenDomain(b, mem_ctx,
7155                                            &connect_hnd,
7156                                            SAMR_DOMAIN_ACCESS_ENUM_ACCOUNTS,
7157                                            queried_dom_sid,
7158                                            &domain_hnd,
7159                                            &result);
7160         if (!NT_STATUS_IS_OK(nt_status)) {
7161                 DEBUG(0, ("Couldn't open domain object. Error was %s\n",
7162                         nt_errstr(nt_status)));
7163                 cli_shutdown(cli);
7164                 talloc_destroy(mem_ctx);
7165                 return -1;
7166         };
7167         if (!NT_STATUS_IS_OK(result)) {
7168                 nt_status = result;
7169                 DEBUG(0, ("Couldn't open domain object. Error was %s\n",
7170                         nt_errstr(result)));
7171                 cli_shutdown(cli);
7172                 talloc_destroy(mem_ctx);
7173                 return -1;
7174         };
7175
7176         /*
7177          * perform actual enumeration
7178          */
7179
7180         found_domain = false;
7181
7182         enum_ctx = 0;   /* reset enumeration context from last enumeration */
7183         do {
7184
7185                 nt_status = dcerpc_samr_EnumDomainUsers(b, mem_ctx,
7186                                                         &domain_hnd,
7187                                                         &enum_ctx,
7188                                                         ACB_DOMTRUST,
7189                                                         &trusts,
7190                                                         0xffff,
7191                                                         &num_domains,
7192                                                         &result);
7193                 if (NT_STATUS_IS_ERR(nt_status)) {
7194                         DEBUG(0, ("Couldn't enumerate accounts. Error was: %s\n",
7195                                 nt_errstr(nt_status)));
7196                         cli_shutdown(cli);
7197                         talloc_destroy(mem_ctx);
7198                         return -1;
7199                 };
7200                 if (NT_STATUS_IS_ERR(result)) {
7201                         nt_status = result;
7202                         DEBUG(0, ("Couldn't enumerate accounts. Error was: %s\n",
7203                                 nt_errstr(result)));
7204                         cli_shutdown(cli);
7205                         talloc_destroy(mem_ctx);
7206                         return -1;
7207                 };
7208
7209                 for (i = 0; i < num_domains; i++) {
7210
7211                         char *str = discard_const_p(char, trusts->entries[i].name.string);
7212
7213                         found_domain = true;
7214
7215                         /*
7216                          * get each single domain's sid (do we _really_ need this ?):
7217                          *  1) connect to domain's pdc
7218                          *  2) query the pdc for domain's sid
7219                          */
7220
7221                         /* get rid of '$' tail */
7222                         ascii_dom_name_len = strlen(str);
7223                         if (ascii_dom_name_len && ascii_dom_name_len < FSTRING_LEN)
7224                                 str[ascii_dom_name_len - 1] = '\0';
7225
7226                         /* set opt_* variables to remote domain */
7227                         if (!strupper_m(str)) {
7228                                 cli_shutdown(cli);
7229                                 talloc_destroy(mem_ctx);
7230                                 return -1;
7231                         }
7232                         c->opt_workgroup = talloc_strdup(mem_ctx, str);
7233                         c->opt_target_workgroup = c->opt_workgroup;
7234
7235                         d_printf("%-20s", str);
7236
7237                         /* connect to remote domain controller */
7238                         nt_status = net_make_ipc_connection(c,
7239                                         NET_FLAGS_PDC | NET_FLAGS_ANONYMOUS,
7240                                         &remote_cli);
7241                         if (NT_STATUS_IS_OK(nt_status)) {
7242                                 /* query for domain's sid */
7243                                 if (run_rpc_command(
7244                                             c, remote_cli,
7245                                             &ndr_table_lsarpc, 0,
7246                                             rpc_query_domain_sid, argc,
7247                                             argv))
7248                                         d_printf(_("strange - couldn't get domain's sid\n"));
7249
7250                                 cli_shutdown(remote_cli);
7251
7252                         } else {
7253                                 d_fprintf(stderr, _("domain controller is not "
7254                                           "responding: %s\n"),
7255                                           nt_errstr(nt_status));
7256                                 d_printf(_("couldn't get domain's sid\n"));
7257                         }
7258                 }
7259
7260         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
7261
7262         if (!found_domain) {
7263                 d_printf("none\n");
7264         }
7265
7266         /* close opened samr and domain policy handles */
7267         nt_status = dcerpc_samr_Close(b, mem_ctx, &domain_hnd, &result);
7268         if (!NT_STATUS_IS_OK(nt_status)) {
7269                 DEBUG(0, ("Couldn't properly close domain policy handle for domain %s\n", domain_name));
7270         };
7271
7272         nt_status = dcerpc_samr_Close(b, mem_ctx, &connect_hnd, &result);
7273         if (!NT_STATUS_IS_OK(nt_status)) {
7274                 DEBUG(0, ("Couldn't properly close samr policy handle for domain %s\n", domain_name));
7275         };
7276
7277         /* close samr pipe and connection to IPC$ */
7278         cli_shutdown(cli);
7279
7280         talloc_destroy(mem_ctx);
7281         return 0;
7282 }
7283
7284 /**
7285  * Entrypoint for 'net rpc trustdom' code.
7286  *
7287  * @param argc Standard argc.
7288  * @param argv Standard argv without initial components.
7289  *
7290  * @return Integer status (0 means success).
7291  */
7292
7293 static int rpc_trustdom(struct net_context *c, int argc, const char **argv)
7294 {
7295         struct functable func[] = {
7296                 {
7297                         "add",
7298                         rpc_trustdom_add,
7299                         NET_TRANSPORT_RPC,
7300                         N_("Add trusting domain's account"),
7301                         N_("net rpc trustdom add\n"
7302                            "    Add trusting domain's account")
7303                 },
7304                 {
7305                         "del",
7306                         rpc_trustdom_del,
7307                         NET_TRANSPORT_RPC,
7308                         N_("Remove trusting domain's account"),
7309                         N_("net rpc trustdom del\n"
7310                            "    Remove trusting domain's account")
7311                 },
7312                 {
7313                         "establish",
7314                         rpc_trustdom_establish,
7315                         NET_TRANSPORT_RPC,
7316                         N_("Establish outgoing trust relationship"),
7317                         N_("net rpc trustdom establish\n"
7318                            "    Establish outgoing trust relationship")
7319                 },
7320                 {
7321                         "revoke",
7322                         rpc_trustdom_revoke,
7323                         NET_TRANSPORT_RPC,
7324                         N_("Revoke outgoing trust relationship"),
7325                         N_("net rpc trustdom revoke\n"
7326                            "    Revoke outgoing trust relationship")
7327                 },
7328                 {
7329                         "list",
7330                         rpc_trustdom_list,
7331                         NET_TRANSPORT_RPC,
7332                         N_("List in- and outgoing domain trusts"),
7333                         N_("net rpc trustdom list\n"
7334                            "    List in- and outgoing domain trusts")
7335                 },
7336                 {
7337                         "vampire",
7338                         rpc_trustdom_vampire,
7339                         NET_TRANSPORT_RPC,
7340                         N_("Vampire trusts from remote server"),
7341                         N_("net rpc trustdom vampire\n"
7342                            "    Vampire trusts from remote server")
7343                 },
7344                 {NULL, NULL, 0, NULL, NULL}
7345         };
7346
7347         return net_run_function(c, argc, argv, "net rpc trustdom", func);
7348 }
7349
7350 /**
7351  * Check if a server will take rpc commands
7352  * @param flags Type of server to connect to (PDC, DMB, localhost)
7353  *              if the host is not explicitly specified
7354  * @return  bool (true means rpc supported)
7355  */
7356 bool net_rpc_check(struct net_context *c, unsigned flags)
7357 {
7358         struct cli_state *cli;
7359         bool ret = false;
7360         struct sockaddr_storage server_ss;
7361         char *server_name = NULL;
7362         NTSTATUS status;
7363
7364         /* flags (i.e. server type) may depend on command */
7365         if (!net_find_server(c, NULL, flags, &server_ss, &server_name))
7366                 return false;
7367
7368         status = cli_connect_nb(server_name, &server_ss, 0, 0x20,
7369                                 lp_netbios_name(), SMB_SIGNING_DEFAULT,
7370                                 0, &cli);
7371         if (!NT_STATUS_IS_OK(status)) {
7372                 return false;
7373         }
7374         status = smbXcli_negprot(cli->conn, cli->timeout, PROTOCOL_CORE,
7375                                  PROTOCOL_NT1);
7376         if (!NT_STATUS_IS_OK(status))
7377                 goto done;
7378         if (smbXcli_conn_protocol(cli->conn) < PROTOCOL_NT1)
7379                 goto done;
7380
7381         ret = true;
7382  done:
7383         cli_shutdown(cli);
7384         return ret;
7385 }
7386
7387 /* dump sam database via samsync rpc calls */
7388 static int rpc_samdump(struct net_context *c, int argc, const char **argv) {
7389         if (c->display_usage) {
7390                 d_printf(  "%s\n"
7391                            "net rpc samdump\n"
7392                            "    %s\n",
7393                          _("Usage:"),
7394                          _("Dump remote SAM database"));
7395                 return 0;
7396         }
7397
7398         return run_rpc_command(c, NULL, &ndr_table_netlogon,
7399                                NET_FLAGS_ANONYMOUS,
7400                                rpc_samdump_internals, argc, argv);
7401 }
7402
7403 /* syncronise sam database via samsync rpc calls */
7404 static int rpc_vampire(struct net_context *c, int argc, const char **argv)
7405 {
7406         struct functable func[] = {
7407                 {
7408                         "ldif",
7409                         rpc_vampire_ldif,
7410                         NET_TRANSPORT_RPC,
7411                         N_("Dump remote SAM database to ldif"),
7412                         N_("net rpc vampire ldif\n"
7413                            "    Dump remote SAM database to LDIF file or "
7414                            "stdout")
7415                 },
7416                 {
7417                         "keytab",
7418                         rpc_vampire_keytab,
7419                         NET_TRANSPORT_RPC,
7420                         N_("Dump remote SAM database to Kerberos Keytab"),
7421                         N_("net rpc vampire keytab\n"
7422                            "    Dump remote SAM database to Kerberos keytab "
7423                            "file")
7424                 },
7425                 {
7426                         "passdb",
7427                         rpc_vampire_passdb,
7428                         NET_TRANSPORT_RPC,
7429                         N_("Dump remote SAM database to passdb"),
7430                         N_("net rpc vampire passdb\n"
7431                            "    Dump remote SAM database to passdb")
7432                 },
7433
7434                 {NULL, NULL, 0, NULL, NULL}
7435         };
7436
7437         if (argc == 0) {
7438                 if (c->display_usage) {
7439                         d_printf(  "%s\n"
7440                                    "net rpc vampire\n"
7441                                    "    %s\n",
7442                                  _("Usage:"),
7443                                  _("Vampire remote SAM database"));
7444                         return 0;
7445                 }
7446
7447                 return rpc_vampire_passdb(c, argc, argv);
7448         }
7449
7450         return net_run_function(c, argc, argv, "net rpc vampire", func);
7451 }
7452
7453 /**
7454  * Migrate everything from a print server.
7455  *
7456  * @param c     A net_context structure.
7457  * @param argc  Standard main() style argc.
7458  * @param argv  Standard main() style argv. Initial components are already
7459  *              stripped.
7460  *
7461  * @return A shell status integer (0 for success).
7462  *
7463  * The order is important !
7464  * To successfully add drivers the print queues have to exist !
7465  * Applying ACLs should be the last step, because you're easily locked out.
7466  *
7467  **/
7468 static int rpc_printer_migrate_all(struct net_context *c, int argc,
7469                                    const char **argv)
7470 {
7471         int ret;
7472
7473         if (c->display_usage) {
7474                 d_printf(  "%s\n"
7475                            "net rpc printer migrate all\n"
7476                            "    %s\n",
7477                          _("Usage:"),
7478                          _("Migrate everything from a print server"));
7479                 return 0;
7480         }
7481
7482         if (!c->opt_host) {
7483                 d_printf(_("no server to migrate\n"));
7484                 return -1;
7485         }
7486
7487         ret = run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7488                               rpc_printer_migrate_printers_internals, argc,
7489                               argv);
7490         if (ret)
7491                 return ret;
7492
7493         ret = run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7494                               rpc_printer_migrate_drivers_internals, argc,
7495                               argv);
7496         if (ret)
7497                 return ret;
7498
7499         ret = run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7500                               rpc_printer_migrate_forms_internals, argc, argv);
7501         if (ret)
7502                 return ret;
7503
7504         ret = run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7505                               rpc_printer_migrate_settings_internals, argc,
7506                               argv);
7507         if (ret)
7508                 return ret;
7509
7510         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7511                                rpc_printer_migrate_security_internals, argc,
7512                                argv);
7513
7514 }
7515
7516 /**
7517  * Migrate print drivers from a print server.
7518  *
7519  * @param c     A net_context structure.
7520  * @param argc  Standard main() style argc.
7521  * @param argv  Standard main() style argv. Initial components are already
7522  *              stripped.
7523  *
7524  * @return A shell status integer (0 for success).
7525  **/
7526 static int rpc_printer_migrate_drivers(struct net_context *c, int argc,
7527                                        const char **argv)
7528 {
7529         if (c->display_usage) {
7530                 d_printf(  "%s\n"
7531                            "net rpc printer migrate drivers\n"
7532                            "     %s\n",
7533                          _("Usage:"),
7534                          _("Migrate print-drivers from a print-server"));
7535                 return 0;
7536         }
7537
7538         if (!c->opt_host) {
7539                 d_printf(_("no server to migrate\n"));
7540                 return -1;
7541         }
7542
7543         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7544                                rpc_printer_migrate_drivers_internals,
7545                                argc, argv);
7546 }
7547
7548 /**
7549  * Migrate print-forms from a print-server.
7550  *
7551  * @param c     A net_context structure.
7552  * @param argc  Standard main() style argc.
7553  * @param argv  Standard main() style argv. Initial components are already
7554  *              stripped.
7555  *
7556  * @return A shell status integer (0 for success).
7557  **/
7558 static int rpc_printer_migrate_forms(struct net_context *c, int argc,
7559                                      const char **argv)
7560 {
7561         if (c->display_usage) {
7562                 d_printf(  "%s\n"
7563                            "net rpc printer migrate forms\n"
7564                            "    %s\n",
7565                          _("Usage:"),
7566                          _("Migrate print-forms from a print-server"));
7567                 return 0;
7568         }
7569
7570         if (!c->opt_host) {
7571                 d_printf(_("no server to migrate\n"));
7572                 return -1;
7573         }
7574
7575         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7576                                rpc_printer_migrate_forms_internals,
7577                                argc, argv);
7578 }
7579
7580 /**
7581  * Migrate printers from a print-server.
7582  *
7583  * @param c     A net_context structure.
7584  * @param argc  Standard main() style argc.
7585  * @param argv  Standard main() style argv. Initial components are already
7586  *              stripped.
7587  *
7588  * @return A shell status integer (0 for success).
7589  **/
7590 static int rpc_printer_migrate_printers(struct net_context *c, int argc,
7591                                         const char **argv)
7592 {
7593         if (c->display_usage) {
7594                 d_printf(  "%s\n"
7595                            "net rpc printer migrate printers\n"
7596                            "    %s\n",
7597                          _("Usage:"),
7598                          _("Migrate printers from a print-server"));
7599                 return 0;
7600         }
7601
7602         if (!c->opt_host) {
7603                 d_printf(_("no server to migrate\n"));
7604                 return -1;
7605         }
7606
7607         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7608                                rpc_printer_migrate_printers_internals,
7609                                argc, argv);
7610 }
7611
7612 /**
7613  * Migrate printer-ACLs from a print-server
7614  *
7615  * @param c     A net_context structure.
7616  * @param argc  Standard main() style argc.
7617  * @param argv  Standard main() style argv. Initial components are already
7618  *              stripped.
7619  *
7620  * @return A shell status integer (0 for success).
7621  **/
7622 static int rpc_printer_migrate_security(struct net_context *c, int argc,
7623                                         const char **argv)
7624 {
7625         if (c->display_usage) {
7626                 d_printf(  "%s\n"
7627                            "net rpc printer migrate security\n"
7628                            "    %s\n",
7629                          _("Usage:"),
7630                          _("Migrate printer-ACLs from a print-server"));
7631                 return 0;
7632         }
7633
7634         if (!c->opt_host) {
7635                 d_printf(_("no server to migrate\n"));
7636                 return -1;
7637         }
7638
7639         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7640                                rpc_printer_migrate_security_internals,
7641                                argc, argv);
7642 }
7643
7644 /**
7645  * Migrate printer-settings from a print-server.
7646  *
7647  * @param c     A net_context structure.
7648  * @param argc  Standard main() style argc.
7649  * @param argv  Standard main() style argv. Initial components are already
7650  *              stripped.
7651  *
7652  * @return A shell status integer (0 for success).
7653  **/
7654 static int rpc_printer_migrate_settings(struct net_context *c, int argc,
7655                                         const char **argv)
7656 {
7657         if (c->display_usage) {
7658                 d_printf(  "%s\n"
7659                            "net rpc printer migrate settings\n"
7660                             "    %s\n",
7661                           _("Usage:"),
7662                           _("Migrate printer-settings from a "
7663                             "print-server"));
7664                 return 0;
7665         }
7666
7667         if (!c->opt_host) {
7668                 d_printf(_("no server to migrate\n"));
7669                 return -1;
7670         }
7671
7672         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7673                                rpc_printer_migrate_settings_internals,
7674                                argc, argv);
7675 }
7676
7677 /**
7678  * 'net rpc printer' entrypoint.
7679  *
7680  * @param c     A net_context structure.
7681  * @param argc  Standard main() style argc.
7682  * @param argv  Standard main() style argv. Initial components are already
7683  *              stripped.
7684  **/
7685
7686 int rpc_printer_migrate(struct net_context *c, int argc, const char **argv)
7687 {
7688
7689         /* ouch: when addriver and setdriver are called from within
7690            rpc_printer_migrate_drivers_internals, the printer-queue already
7691            *has* to exist */
7692
7693         struct functable func[] = {
7694                 {
7695                         "all",
7696                         rpc_printer_migrate_all,
7697                         NET_TRANSPORT_RPC,
7698                         N_("Migrate all from remote to local print server"),
7699                         N_("net rpc printer migrate all\n"
7700                            "    Migrate all from remote to local print server")
7701                 },
7702                 {
7703                         "drivers",
7704                         rpc_printer_migrate_drivers,
7705                         NET_TRANSPORT_RPC,
7706                         N_("Migrate drivers to local server"),
7707                         N_("net rpc printer migrate drivers\n"
7708                            "    Migrate drivers to local server")
7709                 },
7710                 {
7711                         "forms",
7712                         rpc_printer_migrate_forms,
7713                         NET_TRANSPORT_RPC,
7714                         N_("Migrate froms to local server"),
7715                         N_("net rpc printer migrate forms\n"
7716                            "    Migrate froms to local server")
7717                 },
7718                 {
7719                         "printers",
7720                         rpc_printer_migrate_printers,
7721                         NET_TRANSPORT_RPC,
7722                         N_("Migrate printers to local server"),
7723                         N_("net rpc printer migrate printers\n"
7724                            "    Migrate printers to local server")
7725                 },
7726                 {
7727                         "security",
7728                         rpc_printer_migrate_security,
7729                         NET_TRANSPORT_RPC,
7730                         N_("Mirgate printer ACLs to local server"),
7731                         N_("net rpc printer migrate security\n"
7732                            "    Mirgate printer ACLs to local server")
7733                 },
7734                 {
7735                         "settings",
7736                         rpc_printer_migrate_settings,
7737                         NET_TRANSPORT_RPC,
7738                         N_("Migrate printer settings to local server"),
7739                         N_("net rpc printer migrate settings\n"
7740                            "    Migrate printer settings to local server")
7741                 },
7742                 {NULL, NULL, 0, NULL, NULL}
7743         };
7744
7745         return net_run_function(c, argc, argv, "net rpc printer migrate",func);
7746 }
7747
7748
7749 /**
7750  * List printers on a remote RPC server.
7751  *
7752  * @param c     A net_context structure.
7753  * @param argc  Standard main() style argc.
7754  * @param argv  Standard main() style argv. Initial components are already
7755  *              stripped.
7756  *
7757  * @return A shell status integer (0 for success).
7758  **/
7759 static int rpc_printer_list(struct net_context *c, int argc, const char **argv)
7760 {
7761         if (c->display_usage) {
7762                 d_printf(  "%s\n"
7763                            "net rpc printer list\n"
7764                            "    %s\n",
7765                          _("Usage:"),
7766                          _("List printers on a remote RPC server"));
7767                 return 0;
7768         }
7769
7770         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7771                                rpc_printer_list_internals,
7772                                argc, argv);
7773 }
7774
7775 /**
7776  * List printer-drivers on a remote RPC server.
7777  *
7778  * @param c     A net_context structure.
7779  * @param argc  Standard main() style argc.
7780  * @param argv  Standard main() style argv. Initial components are already
7781  *              stripped.
7782  *
7783  * @return A shell status integer (0 for success).
7784  **/
7785 static int rpc_printer_driver_list(struct net_context *c, int argc,
7786                                    const char **argv)
7787 {
7788         if (c->display_usage) {
7789                 d_printf(  "%s\n"
7790                            "net rpc printer driver\n"
7791                            "    %s\n",
7792                          _("Usage:"),
7793                          _("List printer-drivers on a remote RPC server"));
7794                 return 0;
7795         }
7796
7797         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7798                                rpc_printer_driver_list_internals,
7799                                argc, argv);
7800 }
7801
7802 /**
7803  * Publish printer in ADS via MSRPC.
7804  *
7805  * @param c     A net_context structure.
7806  * @param argc  Standard main() style argc.
7807  * @param argv  Standard main() style argv. Initial components are already
7808  *              stripped.
7809  *
7810  * @return A shell status integer (0 for success).
7811  **/
7812 static int rpc_printer_publish_publish(struct net_context *c, int argc,
7813                                        const char **argv)
7814 {
7815         if (c->display_usage) {
7816                 d_printf(  "%s\n"
7817                            "net rpc printer publish publish\n"
7818                            "     %s\n",
7819                          _("Usage:"),
7820                          _("Publish printer in ADS via MSRPC"));
7821                 return 0;
7822         }
7823
7824         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7825                                rpc_printer_publish_publish_internals,
7826                                argc, argv);
7827 }
7828
7829 /**
7830  * Update printer in ADS via MSRPC.
7831  *
7832  * @param c     A net_context structure.
7833  * @param argc  Standard main() style argc.
7834  * @param argv  Standard main() style argv. Initial components are already
7835  *              stripped.
7836  *
7837  * @return A shell status integer (0 for success).
7838  **/
7839 static int rpc_printer_publish_update(struct net_context *c, int argc, const char **argv)
7840 {
7841         if (c->display_usage) {
7842                 d_printf(  "%s\n"
7843                            "net rpc printer publish update\n"
7844                            "    %s\n",
7845                          _("Usage:"),
7846                          _("Update printer in ADS via MSRPC"));
7847                 return 0;
7848         }
7849
7850         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7851                                rpc_printer_publish_update_internals,
7852                                argc, argv);
7853 }
7854
7855 /**
7856  * UnPublish printer in ADS via MSRPC.
7857  *
7858  * @param c     A net_context structure.
7859  * @param argc  Standard main() style argc.
7860  * @param argv  Standard main() style argv. Initial components are already
7861  *              stripped.
7862  *
7863  * @return A shell status integer (0 for success).
7864  **/
7865 static int rpc_printer_publish_unpublish(struct net_context *c, int argc,
7866                                          const char **argv)
7867 {
7868         if (c->display_usage) {
7869                 d_printf(  "%s\n"
7870                            "net rpc printer publish unpublish\n"
7871                            "    %s\n",
7872                          _("Usage:\n"),
7873                          _("UnPublish printer in ADS via MSRPC"));
7874                 return 0;
7875         }
7876
7877         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7878                                rpc_printer_publish_unpublish_internals,
7879                                argc, argv);
7880 }
7881
7882 /**
7883  * List published printers via MSRPC.
7884  *
7885  * @param c     A net_context structure.
7886  * @param argc  Standard main() style argc.
7887  * @param argv  Standard main() style argv. Initial components are already
7888  *              stripped.
7889  *
7890  * @return A shell status integer (0 for success).
7891  **/
7892 static int rpc_printer_publish_list(struct net_context *c, int argc,
7893                                     const char **argv)
7894 {
7895         if (c->display_usage) {
7896                 d_printf(  "%s\n"
7897                            "net rpc printer publish list\n"
7898                            "    %s\n",
7899                          _("Usage:"),
7900                          _("List published printers via MSRPC"));
7901                 return 0;
7902         }
7903
7904         return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7905                                rpc_printer_publish_list_internals,
7906                                argc, argv);
7907 }
7908
7909
7910 /**
7911  * Publish printer in ADS.
7912  *
7913  * @param c     A net_context structure.
7914  * @param argc  Standard main() style argc.
7915  * @param argv  Standard main() style argv. Initial components are already
7916  *              stripped.
7917  *
7918  * @return A shell status integer (0 for success).
7919  **/
7920 static int rpc_printer_publish(struct net_context *c, int argc,
7921                                const char **argv)
7922 {
7923
7924         struct functable func[] = {
7925                 {
7926                         "publish",
7927                         rpc_printer_publish_publish,
7928                         NET_TRANSPORT_RPC,
7929                         N_("Publish printer in AD"),
7930                         N_("net rpc printer publish publish\n"
7931                            "    Publish printer in AD")
7932                 },
7933                 {
7934                         "update",
7935                         rpc_printer_publish_update,
7936                         NET_TRANSPORT_RPC,
7937                         N_("Update printer in AD"),
7938                         N_("net rpc printer publish update\n"
7939                            "    Update printer in AD")
7940                 },
7941                 {
7942                         "unpublish",
7943                         rpc_printer_publish_unpublish,
7944                         NET_TRANSPORT_RPC,
7945                         N_("Unpublish printer"),
7946                         N_("net rpc printer publish unpublish\n"
7947                            "    Unpublish printer")
7948                 },
7949                 {
7950                         "list",
7951                         rpc_printer_publish_list,
7952                         NET_TRANSPORT_RPC,
7953                         N_("List published printers"),
7954                         N_("net rpc printer publish list\n"
7955                            "    List published printers")
7956                 },
7957                 {NULL, NULL, 0, NULL, NULL}
7958         };
7959
7960         if (argc == 0) {
7961                 if (c->display_usage) {
7962                         d_printf(_("Usage:\n"));
7963                         d_printf(_("net rpc printer publish\n"
7964                                    "    List published printers\n"
7965                                    "    Alias of net rpc printer publish "
7966                                    "list\n"));
7967                         net_display_usage_from_functable(func);
7968                         return 0;
7969                 }
7970                 return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
7971                                rpc_printer_publish_list_internals,
7972                                argc, argv);
7973         }
7974
7975         return net_run_function(c, argc, argv, "net rpc printer publish",func);
7976
7977 }
7978
7979
7980 /**
7981  * Display rpc printer help page.
7982  *
7983  * @param c     A net_context structure.
7984  * @param argc  Standard main() style argc.
7985  * @param argv  Standard main() style argv. Initial components are already
7986  *              stripped.
7987  **/
7988 int rpc_printer_usage(struct net_context *c, int argc, const char **argv)
7989 {
7990         d_printf(_("net rpc printer LIST [printer] [misc. options] [targets]\n"
7991                    "\tlists all printers on print-server\n\n"));
7992         d_printf(_("net rpc printer DRIVER [printer] [misc. options] [targets]\n"
7993                    "\tlists all printer-drivers on print-server\n\n"));
7994         d_printf(_("net rpc printer PUBLISH action [printer] [misc. options] [targets]\n"
7995                    "\tpublishes printer settings in Active Directory\n"
7996                    "\taction can be one of PUBLISH, UPDATE, UNPUBLISH or LIST\n\n"));
7997         d_printf(_("net rpc printer MIGRATE PRINTERS [printer] [misc. options] [targets]"
7998                    "\n\tmigrates printers from remote to local server\n\n"));
7999         d_printf(_("net rpc printer MIGRATE SETTINGS [printer] [misc. options] [targets]"
8000                    "\n\tmigrates printer-settings from remote to local server\n\n"));
8001         d_printf(_("net rpc printer MIGRATE DRIVERS [printer] [misc. options] [targets]"
8002                    "\n\tmigrates printer-drivers from remote to local server\n\n"));
8003         d_printf(_("net rpc printer MIGRATE FORMS [printer] [misc. options] [targets]"
8004                    "\n\tmigrates printer-forms from remote to local server\n\n"));
8005         d_printf(_("net rpc printer MIGRATE SECURITY [printer] [misc. options] [targets]"
8006                    "\n\tmigrates printer-ACLs from remote to local server\n\n"));
8007         d_printf(_("net rpc printer MIGRATE ALL [printer] [misc. options] [targets]"
8008                    "\n\tmigrates drivers, forms, queues, settings and acls from\n"
8009                    "\tremote to local print-server\n\n"));
8010         net_common_methods_usage(c, argc, argv);
8011         net_common_flags_usage(c, argc, argv);
8012         d_printf(_(
8013          "\t-v or --verbose\t\t\tgive verbose output\n"
8014          "\t      --destination\t\tmigration target server (default: localhost)\n"));
8015
8016         return -1;
8017 }
8018
8019 /**
8020  * 'net rpc printer' entrypoint.
8021  *
8022  * @param c     A net_context structure.
8023  * @param argc  Standard main() style argc.
8024  * @param argv  Standard main() style argv. Initial components are already
8025  *              stripped.
8026  **/
8027 int net_rpc_printer(struct net_context *c, int argc, const char **argv)
8028 {
8029         struct functable func[] = {
8030                 {
8031                         "list",
8032                         rpc_printer_list,
8033                         NET_TRANSPORT_RPC,
8034                         N_("List all printers on print server"),
8035                         N_("net rpc printer list\n"
8036                            "    List all printers on print server")
8037                 },
8038                 {
8039                         "migrate",
8040                         rpc_printer_migrate,
8041                         NET_TRANSPORT_RPC,
8042                         N_("Migrate printer to local server"),
8043                         N_("net rpc printer migrate\n"
8044                            "    Migrate printer to local server")
8045                 },
8046                 {
8047                         "driver",
8048                         rpc_printer_driver_list,
8049                         NET_TRANSPORT_RPC,
8050                         N_("List printer drivers"),
8051                         N_("net rpc printer driver\n"
8052                            "    List printer drivers")
8053                 },
8054                 {
8055                         "publish",
8056                         rpc_printer_publish,
8057                         NET_TRANSPORT_RPC,
8058                         N_("Publish printer in AD"),
8059                         N_("net rpc printer publish\n"
8060                            "    Publish printer in AD")
8061                 },
8062                 {NULL, NULL, 0, NULL, NULL}
8063         };
8064
8065         if (argc == 0) {
8066                 if (c->display_usage) {
8067                         d_printf(_("Usage:\n"));
8068                         d_printf(_("net rpc printer\n"
8069                                    "    List printers\n"));
8070                         net_display_usage_from_functable(func);
8071                         return 0;
8072                 }
8073                 return run_rpc_command(c, NULL, &ndr_table_spoolss, 0,
8074                                rpc_printer_list_internals,
8075                                argc, argv);
8076         }
8077
8078         return net_run_function(c, argc, argv, "net rpc printer", func);
8079 }
8080
8081 /**
8082  * 'net rpc' entrypoint.
8083  *
8084  * @param c     A net_context structure.
8085  * @param argc  Standard main() style argc.
8086  * @param argv  Standard main() style argv. Initial components are already
8087  *              stripped.
8088  **/
8089
8090 int net_rpc(struct net_context *c, int argc, const char **argv)
8091 {
8092         NET_API_STATUS status;
8093
8094         struct functable func[] = {
8095                 {
8096                         "audit",
8097                         net_rpc_audit,
8098                         NET_TRANSPORT_RPC,
8099                         N_("Modify global audit settings"),
8100                         N_("net rpc audit\n"
8101                            "    Modify global audit settings")
8102                 },
8103                 {
8104                         "info",
8105                         net_rpc_info,
8106                         NET_TRANSPORT_RPC,
8107                         N_("Show basic info about a domain"),
8108                         N_("net rpc info\n"
8109                            "    Show basic info about a domain")
8110                 },
8111                 {
8112                         "join",
8113                         net_rpc_join,
8114                         NET_TRANSPORT_RPC,
8115                         N_("Join a domain"),
8116                         N_("net rpc join\n"
8117                            "    Join a domain")
8118                 },
8119                 {
8120                         "oldjoin",
8121                         net_rpc_oldjoin,
8122                         NET_TRANSPORT_RPC,
8123                         N_("Join a domain created in server manager"),
8124                         N_("net rpc oldjoin\n"
8125                            "    Join a domain created in server manager")
8126                 },
8127                 {
8128                         "testjoin",
8129                         net_rpc_testjoin,
8130                         NET_TRANSPORT_RPC,
8131                         N_("Test that a join is valid"),
8132                         N_("net rpc testjoin\n"
8133                            "    Test that a join is valid")
8134                 },
8135                 {
8136                         "user",
8137                         net_rpc_user,
8138                         NET_TRANSPORT_RPC,
8139                         N_("List/modify users"),
8140                         N_("net rpc user\n"
8141                            "    List/modify users")
8142                 },
8143                 {
8144                         "password",
8145                         rpc_user_password,
8146                         NET_TRANSPORT_RPC,
8147                         N_("Change a user password"),
8148                         N_("net rpc password\n"
8149                            "    Change a user password\n"
8150                            "    Alias for net rpc user password")
8151                 },
8152                 {
8153                         "group",
8154                         net_rpc_group,
8155                         NET_TRANSPORT_RPC,
8156                         N_("List/modify groups"),
8157                         N_("net rpc group\n"
8158                            "    List/modify groups")
8159                 },
8160                 {
8161                         "share",
8162                         net_rpc_share,
8163                         NET_TRANSPORT_RPC,
8164                         N_("List/modify shares"),
8165                         N_("net rpc share\n"
8166                            "    List/modify shares")
8167                 },
8168                 {
8169                         "file",
8170                         net_rpc_file,
8171                         NET_TRANSPORT_RPC,
8172                         N_("List open files"),
8173                         N_("net rpc file\n"
8174                            "    List open files")
8175                 },
8176                 {
8177                         "printer",
8178                         net_rpc_printer,
8179                         NET_TRANSPORT_RPC,
8180                         N_("List/modify printers"),
8181                         N_("net rpc printer\n"
8182                            "    List/modify printers")
8183                 },
8184                 {
8185                         "changetrustpw",
8186                         net_rpc_changetrustpw,
8187                         NET_TRANSPORT_RPC,
8188                         N_("Change trust account password"),
8189                         N_("net rpc changetrustpw\n"
8190                            "    Change trust account password")
8191                 },
8192                 {
8193                         "trustdom",
8194                         rpc_trustdom,
8195                         NET_TRANSPORT_RPC,
8196                         N_("Modify domain trusts"),
8197                         N_("net rpc trustdom\n"
8198                            "    Modify domain trusts")
8199                 },
8200                 {
8201                         "abortshutdown",
8202                         rpc_shutdown_abort,
8203                         NET_TRANSPORT_RPC,
8204                         N_("Abort a remote shutdown"),
8205                         N_("net rpc abortshutdown\n"
8206                            "    Abort a remote shutdown")
8207                 },
8208                 {
8209                         "shutdown",
8210                         rpc_shutdown,
8211                         NET_TRANSPORT_RPC,
8212                         N_("Shutdown a remote server"),
8213                         N_("net rpc shutdown\n"
8214                            "    Shutdown a remote server")
8215                 },
8216                 {
8217                         "samdump",
8218                         rpc_samdump,
8219                         NET_TRANSPORT_RPC,
8220                         N_("Dump SAM data of remote NT PDC"),
8221                         N_("net rpc samdump\n"
8222                            "    Dump SAM data of remote NT PDC")
8223                 },
8224                 {
8225                         "vampire",
8226                         rpc_vampire,
8227                         NET_TRANSPORT_RPC,
8228                         N_("Sync a remote NT PDC's data into local passdb"),
8229                         N_("net rpc vampire\n"
8230                            "    Sync a remote NT PDC's data into local passdb")
8231                 },
8232                 {
8233                         "getsid",
8234                         net_rpc_getsid,
8235                         NET_TRANSPORT_RPC,
8236                         N_("Fetch the domain sid into local secrets.tdb"),
8237                         N_("net rpc getsid\n"
8238                            "    Fetch the domain sid into local secrets.tdb")
8239                 },
8240                 {
8241                         "rights",
8242                         net_rpc_rights,
8243                         NET_TRANSPORT_RPC,
8244                         N_("Manage privileges assigned to SID"),
8245                         N_("net rpc rights\n"
8246                            "    Manage privileges assigned to SID")
8247                 },
8248                 {
8249                         "service",
8250                         net_rpc_service,
8251                         NET_TRANSPORT_RPC,
8252                         N_("Start/stop/query remote services"),
8253                         N_("net rpc service\n"
8254                            "    Start/stop/query remote services")
8255                 },
8256                 {
8257                         "registry",
8258                         net_rpc_registry,
8259                         NET_TRANSPORT_RPC,
8260                         N_("Manage registry hives"),
8261                         N_("net rpc registry\n"
8262                            "    Manage registry hives")
8263                 },
8264                 {
8265                         "shell",
8266                         net_rpc_shell,
8267                         NET_TRANSPORT_RPC,
8268                         N_("Open interactive shell on remote server"),
8269                         N_("net rpc shell\n"
8270                            "    Open interactive shell on remote server")
8271                 },
8272                 {
8273                         "trust",
8274                         net_rpc_trust,
8275                         NET_TRANSPORT_RPC,
8276                         N_("Manage trusts"),
8277                         N_("net rpc trust\n"
8278                            "    Manage trusts")
8279                 },
8280                 {
8281                         "conf",
8282                         net_rpc_conf,
8283                         NET_TRANSPORT_RPC,
8284                         N_("Configure a remote samba server"),
8285                         N_("net rpc conf\n"
8286                            "    Configure a remote samba server")
8287                 },
8288                 {NULL, NULL, 0, NULL, NULL}
8289         };
8290
8291         status = libnetapi_net_init(&c->netapi_ctx);
8292         if (status != 0) {
8293                 return -1;
8294         }
8295         libnetapi_set_username(c->netapi_ctx, c->opt_user_name);
8296         libnetapi_set_password(c->netapi_ctx, c->opt_password);
8297         if (c->opt_kerberos) {
8298                 libnetapi_set_use_kerberos(c->netapi_ctx);
8299         }
8300         if (c->opt_ccache) {
8301                 libnetapi_set_use_ccache(c->netapi_ctx);
8302         }
8303
8304         return net_run_function(c, argc, argv, "net rpc", func);
8305 }