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 OptionError
= optparse
.OptionValueError
37 class SambaOptions(optparse
.OptionGroup
):
38 """General Samba-related command line options."""
40 def __init__(self
, parser
):
41 from samba
import fault_setup
43 from samba
.param
import LoadParm
44 optparse
.OptionGroup
.__init
__(self
, parser
, "Samba Common Options")
45 self
.add_option("-s", "--configfile", action
="callback",
46 type=str, metavar
="FILE", help="Configuration file",
47 callback
=self
._load
_configfile
)
48 self
.add_option("-d", "--debuglevel", action
="callback",
49 type=str, metavar
="DEBUGLEVEL", help="debug level",
50 callback
=self
._set
_debuglevel
)
51 self
.add_option("--option", action
="callback",
52 type=str, metavar
="OPTION",
53 help="set smb.conf option from command line",
54 callback
=self
._set
_option
)
55 self
.add_option("--realm", action
="callback",
56 type=str, metavar
="REALM", help="set the realm name",
57 callback
=self
._set
_realm
)
58 self
._configfile
= None
62 def get_loadparm_path(self
):
63 """Return path to the smb.conf file specified on the command line."""
64 return self
._configfile
66 def _load_configfile(self
, option
, opt_str
, arg
, parser
):
67 self
._configfile
= arg
69 def _set_debuglevel(self
, option
, opt_str
, arg
, parser
):
71 self
._lp
.set('debug level', arg
)
73 raise OptionError(f
"invalid -d/--debug value: '{arg}'")
74 parser
.values
.debuglevel
= arg
76 def _set_realm(self
, option
, opt_str
, arg
, parser
):
78 self
._lp
.set('realm', arg
)
80 raise OptionError(f
"invalid --realm value: '{arg}'")
83 def _set_option(self
, option
, opt_str
, arg
, parser
):
84 if arg
.find('=') == -1:
85 raise optparse
.OptionValueError(
86 "--option option takes a 'a=b' argument")
89 self
._lp
.set(a
[0], a
[1])
90 except Exception as e
:
91 raise optparse
.OptionValueError(
92 "invalid --option option value %r: %s" % (arg
, e
))
94 def get_loadparm(self
):
95 """Return loadparm object with data specified on the command line."""
96 if self
._configfile
is not None:
97 self
._lp
.load(self
._configfile
)
98 elif os
.getenv("SMB_CONF_PATH") is not None:
99 self
._lp
.load(os
.getenv("SMB_CONF_PATH"))
101 self
._lp
.load_default()
105 class Samba3Options(SambaOptions
):
106 """General Samba-related command line options with an s3 param."""
108 def __init__(self
, parser
):
109 SambaOptions
.__init
__(self
, parser
)
110 from samba
.samba3
import param
as s3param
111 self
._lp
= s3param
.get_context()
114 class VersionOptions(optparse
.OptionGroup
):
115 """Command line option for printing Samba version."""
116 def __init__(self
, parser
):
117 optparse
.OptionGroup
.__init
__(self
, parser
, "Version Options")
118 self
.add_option("-V", "--version", action
="callback",
119 callback
=self
._display
_version
,
120 help="Display version number")
122 def _display_version(self
, option
, opt_str
, arg
, parser
):
128 def parse_kerberos_arg_legacy(arg
, opt_str
):
129 if arg
.lower() in ["yes", 'true', '1']:
130 return MUST_USE_KERBEROS
131 elif arg
.lower() in ["no", 'false', '0']:
132 return DONT_USE_KERBEROS
133 elif arg
.lower() in ["auto"]:
134 return AUTO_USE_KERBEROS
136 raise optparse
.OptionValueError("invalid %s option value: %s" %
140 def parse_kerberos_arg(arg
, opt_str
):
141 if arg
.lower() == 'required':
142 return MUST_USE_KERBEROS
143 elif arg
.lower() == 'desired':
144 return AUTO_USE_KERBEROS
145 elif arg
.lower() == 'off':
146 return DONT_USE_KERBEROS
148 raise optparse
.OptionValueError("invalid %s option value: %s" %
152 class CredentialsOptions(optparse
.OptionGroup
):
153 """Command line options for specifying credentials."""
155 def __init__(self
, parser
, special_name
=None):
156 self
.special_name
= special_name
157 if special_name
is not None:
158 self
.section
= "Credentials Options (%s)" % special_name
160 self
.section
= "Credentials Options"
162 self
.ask_for_password
= True
163 self
.ipaddress
= None
164 self
.machine_pass
= False
165 optparse
.OptionGroup
.__init
__(self
, parser
, self
.section
)
166 self
._add
_option
("--simple-bind-dn", metavar
="DN", action
="callback",
167 callback
=self
._set
_simple
_bind
_dn
, type=str,
168 help="DN to use for a simple bind")
169 self
._add
_option
("--password", metavar
="PASSWORD", action
="callback",
170 help="Password", type=str, callback
=self
._set
_password
)
171 self
._add
_option
("-U", "--username", metavar
="USERNAME",
172 action
="callback", type=str,
173 help="Username", callback
=self
._parse
_username
)
174 self
._add
_option
("-W", "--workgroup", metavar
="WORKGROUP",
175 action
="callback", type=str,
176 help="Workgroup", callback
=self
._parse
_workgroup
)
177 self
._add
_option
("-N", "--no-pass", action
="callback",
178 help="Don't ask for a password",
179 callback
=self
._set
_no
_password
)
180 self
._add
_option
("", "--ipaddress", metavar
="IPADDRESS",
181 action
="callback", type=str,
182 help="IP address of server",
183 callback
=self
._set
_ipaddress
)
184 self
._add
_option
("-P", "--machine-pass",
186 help="Use stored machine account password",
187 callback
=self
._set
_machine
_pass
)
188 self
._add
_option
("--use-kerberos", metavar
="desired|required|off",
189 action
="callback", type=str,
190 help="Use Kerberos authentication", callback
=self
._set
_kerberos
)
191 self
._add
_option
("--use-krb5-ccache", metavar
="KRB5CCNAME",
192 action
="callback", type=str,
193 help="Kerberos Credentials cache",
194 callback
=self
._set
_krb
5_ccache
)
195 self
._add
_option
("-A", "--authentication-file", metavar
="AUTHFILE",
196 action
="callback", type=str,
197 help="Authentication file",
198 callback
=self
._set
_auth
_file
)
201 self
._add
_option
("-k", "--kerberos", metavar
="KERBEROS",
202 action
="callback", type=str,
203 help="DEPRECATED: Migrate to --use-kerberos", callback
=self
._set
_kerberos
_legacy
)
204 self
.creds
= Credentials()
206 def _ensure_secure_proctitle(self
, opt_str
, secret_data
, data_type
="password"):
207 """ Make sure no sensitive data (e.g. password) resides in proctitle. """
211 except ModuleNotFoundError
:
212 msg
= ("WARNING: Using %s on command line is insecure. "
213 "Please install the setproctitle python module.\n"
215 sys
.stderr
.write(msg
)
218 # Regex to search and replace secret data + option with.
219 # .*[ ]+ -> Before the option must be one or more spaces.
220 # [= ] -> The option and the secret data might be separated by space
222 # [ ]*.* -> After the secret data might be one, many or no space.
223 pass_opt_re_str
= "(.*[ ]+)(%s[= ]%s)([ ]*.*)" % (opt_str
, secret_data
)
224 pass_opt_re
= re
.compile(pass_opt_re_str
)
225 # Get current proctitle.
226 cur_proctitle
= setproctitle
.getproctitle()
227 # Make sure we build the correct regex.
228 if not pass_opt_re
.match(cur_proctitle
):
229 msg
= ("Unable to hide %s in proctitle. This is most likely "
230 "a bug!\n" % data_type
)
231 sys
.stderr
.write(msg
)
234 # String to replace secret data with.
235 secret_data_replacer
= "xxx"
236 # Build string to replace secret data and option with. And as we dont
237 # want to change anything else than the secret data within the proctitle
238 # we have to check if the option was passed with space or equal sign as
240 opt_pass_with_eq
= "%s=%s" % (opt_str
, secret_data
)
241 opt_pass_part
= re
.sub(pass_opt_re_str
, r
'\2', cur_proctitle
)
242 if opt_pass_part
== opt_pass_with_eq
:
243 replace_str
= "%s=%s" % (opt_str
, secret_data_replacer
)
245 replace_str
= "%s %s" % (opt_str
, secret_data_replacer
)
246 # Build new proctitle:
247 new_proctitle
= re
.sub(pass_opt_re_str
,
248 r
'\1' + replace_str
+ r
'\3',
251 setproctitle
.setproctitle(new_proctitle
)
253 def _add_option(self
, *args1
, **kwargs
):
254 if self
.special_name
is None:
255 return self
.add_option(*args1
, **kwargs
)
259 if not a
.startswith("--"):
261 args2
+= (a
.replace("--", "--%s-" % self
.special_name
),)
262 self
.add_option(*args2
, **kwargs
)
264 def _parse_username(self
, option
, opt_str
, arg
, parser
):
265 self
.creds
.parse_string(arg
)
266 self
.machine_pass
= False
268 def _parse_workgroup(self
, option
, opt_str
, arg
, parser
):
269 self
.creds
.set_domain(arg
)
271 def _set_password(self
, option
, opt_str
, arg
, parser
):
272 self
._ensure
_secure
_proctitle
(opt_str
, arg
, "password")
273 self
.creds
.set_password(arg
)
274 self
.ask_for_password
= False
275 self
.machine_pass
= False
277 def _set_no_password(self
, option
, opt_str
, arg
, parser
):
278 self
.ask_for_password
= False
280 def _set_machine_pass(self
, option
, opt_str
, arg
, parser
):
281 self
.machine_pass
= True
283 def _set_ipaddress(self
, option
, opt_str
, arg
, parser
):
286 def _set_kerberos_legacy(self
, option
, opt_str
, arg
, parser
):
287 print('WARNING: The option -k|--kerberos is deprecated!')
288 self
.creds
.set_kerberos_state(parse_kerberos_arg_legacy(arg
, opt_str
))
290 def _set_kerberos(self
, option
, opt_str
, arg
, parser
):
291 self
.creds
.set_kerberos_state(parse_kerberos_arg(arg
, opt_str
))
293 def _set_simple_bind_dn(self
, option
, opt_str
, arg
, parser
):
294 self
.creds
.set_bind_dn(arg
)
296 def _set_krb5_ccache(self
, option
, opt_str
, arg
, parser
):
297 self
.creds
.set_kerberos_state(MUST_USE_KERBEROS
)
298 self
.creds
.set_named_ccache(arg
)
300 def _set_auth_file(self
, option
, opt_str
, arg
, parser
):
301 if os
.path
.exists(arg
):
302 self
.creds
.parse_file(arg
)
303 self
.ask_for_password
= False
304 self
.machine_pass
= False
306 def get_credentials(self
, lp
, fallback_machine
=False):
307 """Obtain the credentials set on the command-line.
309 :param lp: Loadparm object to use.
310 :return: Credentials object
313 if self
.machine_pass
:
314 self
.creds
.set_machine_account(lp
)
315 elif self
.ask_for_password
:
316 self
.creds
.set_cmdline_callbacks()
318 # possibly fallback to using the machine account, if we have
319 # access to the secrets db
320 if fallback_machine
and not self
.creds
.authentication_requested():
322 self
.creds
.set_machine_account(lp
)
329 class CredentialsOptionsDouble(CredentialsOptions
):
330 """Command line options for specifying credentials of two servers."""
332 def __init__(self
, parser
):
333 CredentialsOptions
.__init
__(self
, parser
)
335 self
.add_option("--simple-bind-dn2", metavar
="DN2", action
="callback",
336 callback
=self
._set
_simple
_bind
_dn
2, type=str,
337 help="DN to use for a simple bind")
338 self
.add_option("--password2", metavar
="PASSWORD2", action
="callback",
339 help="Password", type=str,
340 callback
=self
._set
_password
2)
341 self
.add_option("--username2", metavar
="USERNAME2",
342 action
="callback", type=str,
343 help="Username for second server",
344 callback
=self
._parse
_username
2)
345 self
.add_option("--workgroup2", metavar
="WORKGROUP2",
346 action
="callback", type=str,
347 help="Workgroup for second server",
348 callback
=self
._parse
_workgroup
2)
349 self
.add_option("--no-pass2", action
="store_true",
350 help="Don't ask for a password for the second server")
351 self
.add_option("--use-kerberos2", metavar
="desired|required|off",
352 action
="callback", type=str,
353 help="Use Kerberos authentication", callback
=self
._set
_kerberos
2)
356 self
.add_option("--kerberos2", metavar
="KERBEROS2",
357 action
="callback", type=str,
358 help="Use Kerberos", callback
=self
._set
_kerberos
2_legacy
)
359 self
.creds2
= Credentials()
361 def _parse_username2(self
, option
, opt_str
, arg
, parser
):
362 self
.creds2
.parse_string(arg
)
364 def _parse_workgroup2(self
, option
, opt_str
, arg
, parser
):
365 self
.creds2
.set_domain(arg
)
367 def _set_password2(self
, option
, opt_str
, arg
, parser
):
368 self
.creds2
.set_password(arg
)
369 self
.no_pass2
= False
371 def _set_kerberos2_legacy(self
, option
, opt_str
, arg
, parser
):
372 self
.creds2
.set_kerberos_state(parse_kerberos_arg(arg
, opt_str
))
374 def _set_kerberos2(self
, option
, opt_str
, arg
, parser
):
375 self
.creds2
.set_kerberos_state(parse_kerberos_arg(arg
, opt_str
))
377 def _set_simple_bind_dn2(self
, option
, opt_str
, arg
, parser
):
378 self
.creds2
.set_bind_dn(arg
)
380 def get_credentials2(self
, lp
, guess
=True):
381 """Obtain the credentials set on the command-line.
383 :param lp: Loadparm object to use.
384 :param guess: Try guess Credentials from environment
385 :return: Credentials object
388 self
.creds2
.guess(lp
)
389 elif not self
.creds2
.get_username():
390 self
.creds2
.set_anonymous()
393 self
.creds2
.set_cmdline_callbacks()
396 # Custom option type to allow the input of sizes using byte, kb, mb ...
397 # units, e.g. 2Gb, 4KiB ...
398 # e.g. Option("--size", type="bytes", metavar="SIZE")
400 def check_bytes(option
, opt
, value
):
406 "GB" : 1024 * 1024 * 1024}
408 # strip out any spaces
409 v
= value
.replace(" ", "")
411 # extract the numeric prefix
413 while v
and v
[0:1].isdigit() or v
[0:1] == '.':
420 msg
= ("{0} option requires a numeric value, "
421 "with an optional unit suffix").format(opt
)
422 raise optparse
.OptionValueError(msg
)
425 # strip out the 'i' and convert to upper case so
426 # kib Kib kb KB are all equivalent
427 suffix
= v
.upper().replace("I", "")
429 return m
* multipliers
[suffix
]
430 except KeyError as k
:
431 msg
= ("{0} invalid suffix '{1}', "
432 "should be B, Kb, Mb or Gb").format(opt
, v
)
433 raise optparse
.OptionValueError(msg
)
435 class SambaOption(optparse
.Option
):
436 TYPES
= optparse
.Option
.TYPES
+ ("bytes",)
437 TYPE_CHECKER
= copy(optparse
.Option
.TYPE_CHECKER
)
438 TYPE_CHECKER
["bytes"] = check_bytes