dcesrv_core: better fault codes dcesrv_auth_prepare_auth3()
[Samba.git] / python / samba / getopt.py
blob2620138c3de0e7ed6e7565a56225fb8731799690
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"
22 import optparse
23 import os
24 import sys
25 from abc import ABCMeta, abstractmethod
26 from copy import copy
28 from samba.credentials import (
29 Credentials,
30 AUTO_USE_KERBEROS,
31 DONT_USE_KERBEROS,
32 MUST_USE_KERBEROS,
34 from samba._glue import get_burnt_commandline
37 def check_bytes(option, opt, value):
38 """Custom option type to allow the input of sizes using byte, kb, mb ...
40 units, e.g. 2Gb, 4KiB ...
41 e.g. Option("--size", type="bytes", metavar="SIZE")
42 """
44 multipliers = {"B": 1,
45 "KB": 1024,
46 "MB": 1024 * 1024,
47 "GB": 1024 * 1024 * 1024}
49 # strip out any spaces
50 v = value.replace(" ", "")
52 # extract the numeric prefix
53 digits = ""
54 while v and v[0:1].isdigit() or v[0:1] == '.':
55 digits += v[0]
56 v = v[1:]
58 try:
59 m = float(digits)
60 except ValueError:
61 msg = ("{0} option requires a numeric value, "
62 "with an optional unit suffix").format(opt)
63 raise optparse.OptionValueError(msg)
65 # strip out the 'i' and convert to upper case so
66 # kib Kib kb KB are all equivalent
67 suffix = v.upper().replace("I", "")
68 try:
69 return m * multipliers[suffix]
70 except KeyError as k:
71 msg = ("{0} invalid suffix '{1}', "
72 "should be B, Kb, Mb or Gb").format(opt, v)
73 raise optparse.OptionValueError(msg)
76 class OptionMissingError(optparse.OptionValueError):
77 """One or more Options with required=True is missing."""
79 def __init__(self, options):
80 """Raised when required Options are missing from the command line.
82 :param options: list of 1 or more option
83 """
84 self.options = options
86 def __str__(self):
87 if len(self.options) == 1:
88 missing = self.options[0]
89 return f"Argument {missing} is required."
90 else:
91 options = sorted([str(option) for option in self.options])
92 missing = ", ".join(options)
93 return f"The arguments {missing} are required."
96 class ValidationError(Exception):
97 """ValidationError is the exception raised by validators.
99 Should be raised from the __call__ method of the Validator subclass.
101 pass
104 class Validator(metaclass=ABCMeta):
105 """Base class for Validators used by SambaOption.
107 Subclass this to make custom validators and implement __call__.
110 @abstractmethod
111 def __call__(self, field, value):
112 pass
115 class Option(optparse.Option):
116 ATTRS = optparse.Option.ATTRS + ["required", "validators"]
117 TYPES = optparse.Option.TYPES + ("bytes",)
118 TYPE_CHECKER = copy(optparse.Option.TYPE_CHECKER)
119 TYPE_CHECKER["bytes"] = check_bytes
121 def run_validators(self, opt, value):
122 """Runs the list of validators on the current option."""
123 validators = getattr(self, "validators") or []
124 for validator in validators:
125 validator(opt, value)
127 def convert_value(self, opt, value):
128 """Override convert_value to run validators just after.
130 This can also be done in process() but there we would have to
131 replace the entire method.
133 value = super().convert_value(opt, value)
134 self.run_validators(opt, value)
135 return value
138 class OptionParser(optparse.OptionParser):
139 """Samba OptionParser, adding support for required=True on Options."""
141 def __init__(self,
142 usage=None,
143 option_list=None,
144 option_class=Option,
145 version=None,
146 conflict_handler="error",
147 description=None,
148 formatter=None,
149 add_help_option=True,
150 prog=None,
151 epilog=None):
153 Ensure that option_class defaults to the Samba one.
155 super().__init__(usage, option_list, option_class, version,
156 conflict_handler, description, formatter,
157 add_help_option, prog, epilog)
159 def check_values(self, values, args):
160 """Loop through required options if value is missing raise exception."""
161 missing = []
162 for option in self._get_all_options():
163 if option.required:
164 value = getattr(values, option.dest)
165 if value is None:
166 missing.append(option)
168 if missing:
169 raise OptionMissingError(missing)
171 return super().check_values(values, args)
174 class OptionGroup(optparse.OptionGroup):
175 """Samba OptionGroup base class.
177 Provides a generic set_option method to be used as Option callback,
178 so that one doesn't need to be created for every available Option.
180 Also overrides the add_option method, so it correctly initialises
181 the defaults on the OptionGroup.
184 def add_option(self, *args, **kwargs):
185 """Override add_option so it applies defaults during constructor."""
186 opt = super().add_option(*args, **kwargs)
187 default = None if opt.default == optparse.NO_DEFAULT else opt.default
188 self.set_option(opt, opt.get_opt_string(), default, self.parser)
189 return opt
191 def set_option(self, option, opt_str, arg, parser):
192 """Callback to set the attribute based on the Option dest name."""
193 dest = option.dest or option._long_opts[0][2:].replace("-", "_")
194 setattr(self, dest, arg)
197 class SambaOptions(OptionGroup):
198 """General Samba-related command line options."""
200 def __init__(self, parser):
201 from samba import fault_setup
202 fault_setup()
204 # This removes passwords from the commandline via
205 # setproctitle() but makes no change to python sys.argv so we
206 # can continue to process as normal
208 # get_burnt_commandline returns None if no change is needed
209 new_proctitle = get_burnt_commandline(sys.argv)
210 if new_proctitle is not None:
211 try:
212 import setproctitle
213 setproctitle.setproctitle(new_proctitle)
215 except ModuleNotFoundError:
216 msg = ("WARNING: Using passwords on command line is insecure. "
217 "Installing the setproctitle python module will hide "
218 "these from shortly after program start.\n")
219 sys.stderr.write(msg)
220 sys.stderr.flush()
222 from samba.param import LoadParm
223 super().__init__(parser, "Samba Common Options")
224 self.add_option("-s", "--configfile", action="callback",
225 type=str, metavar="FILE", help="Configuration file",
226 callback=self._load_configfile)
227 self.add_option("-d", "--debuglevel", action="callback",
228 type=str, metavar="DEBUGLEVEL", help="debug level",
229 callback=self._set_debuglevel)
230 self.add_option("--option", action="callback",
231 type=str, metavar="OPTION",
232 help="set smb.conf option from command line",
233 callback=self._set_option)
234 self.add_option("--realm", action="callback",
235 type=str, metavar="REALM", help="set the realm name",
236 callback=self._set_realm)
237 self._configfile = None
238 self._lp = LoadParm()
239 self.realm = None
241 def get_loadparm_path(self):
242 """Return path to the smb.conf file specified on the command line."""
243 return self._configfile
245 def _load_configfile(self, option, opt_str, arg, parser):
246 self._configfile = arg
248 def _set_debuglevel(self, option, opt_str, arg, parser):
249 try:
250 self._lp.set('debug level', arg)
251 except RuntimeError:
252 raise optparse.OptionValueError(
253 f"invalid -d/--debug value: '{arg}'")
254 parser.values.debuglevel = arg
256 def _set_realm(self, option, opt_str, arg, parser):
257 try:
258 self._lp.set('realm', arg)
259 except RuntimeError:
260 raise optparse.OptionValueError(
261 f"invalid --realm value: '{arg}'")
262 self.realm = arg
264 def _set_option(self, option, opt_str, arg, parser):
265 if arg.find('=') == -1:
266 raise optparse.OptionValueError(
267 "--option option takes a 'a=b' argument")
268 a = arg.split('=', 1)
269 try:
270 self._lp.set(a[0], a[1])
271 except Exception as e:
272 raise optparse.OptionValueError(
273 "invalid --option option value %r: %s" % (arg, e))
275 def get_loadparm(self):
276 """Return loadparm object with data specified on the command line."""
277 if self._configfile is not None:
278 self._lp.load(self._configfile)
279 elif os.getenv("SMB_CONF_PATH") is not None:
280 self._lp.load(os.getenv("SMB_CONF_PATH"))
281 else:
282 self._lp.load_default()
283 return self._lp
286 class Samba3Options(SambaOptions):
287 """General Samba-related command line options with an s3 param."""
289 def __init__(self, parser):
290 super().__init__(parser)
291 from samba.samba3 import param as s3param
292 self._lp = s3param.get_context()
295 class HostOptions(OptionGroup):
296 """Command line options for connecting to target host or database."""
298 def __init__(self, parser):
299 super().__init__(parser, "Host Options")
301 self.add_option("-H", "--URL",
302 help="LDB URL for database or target server",
303 type=str, metavar="URL", action="callback",
304 callback=self.set_option, dest="H")
307 class VersionOptions(OptionGroup):
308 """Command line option for printing Samba version."""
309 def __init__(self, parser):
310 super().__init__(parser, "Version Options")
311 self.add_option("-V", "--version", action="callback",
312 callback=self._display_version,
313 help="Display version number")
315 def _display_version(self, option, opt_str, arg, parser):
316 import samba
317 print(samba.version)
318 sys.exit(0)
321 def parse_kerberos_arg_legacy(arg, opt_str):
322 if arg.lower() in ["yes", 'true', '1']:
323 return MUST_USE_KERBEROS
324 elif arg.lower() in ["no", 'false', '0']:
325 return DONT_USE_KERBEROS
326 elif arg.lower() in ["auto"]:
327 return AUTO_USE_KERBEROS
328 else:
329 raise optparse.OptionValueError("invalid %s option value: %s" %
330 (opt_str, arg))
333 def parse_kerberos_arg(arg, opt_str):
334 if arg.lower() == 'required':
335 return MUST_USE_KERBEROS
336 elif arg.lower() == 'desired':
337 return AUTO_USE_KERBEROS
338 elif arg.lower() == 'off':
339 return DONT_USE_KERBEROS
340 else:
341 raise optparse.OptionValueError("invalid %s option value: %s" %
342 (opt_str, arg))
345 class CredentialsOptions(OptionGroup):
346 """Command line options for specifying credentials."""
348 def __init__(self, parser, special_name=None):
349 self.special_name = special_name
350 if special_name is not None:
351 self.section = "Credentials Options (%s)" % special_name
352 else:
353 self.section = "Credentials Options"
355 self.ask_for_password = True
356 self.ipaddress = None
357 self.machine_pass = False
358 super().__init__(parser, self.section)
359 self._add_option("--simple-bind-dn", metavar="DN", action="callback",
360 callback=self._set_simple_bind_dn, type=str,
361 help="DN to use for a simple bind")
362 self._add_option("--password", metavar="PASSWORD", action="callback",
363 help="Password", type=str, callback=self._set_password)
364 self._add_option("-U", "--username", metavar="USERNAME",
365 action="callback", type=str,
366 help="Username", callback=self._parse_username)
367 self._add_option("-W", "--workgroup", metavar="WORKGROUP",
368 action="callback", type=str,
369 help="Workgroup", callback=self._parse_workgroup)
370 self._add_option("-N", "--no-pass", action="callback",
371 help="Don't ask for a password",
372 callback=self._set_no_password)
373 self._add_option("", "--ipaddress", metavar="IPADDRESS",
374 action="callback", type=str,
375 help="IP address of server",
376 callback=self._set_ipaddress)
377 self._add_option("-P", "--machine-pass",
378 action="callback",
379 help="Use stored machine account password",
380 callback=self._set_machine_pass)
381 self._add_option("--use-kerberos", metavar="desired|required|off",
382 action="callback", type=str,
383 help="Use Kerberos authentication", callback=self._set_kerberos)
384 self._add_option("--use-krb5-ccache", metavar="KRB5CCNAME",
385 action="callback", type=str,
386 help="Kerberos Credentials cache",
387 callback=self._set_krb5_ccache)
388 self._add_option("-A", "--authentication-file", metavar="AUTHFILE",
389 action="callback", type=str,
390 help="Authentication file",
391 callback=self._set_auth_file)
393 # LEGACY
394 self._add_option("-k", "--kerberos", metavar="KERBEROS",
395 action="callback", type=str,
396 help="DEPRECATED: Migrate to --use-kerberos", callback=self._set_kerberos_legacy)
397 self.creds = Credentials()
399 def _add_option(self, *args1, **kwargs):
400 if self.special_name is None:
401 return self.add_option(*args1, **kwargs)
403 args2 = ()
404 for a in args1:
405 if not a.startswith("--"):
406 continue
407 args2 += (a.replace("--", "--%s-" % self.special_name),)
408 self.add_option(*args2, **kwargs)
410 def _parse_username(self, option, opt_str, arg, parser):
411 self.creds.parse_string(arg)
412 self.machine_pass = False
414 def _parse_workgroup(self, option, opt_str, arg, parser):
415 self.creds.set_domain(arg)
417 def _set_password(self, option, opt_str, arg, parser):
418 self.creds.set_password(arg)
419 self.ask_for_password = False
420 self.machine_pass = False
422 def _set_no_password(self, option, opt_str, arg, parser):
423 self.ask_for_password = False
425 def _set_machine_pass(self, option, opt_str, arg, parser):
426 self.machine_pass = True
428 def _set_ipaddress(self, option, opt_str, arg, parser):
429 self.ipaddress = arg
431 def _set_kerberos_legacy(self, option, opt_str, arg, parser):
432 print('WARNING: The option -k|--kerberos is deprecated!')
433 self.creds.set_kerberos_state(parse_kerberos_arg_legacy(arg, opt_str))
435 def _set_kerberos(self, option, opt_str, arg, parser):
436 self.creds.set_kerberos_state(parse_kerberos_arg(arg, opt_str))
438 def _set_simple_bind_dn(self, option, opt_str, arg, parser):
439 self.creds.set_bind_dn(arg)
441 def _set_krb5_ccache(self, option, opt_str, arg, parser):
442 self.ask_for_password = False
443 self.creds.set_kerberos_state(MUST_USE_KERBEROS)
444 self.creds.set_named_ccache(arg)
446 def _set_auth_file(self, option, opt_str, arg, parser):
447 if os.path.exists(arg):
448 self.creds.parse_file(arg)
449 self.ask_for_password = False
450 self.machine_pass = False
452 def get_credentials(self, lp, fallback_machine=False):
453 """Obtain the credentials set on the command-line.
455 :param lp: Loadparm object to use.
456 :return: Credentials object
458 self.creds.guess(lp)
459 if self.machine_pass:
460 self.creds.set_machine_account(lp)
461 elif self.ask_for_password:
462 self.creds.set_cmdline_callbacks()
464 # possibly fallback to using the machine account, if we have
465 # access to the secrets db
466 if fallback_machine and not self.creds.authentication_requested():
467 try:
468 self.creds.set_machine_account(lp)
469 except Exception:
470 pass
472 return self.creds
475 class CredentialsOptionsDouble(CredentialsOptions):
476 """Command line options for specifying credentials of two servers."""
478 def __init__(self, parser):
479 super().__init__(parser)
480 self.no_pass2 = True
481 self.add_option("--simple-bind-dn2", metavar="DN2", action="callback",
482 callback=self._set_simple_bind_dn2, type=str,
483 help="DN to use for a simple bind")
484 self.add_option("--password2", metavar="PASSWORD2", action="callback",
485 help="Password", type=str,
486 callback=self._set_password2)
487 self.add_option("--username2", metavar="USERNAME2",
488 action="callback", type=str,
489 help="Username for second server",
490 callback=self._parse_username2)
491 self.add_option("--workgroup2", metavar="WORKGROUP2",
492 action="callback", type=str,
493 help="Workgroup for second server",
494 callback=self._parse_workgroup2)
495 self.add_option("--no-pass2", action="store_true",
496 help="Don't ask for a password for the second server")
497 self.add_option("--use-kerberos2", metavar="desired|required|off",
498 action="callback", type=str,
499 help="Use Kerberos authentication", callback=self._set_kerberos2)
501 # LEGACY
502 self.add_option("--kerberos2", metavar="KERBEROS2",
503 action="callback", type=str,
504 help="Use Kerberos", callback=self._set_kerberos2_legacy)
505 self.creds2 = Credentials()
507 def _parse_username2(self, option, opt_str, arg, parser):
508 self.creds2.parse_string(arg)
510 def _parse_workgroup2(self, option, opt_str, arg, parser):
511 self.creds2.set_domain(arg)
513 def _set_password2(self, option, opt_str, arg, parser):
514 self.creds2.set_password(arg)
515 self.no_pass2 = False
517 def _set_kerberos2_legacy(self, option, opt_str, arg, parser):
518 self.creds2.set_kerberos_state(parse_kerberos_arg(arg, opt_str))
520 def _set_kerberos2(self, option, opt_str, arg, parser):
521 self.creds2.set_kerberos_state(parse_kerberos_arg(arg, opt_str))
523 def _set_simple_bind_dn2(self, option, opt_str, arg, parser):
524 self.creds2.set_bind_dn(arg)
526 def get_credentials2(self, lp, guess=True):
527 """Obtain the credentials set on the command-line.
529 :param lp: Loadparm object to use.
530 :param guess: Try guess Credentials from environment
531 :return: Credentials object
533 if guess:
534 self.creds2.guess(lp)
535 elif not self.creds2.get_username():
536 self.creds2.set_anonymous()
538 if self.no_pass2:
539 self.creds2.set_cmdline_callbacks()
540 return self.creds2