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