1 # Samba-specific bits for optparse
2 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 """Support for parsing Samba-related command-line options."""
20 __docformat__ = "restructuredText"
25 from samba.credentials import (
34 class SambaOptions(optparse.OptionGroup):
35 """General Samba-related command line options."""
37 def __init__(self, parser):
38 from samba import fault_setup
40 from samba.param import LoadParm
41 optparse.OptionGroup.__init__(self, parser, "Samba Common Options")
42 self.add_option("-s", "--configfile", action="callback",
43 type=str, metavar="FILE", help="Configuration file",
44 callback=self._load_configfile)
45 self.add_option("-d", "--debuglevel", action="callback",
46 type=str, metavar="DEBUGLEVEL", help="debug level",
47 callback=self._set_debuglevel)
48 self.add_option("--option", action="callback",
49 type=str, metavar="OPTION",
50 help="set smb.conf option from command line",
51 callback=self._set_option)
52 self.add_option("--realm", action="callback",
53 type=str, metavar="REALM", help="set the realm name",
54 callback=self._set_realm)
55 self._configfile = None
59 def get_loadparm_path(self):
60 """Return path to the smb.conf file specified on the command line."""
61 return self._configfile
63 def _load_configfile(self, option, opt_str, arg, parser):
64 self._configfile = arg
66 def _set_debuglevel(self, option, opt_str, arg, parser):
67 self._lp.set('debug level', arg)
68 parser.values.debuglevel = arg
70 def _set_realm(self, option, opt_str, arg, parser):
71 self._lp.set('realm', arg)
74 def _set_option(self, option, opt_str, arg, parser):
75 if arg.find('=') == -1:
76 raise optparse.OptionValueError(
77 "--option option takes a 'a=b' argument")
80 self._lp.set(a[0], a[1])
81 except Exception as e:
82 raise optparse.OptionValueError(
83 "invalid --option option value %r: %s" % (arg, e))
85 def get_loadparm(self):
86 """Return loadparm object with data specified on the command line."""
87 if self._configfile is not None:
88 self._lp.load(self._configfile)
89 elif os.getenv("SMB_CONF_PATH") is not None:
90 self._lp.load(os.getenv("SMB_CONF_PATH"))
92 self._lp.load_default()
96 class Samba3Options(SambaOptions):
97 """General Samba-related command line options with an s3 param."""
99 def __init__(self, parser):
100 SambaOptions.__init__(self, parser)
101 from samba.samba3 import param as s3param
102 self._lp = s3param.get_context()
105 class VersionOptions(optparse.OptionGroup):
106 """Command line option for printing Samba version."""
107 def __init__(self, parser):
108 optparse.OptionGroup.__init__(self, parser, "Version Options")
109 self.add_option("-V", "--version", action="callback",
110 callback=self._display_version,
111 help="Display version number")
113 def _display_version(self, option, opt_str, arg, parser):
119 def parse_kerberos_arg_legacy(arg, opt_str):
120 if arg.lower() in ["yes", 'true', '1']:
121 return MUST_USE_KERBEROS
122 elif arg.lower() in ["no", 'false', '0']:
123 return DONT_USE_KERBEROS
124 elif arg.lower() in ["auto"]:
125 return AUTO_USE_KERBEROS
127 raise optparse.OptionValueError("invalid %s option value: %s" %
131 def parse_kerberos_arg(arg, opt_str):
132 if arg.lower() == 'required':
133 return MUST_USE_KERBEROS
134 elif arg.lower() == 'desired':
135 return AUTO_USE_KERBEROS
136 elif arg.lower() == 'off':
137 return DONT_USE_KERBEROS
139 raise optparse.OptionValueError("invalid %s option value: %s" %
143 class CredentialsOptions(optparse.OptionGroup):
144 """Command line options for specifying credentials."""
146 def __init__(self, parser, special_name=None):
147 self.special_name = special_name
148 if special_name is not None:
149 self.section = "Credentials Options (%s)" % special_name
151 self.section = "Credentials Options"
153 self.ask_for_password = True
154 self.ipaddress = None
155 self.machine_pass = False
156 optparse.OptionGroup.__init__(self, parser, self.section)
157 self._add_option("--simple-bind-dn", metavar="DN", action="callback",
158 callback=self._set_simple_bind_dn, type=str,
159 help="DN to use for a simple bind")
160 self._add_option("--password", metavar="PASSWORD", action="callback",
161 help="Password", type=str, callback=self._set_password)
162 self._add_option("-U", "--username", metavar="USERNAME",
163 action="callback", type=str,
164 help="Username", callback=self._parse_username)
165 self._add_option("-W", "--workgroup", metavar="WORKGROUP",
166 action="callback", type=str,
167 help="Workgroup", callback=self._parse_workgroup)
168 self._add_option("-N", "--no-pass", action="callback",
169 help="Don't ask for a password",
170 callback=self._set_no_password)
171 self._add_option("", "--ipaddress", metavar="IPADDRESS",
172 action="callback", type=str,
173 help="IP address of server",
174 callback=self._set_ipaddress)
175 self._add_option("-P", "--machine-pass",
177 help="Use stored machine account password",
178 callback=self._set_machine_pass)
179 self._add_option("--use-kerberos", metavar="desired|required|off",
180 action="callback", type=str,
181 help="Use Kerberos authentication", callback=self._set_kerberos)
182 self._add_option("--use-krb5-ccache", metavar="KRB5CCNAME",
183 action="callback", type=str,
184 help="Kerberos Credentials cache",
185 callback=self._set_krb5_ccache)
188 self._add_option("-k", "--kerberos", metavar="KERBEROS",
189 action="callback", type=str,
190 help="DEPRECATED: Migrate to --use-kerberos", callback=self._set_kerberos_legacy)
191 self.creds = Credentials()
193 def _ensure_secure_proctitle(self, opt_str, secret_data, data_type="password"):
194 """ Make sure no sensitive data (e.g. password) resides in proctitle. """
198 except ModuleNotFoundError:
199 msg = ("WARNING: Using %s on command line is insecure. "
200 "Please install the setproctitle python module.\n"
202 sys.stderr.write(msg)
205 # Regex to search and replace secret data + option with.
206 # .*[ ]+ -> Before the option must be one or more spaces.
207 # [= ] -> The option and the secret data might be separated by space
209 # [ ]*.* -> After the secret data might be one, many or no space.
210 pass_opt_re_str = "(.*[ ]+)(%s[= ]%s)([ ]*.*)" % (opt_str, secret_data)
211 pass_opt_re = re.compile(pass_opt_re_str)
212 # Get current proctitle.
213 cur_proctitle = setproctitle.getproctitle()
214 # Make sure we build the correct regex.
215 if not pass_opt_re.match(cur_proctitle):
216 msg = ("Unable to hide %s in proctitle. This is most likely "
217 "a bug!\n" % data_type)
218 sys.stderr.write(msg)
221 # String to replace secret data with.
222 secret_data_replacer = "xxx"
223 # Build string to replace secret data and option with. And as we dont
224 # want to change anything else than the secret data within the proctitle
225 # we have to check if the option was passed with space or equal sign as
227 opt_pass_with_eq = "%s=%s" % (opt_str, secret_data)
228 opt_pass_part = re.sub(pass_opt_re_str, r'\2', cur_proctitle)
229 if opt_pass_part == opt_pass_with_eq:
230 replace_str = "%s=%s" % (opt_str, secret_data_replacer)
232 replace_str = "%s %s" % (opt_str, secret_data_replacer)
233 # Build new proctitle:
234 new_proctitle = re.sub(pass_opt_re_str,
235 r'\1' + replace_str + r'\3',
238 setproctitle.setproctitle(new_proctitle)
240 def _add_option(self, *args1, **kwargs):
241 if self.special_name is None:
242 return self.add_option(*args1, **kwargs)
246 if not a.startswith("--"):
248 args2 += (a.replace("--", "--%s-" % self.special_name),)
249 self.add_option(*args2, **kwargs)
251 def _parse_username(self, option, opt_str, arg, parser):
252 self.creds.parse_string(arg)
253 self.machine_pass = False
255 def _parse_workgroup(self, option, opt_str, arg, parser):
256 self.creds.set_domain(arg)
258 def _set_password(self, option, opt_str, arg, parser):
259 self._ensure_secure_proctitle(opt_str, arg, "password")
260 self.creds.set_password(arg)
261 self.ask_for_password = False
262 self.machine_pass = False
264 def _set_no_password(self, option, opt_str, arg, parser):
265 self.ask_for_password = False
267 def _set_machine_pass(self, option, opt_str, arg, parser):
268 self.machine_pass = True
270 def _set_ipaddress(self, option, opt_str, arg, parser):
273 def _set_kerberos_legacy(self, option, opt_str, arg, parser):
274 print('WARNING: The option -k|--kerberos is deprecated!')
275 self.creds.set_kerberos_state(parse_kerberos_arg_legacy(arg, opt_str))
277 def _set_kerberos(self, option, opt_str, arg, parser):
278 self.creds.set_kerberos_state(parse_kerberos_arg(arg, opt_str))
280 def _set_simple_bind_dn(self, option, opt_str, arg, parser):
281 self.creds.set_bind_dn(arg)
283 def _set_krb5_ccache(self, option, opt_str, arg, parser):
284 self.creds.set_kerberos_state(MUST_USE_KERBEROS)
285 self.creds.set_named_ccache(arg)
287 def get_credentials(self, lp, fallback_machine=False):
288 """Obtain the credentials set on the command-line.
290 :param lp: Loadparm object to use.
291 :return: Credentials object
294 if self.machine_pass:
295 self.creds.set_machine_account(lp)
296 elif self.ask_for_password:
297 self.creds.set_cmdline_callbacks()
299 # possibly fallback to using the machine account, if we have
300 # access to the secrets db
301 if fallback_machine and not self.creds.authentication_requested():
303 self.creds.set_machine_account(lp)
310 class CredentialsOptionsDouble(CredentialsOptions):
311 """Command line options for specifying credentials of two servers."""
313 def __init__(self, parser):
314 CredentialsOptions.__init__(self, parser)
316 self.add_option("--simple-bind-dn2", metavar="DN2", action="callback",
317 callback=self._set_simple_bind_dn2, type=str,
318 help="DN to use for a simple bind")
319 self.add_option("--password2", metavar="PASSWORD2", action="callback",
320 help="Password", type=str,
321 callback=self._set_password2)
322 self.add_option("--username2", metavar="USERNAME2",
323 action="callback", type=str,
324 help="Username for second server",
325 callback=self._parse_username2)
326 self.add_option("--workgroup2", metavar="WORKGROUP2",
327 action="callback", type=str,
328 help="Workgroup for second server",
329 callback=self._parse_workgroup2)
330 self.add_option("--no-pass2", action="store_true",
331 help="Don't ask for a password for the second server")
332 self.add_option("--use-kerberos2", metavar="desired|required|off",
333 action="callback", type=str,
334 help="Use Kerberos authentication", callback=self._set_kerberos2)
337 self.add_option("--kerberos2", metavar="KERBEROS2",
338 action="callback", type=str,
339 help="Use Kerberos", callback=self._set_kerberos2_legacy)
340 self.creds2 = Credentials()
342 def _parse_username2(self, option, opt_str, arg, parser):
343 self.creds2.parse_string(arg)
345 def _parse_workgroup2(self, option, opt_str, arg, parser):
346 self.creds2.set_domain(arg)
348 def _set_password2(self, option, opt_str, arg, parser):
349 self.creds2.set_password(arg)
350 self.no_pass2 = False
352 def _set_kerberos2_legacy(self, option, opt_str, arg, parser):
353 self.creds2.set_kerberos_state(parse_kerberos_arg(arg, opt_str))
355 def _set_kerberos2(self, option, opt_str, arg, parser):
356 self.creds2.set_kerberos_state(parse_kerberos_arg(arg, opt_str))
358 def _set_simple_bind_dn2(self, option, opt_str, arg, parser):
359 self.creds2.set_bind_dn(arg)
361 def get_credentials2(self, lp, guess=True):
362 """Obtain the credentials set on the command-line.
364 :param lp: Loadparm object to use.
365 :param guess: Try guess Credentials from environment
366 :return: Credentials object
369 self.creds2.guess(lp)
370 elif not self.creds2.get_username():
371 self.creds2.set_anonymous()
374 self.creds2.set_cmdline_callbacks()
377 # Custom option type to allow the input of sizes using byte, kb, mb ...
378 # units, e.g. 2Gb, 4KiB ...
379 # e.g. Option("--size", type="bytes", metavar="SIZE")
381 def check_bytes(option, opt, value):
387 "GB" : 1024 * 1024 * 1024}
389 # strip out any spaces
390 v = value.replace(" ", "")
392 # extract the numeric prefix
394 while v and v[0:1].isdigit() or v[0:1] == '.':
401 msg = ("{0} option requires a numeric value, "
402 "with an optional unit suffix").format(opt)
403 raise optparse.OptionValueError(msg)
406 # strip out the 'i' and convert to upper case so
407 # kib Kib kb KB are all equivalent
408 suffix = v.upper().replace("I", "")
410 return m * multipliers[suffix]
411 except KeyError as k:
412 msg = ("{0} invalid suffix '{1}', "
413 "should be B, Kb, Mb or Gb").format(opt, v)
414 raise optparse.OptionValueError(msg)
416 class SambaOption(optparse.Option):
417 TYPES = optparse.Option.TYPES + ("bytes",)
418 TYPE_CHECKER = copy(optparse.Option.TYPE_CHECKER)
419 TYPE_CHECKER["bytes"] = check_bytes