def check_user(user): ''' Check user and assign process uid/gid. ''' if salt.utils.is_windows(): return True if user == salt.utils.get_user(): return True import pwd # after confirming not running Windows try: pwuser = pwd.getpwnam(user) try: if hasattr(os, 'initgroups'): os.initgroups(user, pwuser.pw_gid) else: os.setgroups(salt.utils.get_gid_list(user, include_default=False)) os.setgid(pwuser.pw_gid) os.setuid(pwuser.pw_uid) except OSError: msg = 'Salt configured to run as user "{0}" but unable to switch.' msg = msg.format(user) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) return False except KeyError: msg = 'User not found: "{0}"'.format(user) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) return False return True
def check_user(user): ''' Check user and assign process uid/gid. ''' if 'os' in os.environ: if os.environ['os'].startswith('Windows'): return True if user == getpass.getuser(): return True import pwd # after confirming not running Windows try: pwuser = pwd.getpwnam(user) try: os.setgid(pwuser.pw_gid) os.setuid(pwuser.pw_uid) except OSError: msg = 'Salt configured to run as user "{0}" but unable to switch.' msg = msg.format(user) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) return False except KeyError: msg = 'User not found: "{0}"'.format(user) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) return False return True
def check_user(user): ''' Check user and assign process uid/gid. ''' if salt.utils.is_windows(): return True if user == getpass.getuser(): return True import pwd # after confirming not running Windows try: pwuser = pwd.getpwnam(user) try: if hasattr(os, 'initgroups'): os.initgroups(user, pwuser.pw_gid) else: os.setgroups(salt.utils.get_gid_list(user, include_default=False)) os.setgid(pwuser.pw_gid) os.setuid(pwuser.pw_uid) except OSError: msg = 'Salt configured to run as user "{0}" but unable to switch.' msg = msg.format(user) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) return False except KeyError: msg = 'User not found: "{0}"'.format(user) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) return False return True
def check_user(user): ''' Check user and assign process uid/gid. ''' if 'os' in os.environ: if os.environ['os'].startswith('Windows'): return True if user == getpass.getuser(): return True import pwd # after confirming not running Windows try: p = pwd.getpwnam(user) try: os.setgid(p.pw_gid) os.setuid(p.pw_uid) except OSError: msg = 'Salt configured to run as user "{0}" but unable to switch.' msg = msg.format(user) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) return False except KeyError: msg = 'User not found: "{0}"'.format(user) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) return False return True
def zmq_version(): """ ZeroMQ python bindings >= 2.1.9 are required """ try: import zmq except Exception: # pylint: disable=broad-except # Return True for local mode return True ver = zmq.__version__ # The last matched group can be None if the version # is something like 3.1 and that will work properly match = re.match(r"^(\d+)\.(\d+)(?:\.(\d+))?", ver) # Fallthrough and hope for the best if not match: msg = "Using untested zmq python bindings version: '{}'".format(ver) if is_console_configured(): log.warning(msg) else: sys.stderr.write("WARNING {}\n".format(msg)) return True major, minor, point = match.groups() if major.isdigit(): major = int(major) if minor.isdigit(): minor = int(minor) # point very well could be None if point and point.isdigit(): point = int(point) if major == 2 and minor == 1: # zmq 2.1dev could be built against a newer libzmq if "dev" in ver and not point: msg = "Using dev zmq module, please report unexpected results" if is_console_configured(): log.warning(msg) else: sys.stderr.write("WARNING: {}\n".format(msg)) return True elif point and point >= 9: return True elif major > 2 or (major == 2 and minor > 1): return True # If all else fails, gracefully croak and warn the user log.critical("ZeroMQ python bindings >= 2.1.9 are required") if "salt-master" in sys.argv[0]: msg = ("The Salt Master is unstable using a ZeroMQ version " "lower than 2.1.11 and requires this fix: http://lists.zeromq." "org/pipermail/zeromq-dev/2011-June/012094.html") if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL {}\n".format(msg)) return False
def zmq_version(): ''' ZeroMQ python bindings >= 2.1.9 are required ''' try: import zmq except Exception: # Return True for local mode return True ver = zmq.__version__ # The last matched group can be None if the version # is something like 3.1 and that will work properly match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', ver) # Fallthrough and hope for the best if not match: msg = "Using untested zmq python bindings version: '{0}'".format(ver) if is_console_configured(): log.warn(msg) else: sys.stderr.write("WARNING {0}\n".format(msg)) return True major, minor, point = match.groups() if major.isdigit(): major = int(major) if minor.isdigit(): minor = int(minor) # point very well could be None if point and point.isdigit(): point = int(point) if major == 2 and minor == 1: # zmq 2.1dev could be built against a newer libzmq if "dev" in ver and not point: msg = 'Using dev zmq module, please report unexpected results' if is_console_configured(): log.warn(msg) else: sys.stderr.write("WARNING: {0}\n".format(msg)) return True elif point and point >= 9: return True elif major > 2 or (major == 2 and minor > 1): return True # If all else fails, gracefully croak and warn the user log.critical('ZeroMQ python bindings >= 2.1.9 are required') if 'salt-master' in sys.argv[0]: msg = ('The Salt Master is unstable using a ZeroMQ version ' 'lower than 2.1.11 and requires this fix: http://lists.zeromq.' 'org/pipermail/zeromq-dev/2011-June/012094.html') if is_console_configured(): log.critical(msg) else: sys.stderr.write('CRITICAL {0}\n'.format(msg)) return False
def check_user(user): """ Check user and assign process uid/gid. """ if salt.utils.platform.is_windows(): return True if user == salt.utils.user.get_user(): return True import pwd # after confirming not running Windows try: pwuser = pwd.getpwnam(user) try: if hasattr(os, "initgroups"): os.initgroups(user, pwuser.pw_gid) # pylint: disable=minimum-python-version else: os.setgroups( salt.utils.user.get_gid_list(user, include_default=False)) os.setgid(pwuser.pw_gid) os.setuid(pwuser.pw_uid) # We could just reset the whole environment but let's just override # the variables we can get from pwuser if "HOME" in os.environ: os.environ["HOME"] = pwuser.pw_dir if "SHELL" in os.environ: os.environ["SHELL"] = pwuser.pw_shell for envvar in ("USER", "LOGNAME"): if envvar in os.environ: os.environ[envvar] = pwuser.pw_name except OSError: msg = 'Salt configured to run as user "{0}" but unable to switch.' msg = msg.format(user) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) return False except KeyError: msg = 'User not found: "{0}"'.format(user) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) return False return True
def verify_socket(interface, pub_port, ret_port): ''' Attempt to bind to the sockets to verify that they are available ''' pubsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) retsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: pubsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) pubsock.bind((interface, int(pub_port))) pubsock.close() retsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) retsock.bind((interface, int(ret_port))) retsock.close() result = True except Exception: msg = ("Unable to bind socket, this might not be a problem." " Is there another salt-master running?") if is_console_configured(): log.warn(msg) else: sys.stderr.write("WARNING: {0}\n".format(msg)) result = False finally: pubsock.close() retsock.close() return result
def verify_socket(interface, pub_port, ret_port): ''' Attempt to bind to the sockets to verify that they are available ''' addr_family = lookup_family(interface) pubsock = socket.socket(addr_family, socket.SOCK_STREAM) retsock = socket.socket(addr_family, socket.SOCK_STREAM) try: pubsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) pubsock.bind((interface, int(pub_port))) pubsock.close() retsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) retsock.bind((interface, int(ret_port))) retsock.close() result = True except Exception as exc: if exc.args: msg = ('Unable to bind socket, error: {0}'.format(str(exc))) else: msg = ('Unable to bind socket, this might not be a problem.' ' Is there another salt-master running?') if is_console_configured(): log.warn(msg) else: sys.stderr.write('WARNING: {0}\n'.format(msg)) result = False finally: pubsock.close() retsock.close() return result
def process(opt): default = self.defaults.get(opt.dest) if getattr(self.options, opt.dest, default) is False: return # XXX: CLEAN THIS CODE WHEN 0.10.8 is about to come out if version.__version_info__ >= (0, 10, 7): self.error( 'The option {0} is deprecated. You must now use ' '\'--out {1}\' instead.'.format( opt.get_opt_string(), opt.dest.split('_', 1)[0] ) ) if opt.dest != 'out': msg = ( 'The option {0} is deprecated. Please consider using ' '\'--out {1}\' instead.'.format( opt.get_opt_string(), opt.dest.split('_', 1)[0] ) ) if log.is_console_configured(): logging.getLogger(__name__).warning(msg) else: sys.stdout.write('WARNING: {0}\n'.format(msg)) self.selected_output_option = opt.dest
def verify_socket(interface, pub_port, ret_port): ''' Attempt to bind to the sockets to verify that they are available ''' addr_family = lookup_family(interface) for port in pub_port, ret_port: sock = socket.socket(addr_family, socket.SOCK_STREAM) try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((interface, int(port))) except Exception as exc: msg = 'Unable to bind socket {0}:{1}'.format(interface, port) if exc.args: msg = '{0}, error: {1}'.format(msg, str(exc)) else: msg = '{0}, this might not be a problem.'.format(msg) msg += '; Is there another salt-master running?' if is_console_configured(): log.warning(msg) else: sys.stderr.write('WARNING: {0}\n'.format(msg)) return False finally: sock.close() return True
def verify_socket(interface, pub_port, ret_port): """ Attempt to bind to the sockets to verify that they are available """ addr_family = lookup_family(interface) for port in pub_port, ret_port: sock = socket.socket(addr_family, socket.SOCK_STREAM) try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((interface, int(port))) except Exception as exc: # pylint: disable=broad-except msg = "Unable to bind socket {}:{}".format(interface, port) if exc.args: msg = "{}, error: {}".format(msg, str(exc)) else: msg = "{}, this might not be a problem.".format(msg) msg += "; Is there another salt-master running?" if is_console_configured(): log.warning(msg) else: sys.stderr.write("WARNING: {}\n".format(msg)) return False finally: sock.close() return True
def check_user(user): ''' Check user and assign process uid/gid. ''' if salt.utils.is_windows(): return True if user == salt.utils.get_user(): return True import pwd # after confirming not running Windows try: pwuser = pwd.getpwnam(user) try: if hasattr(os, 'initgroups'): os.initgroups(user, pwuser.pw_gid) # pylint: disable=minimum-python-version else: os.setgroups(salt.utils.get_gid_list(user, include_default=False)) os.setgid(pwuser.pw_gid) os.setuid(pwuser.pw_uid) # We could just reset the whole environment but let's just override # the variables we can get from pwuser if 'HOME' in os.environ: os.environ['HOME'] = pwuser.pw_dir if 'SHELL' in os.environ: os.environ['SHELL'] = pwuser.pw_shell for envvar in ('USER', 'LOGNAME'): if envvar in os.environ: os.environ[envvar] = pwuser.pw_name except OSError: msg = 'Salt configured to run as user "{0}" but unable to switch.' msg = msg.format(user) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) return False except KeyError: msg = 'User not found: "{0}"'.format(user) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) return False return True
def check_user(user): """ Check user and assign process uid/gid. """ if "os" in os.environ: if os.environ["os"].startswith("Windows"): return True if user == getpass.getuser(): return True import pwd # after confirming not running Windows import grp try: pwuser = pwd.getpwnam(user) try: if hasattr(os, "initgroups"): os.initgroups(user, pwuser.pw_gid) else: os.setgroups([e.gr_gid for e in grp.getgrall() if user in e.gr_mem] + [pwuser.pw_gid]) os.setgid(pwuser.pw_gid) os.setuid(pwuser.pw_uid) except OSError: msg = 'Salt configured to run as user "{0}" but unable to switch.' msg = msg.format(user) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) return False except KeyError: msg = 'User not found: "{0}"'.format(user) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) return False return True
def __get_version_info_from_git(version, version_info): ''' If we can get a version from Git use that instead, otherwise we carry on ''' try: process = subprocess.Popen('which git', stdout=subprocess.PIPE, shell=True) git, _ = process.communicate() if process.poll() != 0: return version, version_info git = git[:-1] process = subprocess.Popen([git, 'describe'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, cwd=os.path.abspath( os.path.dirname(__file__))) out, _ = process.communicate() if not out.strip(): return version, version_info parsed_version = '{0}'.format(out.strip().lstrip('v')) parsed_version_info = tuple( [int(i) for i in parsed_version.split('-', 1)[0].split('.')]) if parsed_version_info != version_info: msg = ('In order to get the proper salt version with the ' 'git hash you need to update salt\'s local git ' 'tags. Something like: \'git fetch --tags\' or ' '\'git fetch --tags upstream\' if you followed ' 'salt\'s contribute documentation. The version ' 'string WILL NOT include the git hash.') from salt import log if log.is_console_configured(): import logging logging.getLogger(__name__).warning(msg) else: sys.stderr.write('WARNING: {0}\n'.format(msg)) return version, version_info return parsed_version, parsed_version_info except OSError, err: if not hasattr(err, 'child_traceback'): # This is not an exception thrown within the Popen created child. # Let's raise it so it can be catch by the developers raise
def _get_pwnam(user): """ Get the user from passwords database """ if salt.utils.platform.is_windows(): return True import pwd # after confirming not running Windows try: return pwd.getpwnam(user) except KeyError: msg = "Failed to prepare the Salt environment for user {}. The user is not available.".format( user) if is_console_configured(): log.critical(msg) else: print(msg, file=sys.stderr, flush=True) sys.exit(salt.defaults.exitcodes.EX_NOUSER)
def process(opt): default = self.defaults.get(opt.dest) if getattr(self.options, opt.dest, default) is False: return if opt.dest not in ('out', 'output_indent', 'no_color'): msg = ( 'The option {0} is deprecated. Please consider using ' '\'--out {1}\' instead.'.format( opt.get_opt_string(), opt.dest.split('_', 1)[0])) if version.__version_info__ >= (0, 12): # XXX: CLEAN THIS CODE WHEN 0.13 is about to come out self.error(msg) elif log.is_console_configured(): logging.getLogger(__name__).warning(msg) else: sys.stdout.write('WARNING: {0}\n'.format(msg)) self.selected_output_option = opt.dest
def __get_version_info_from_git(): ''' If we can get a version from Git use that instead, otherwise we carry on ''' try: from salt.utils import which git = which('git') if git: process = subprocess.Popen( [git, 'describe'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, cwd=os.path.abspath(os.path.dirname(__file__)) ) out, _ = process.communicate() if out: parsed_version = '{0}'.format(out.strip().lstrip('v')) parsed_version_info = tuple([ int(i) for i in parsed_version.split('-', 1)[0].split('.') ]) if parsed_version_info != __version_info__: msg = ('In order to get the proper salt version with the ' 'git hash you need to update salt\'s local git ' 'tags. Something like: \'git fetch --tags\' or ' '\'git fetch --tags upstream\' if you followed ' 'salt\'s contribute documentation. The version ' 'string WILL NOT include the git hash.') from salt import log if log.is_console_configured(): import logging logging.getLogger(__name__).warning(msg) else: sys.stderr.write('WARNING: {0}\n'.format(msg)) else: __version__ = parsed_version __version_info__ = parsed_version_info except Exception: pass
def win_verify_env(dirs, permissive=False, pki_dir='', skip_extra=False): ''' Verify that the named directories are in place and that the environment can shake the salt ''' import salt.utils.win_functions import salt.utils.win_dacl # Get the root path directory where salt is installed path = dirs[0] while os.path.basename(path) not in ['salt', 'salt-tests-tmpdir']: path, base = os.path.split(path) # Create the root path directory if missing if not os.path.isdir(path): os.makedirs(path) # Set permissions to the root path directory current_user = salt.utils.win_functions.get_current_user() if salt.utils.win_functions.is_admin(current_user): try: # Make the Administrators group owner # Use the SID to be locale agnostic salt.utils.win_dacl.set_owner(path, 'S-1-5-32-544') except CommandExecutionError: msg = 'Unable to securely set the owner of "{0}".'.format(path) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) if not permissive: try: # Get a clean dacl by not passing an obj_name dacl = salt.utils.win_dacl.Dacl() # Add aces to the dacl, use the GUID (locale non-specific) # Administrators Group dacl.add_ace('S-1-5-32-544', 'grant', 'full_control', 'this_folder_subfolders_files') # System dacl.add_ace('S-1-5-18', 'grant', 'full_control', 'this_folder_subfolders_files') # Owner dacl.add_ace('S-1-3-4', 'grant', 'full_control', 'this_folder_subfolders_files') # Users Group dacl.add_ace('S-1-5-32-545', 'grant', 'read_execute', 'this_folder_subfolders_files') # Save the dacl to the object dacl.save(path, True) except CommandExecutionError: msg = 'Unable to securely set the permissions of ' \ '"{0}".'.format(path) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) # Create the directories for dir_ in dirs: if not dir_: continue if not os.path.isdir(dir_): try: os.makedirs(dir_) except OSError as err: msg = 'Failed to create directory path "{0}" - {1}\n' sys.stderr.write(msg.format(dir_, err)) sys.exit(err.errno) # The PKI dir gets its own permissions if dir_ == pki_dir: try: # Make Administrators group the owner salt.utils.win_dacl.set_owner(path, 'S-1-5-32-544') # Give Admins, System and Owner permissions # Get a clean dacl by not passing an obj_name dacl = salt.utils.win_dacl.Dacl() # Add aces to the dacl, use the GUID (locale non-specific) # Administrators Group dacl.add_ace('S-1-5-32-544', 'grant', 'full_control', 'this_folder_subfolders_files') # System dacl.add_ace('S-1-5-18', 'grant', 'full_control', 'this_folder_subfolders_files') # Owner dacl.add_ace('S-1-3-4', 'grant', 'full_control', 'this_folder_subfolders_files') # Save the dacl to the object dacl.save(dir_, True) except CommandExecutionError: msg = 'Unable to securely set the permissions of "{0}".' msg = msg.format(dir_) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) if skip_extra is False: # Run the extra verification checks zmq_version()
def win_verify_env(path, dirs, permissive=False, pki_dir="", skip_extra=False): """ Verify that the named directories are in place and that the environment can shake the salt """ import salt.utils.win_functions import salt.utils.win_dacl import salt.utils.path # Make sure the file_roots is not set to something unsafe since permissions # on that directory are reset # `salt.utils.path.safe_path` will consider anything inside `C:\Windows` to # be unsafe. In some instances the test suite uses # `C:\Windows\Temp\salt-tests-tmpdir\rootdir` as the file_roots. So, we need # to consider anything in `C:\Windows\Temp` to be safe system_root = os.environ.get("SystemRoot", r"C:\Windows") allow_path = "\\".join([system_root, "TEMP"]) if not salt.utils.path.safe_path(path=path, allow_path=allow_path): raise CommandExecutionError( "`file_roots` set to a possibly unsafe location: {}".format(path)) # Create the root path directory if missing if not os.path.isdir(path): os.makedirs(path) # Set permissions to the root path directory current_user = salt.utils.win_functions.get_current_user() if salt.utils.win_functions.is_admin(current_user): try: # Make the Administrators group owner # Use the SID to be locale agnostic salt.utils.win_dacl.set_owner(path, "S-1-5-32-544") except CommandExecutionError: msg = 'Unable to securely set the owner of "{}".'.format(path) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {}\n".format(msg)) if not permissive: try: # Get a clean dacl by not passing an obj_name dacl = salt.utils.win_dacl.dacl() # Add aces to the dacl, use the GUID (locale non-specific) # Administrators Group dacl.add_ace( "S-1-5-32-544", "grant", "full_control", "this_folder_subfolders_files", ) # System dacl.add_ace("S-1-5-18", "grant", "full_control", "this_folder_subfolders_files") # Owner dacl.add_ace("S-1-3-4", "grant", "full_control", "this_folder_subfolders_files") # Save the dacl to the object dacl.save(path, True) except CommandExecutionError: msg = "Unable to securely set the permissions of " '"{}".'.format( path) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {}\n".format(msg)) # Create the directories for dir_ in dirs: if not dir_: continue if not os.path.isdir(dir_): try: os.makedirs(dir_) except OSError as err: msg = 'Failed to create directory path "{0}" - {1}\n' sys.stderr.write(msg.format(dir_, err)) sys.exit(err.errno) # The PKI dir gets its own permissions if dir_ == pki_dir: try: # Make Administrators group the owner salt.utils.win_dacl.set_owner(path, "S-1-5-32-544") # Give Admins, System and Owner permissions # Get a clean dacl by not passing an obj_name dacl = salt.utils.win_dacl.dacl() # Add aces to the dacl, use the GUID (locale non-specific) # Administrators Group dacl.add_ace( "S-1-5-32-544", "grant", "full_control", "this_folder_subfolders_files", ) # System dacl.add_ace("S-1-5-18", "grant", "full_control", "this_folder_subfolders_files") # Owner dacl.add_ace("S-1-3-4", "grant", "full_control", "this_folder_subfolders_files") # Save the dacl to the object dacl.save(dir_, True) except CommandExecutionError: msg = 'Unable to securely set the permissions of "{0}".' msg = msg.format(dir_) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {}\n".format(msg)) if skip_extra is False: # Run the extra verification checks zmq_version()
def win_verify_env( path, dirs, permissive=False, pki_dir='', skip_extra=False, sensitive_dirs=None): ''' Verify that the named directories are in place and that the environment can shake the salt ''' if pki_dir: salt.utils.versions.warn_until( 'Neon', 'Use of \'pki_dir\' was detected: \'pki_dir\' has been deprecated ' 'in favor of \'sensitive_dirs\'. Support for \'pki_dir\' will be ' 'removed in Salt Neon.' ) sensitive_dirs = sensitive_dirs or [] sensitive_dirs.append(list(pki_dir)) import salt.utils.win_functions import salt.utils.win_dacl import salt.utils.path # Make sure the file_roots is not set to something unsafe since permissions # on that directory are reset if not salt.utils.path.safe_path(path=path): raise CommandExecutionError( '`file_roots` set to a possibly unsafe location: {0}'.format(path) ) # Create the root path directory if missing if not os.path.isdir(path): os.makedirs(path) # Set permissions to the root path directory current_user = salt.utils.win_functions.get_current_user() if salt.utils.win_functions.is_admin(current_user): try: # Make the Administrators group owner # Use the SID to be locale agnostic salt.utils.win_dacl.set_owner(path, 'S-1-5-32-544') except CommandExecutionError: msg = 'Unable to securely set the owner of "{0}".'.format(path) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) if not permissive: try: # Get a clean dacl by not passing an obj_name dacl = salt.utils.win_dacl.dacl() # Add aces to the dacl, use the GUID (locale non-specific) # Administrators Group dacl.add_ace('S-1-5-32-544', 'grant', 'full_control', 'this_folder_subfolders_files') # System dacl.add_ace('S-1-5-18', 'grant', 'full_control', 'this_folder_subfolders_files') # Owner dacl.add_ace('S-1-3-4', 'grant', 'full_control', 'this_folder_subfolders_files') # Save the dacl to the object dacl.save(path, True) except CommandExecutionError: msg = 'Unable to securely set the permissions of ' \ '"{0}".'.format(path) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) # Create the directories for dir_ in dirs: if not dir_: continue if not os.path.isdir(dir_): try: os.makedirs(dir_) except OSError as err: msg = 'Failed to create directory path "{0}" - {1}\n' sys.stderr.write(msg.format(dir_, err)) sys.exit(err.errno) # The senitive_dirs (i.e. pki_dir, key_dir) gets its own permissions sensitive_dirs = sensitive_dirs or [] if dir_ in sensitive_dirs: try: # Make Administrators group the owner salt.utils.win_dacl.set_owner(path, 'S-1-5-32-544') # Give Admins, System and Owner permissions # Get a clean dacl by not passing an obj_name dacl = salt.utils.win_dacl.dacl() # Add aces to the dacl, use the GUID (locale non-specific) # Administrators Group dacl.add_ace('S-1-5-32-544', 'grant', 'full_control', 'this_folder_subfolders_files') # System dacl.add_ace('S-1-5-18', 'grant', 'full_control', 'this_folder_subfolders_files') # Owner dacl.add_ace('S-1-3-4', 'grant', 'full_control', 'this_folder_subfolders_files') # Save the dacl to the object dacl.save(dir_, True) except CommandExecutionError: msg = 'Unable to securely set the permissions of "{0}".' msg = msg.format(dir_) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) if skip_extra is False: # Run the extra verification checks zmq_version()
def verify_env(dirs, user, permissive=False, pki_dir="", skip_extra=False, root_dir=ROOT_DIR): """ Verify that the named directories are in place and that the environment can shake the salt """ if salt.utils.platform.is_windows(): return win_verify_env(root_dir, dirs, permissive=permissive, skip_extra=skip_extra) # after confirming not running Windows pwnam = _get_pwnam(user) uid = pwnam[2] gid = pwnam[3] groups = salt.utils.user.get_gid_list(user, include_default=False) for dir_ in dirs: if not dir_: continue if not os.path.isdir(dir_): try: with salt.utils.files.set_umask(0o022): os.makedirs(dir_) # If starting the process as root, chown the new dirs if os.getuid() == 0: os.chown(dir_, uid, gid) except OSError as err: msg = 'Failed to create directory path "{0}" - {1}\n' sys.stderr.write(msg.format(dir_, err)) sys.exit(err.errno) mode = os.stat(dir_) # If starting the process as root, chown the new dirs if os.getuid() == 0: fmode = os.stat(dir_) if fmode.st_uid != uid or fmode.st_gid != gid: if permissive and fmode.st_gid in groups: # Allow the directory to be owned by any group root # belongs to if we say it's ok to be permissive pass else: # chown the file for the new user os.chown(dir_, uid, gid) for subdir in [a for a in os.listdir(dir_) if "jobs" not in a]: fsubdir = os.path.join(dir_, subdir) if "{}jobs".format(os.path.sep) in fsubdir: continue for root, dirs, files in salt.utils.path.os_walk(fsubdir): for name in files: if name.startswith("."): continue path = os.path.join(root, name) try: fmode = os.stat(path) except OSError: pass if fmode.st_uid != uid or fmode.st_gid != gid: if permissive and fmode.st_gid in groups: pass else: # chown the file for the new user os.chown(path, uid, gid) for name in dirs: path = os.path.join(root, name) fmode = os.stat(path) if fmode.st_uid != uid or fmode.st_gid != gid: if permissive and fmode.st_gid in groups: pass else: # chown the file for the new user os.chown(path, uid, gid) # Allow the pki dir to be 700 or 750, but nothing else. # This prevents other users from writing out keys, while # allowing the use-case of 3rd-party software (like django) # to read in what it needs to integrate. # # If the permissions aren't correct, default to the more secure 700. # If acls are enabled, the pki_dir needs to remain readable, this # is still secure because the private keys are still only readable # by the user running the master if dir_ == pki_dir: smode = stat.S_IMODE(mode.st_mode) if smode != 448 and smode != 488: if os.access(dir_, os.W_OK): os.chmod(dir_, 448) else: msg = 'Unable to securely set the permissions of "{0}".' msg = msg.format(dir_) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {}\n".format(msg)) if skip_extra is False: # Run the extra verification checks zmq_version()
close_fds=True, cwd=os.path.abspath(os.path.dirname(__file__))) out, err = p.communicate() if out: parsed_version = '{0}'.format(out.strip().lstrip('v')) parsed_version_info = tuple( [int(i) for i in parsed_version.split('-', 1)[0].split('.')]) if parsed_version_info != __version_info__: msg = ('In order to get the proper salt version with the git ' 'hash you need to update salt\'s local git tags. ' 'Something like: \'git fetch --tags\' or ' '\'git fetch --tags upstream\' if you followed ' 'salt\'s contribute documentation. The version string ' 'WILL NOT include the git hash.') from salt import log if log.is_console_configured(): import logging logging.getLogger(__name__).warning(msg) else: sys.stderr.write('WARNING: {0}\n'.format(msg)) else: __version__ = parsed_version __version_info__ = parsed_version_info except Exception: pass def versions_report(): libs = ( ("Jinja2", "jinja2", "__version__"), ("M2Crypto", "M2Crypto", "version"),
) out, err = p.communicate() if out: parsed_version = '{0}'.format(out.strip().lstrip('v')) parsed_version_info = tuple( [int(i) for i in parsed_version.split('-', 1)[0].split('.')] ) if parsed_version_info != __version_info__: msg = ('In order to get the proper salt version with the git ' 'hash you need to update salt\'s local git tags. ' 'Something like: \'git fetch --tags\' or ' '\'git fetch --tags upstream\' if you followed ' 'salt\'s contribute documentation. The version string ' 'WILL NOT include the git hash.') from salt import log if log.is_console_configured(): import logging logging.getLogger(__name__).warning(msg) else: sys.stderr.write('WARNING: {0}\n'.format(msg)) else: __version__ = parsed_version __version_info__ = parsed_version_info except Exception: pass def versions_report(): libs = ( ("Jinja2", "jinja2", "__version__"),
def verify_env(dirs, user, permissive=False, pki_dir='', skip_extra=False, sensitive_dirs=None): ''' Verify that the named directories are in place and that the environment can shake the salt ''' if pki_dir: salt.utils.versions.warn_until( 'Neon', 'Use of \'pki_dir\' was detected: \'pki_dir\' has been deprecated ' 'in favor of \'sensitive_dirs\'. Support for \'pki_dir\' will be ' 'removed in Salt Neon.') sensitive_dirs = sensitive_dirs or [] sensitive_dirs.append(list(pki_dir)) if salt.utils.platform.is_windows(): return win_verify_env(dirs, permissive=permissive, skip_extra=skip_extra, sensitive_dirs=sensitive_dirs) import pwd # after confirming not running Windows try: pwnam = pwd.getpwnam(user) uid = pwnam[2] gid = pwnam[3] groups = salt.utils.user.get_gid_list(user, include_default=False) except KeyError: err = ('Failed to prepare the Salt environment for user ' '{0}. The user is not available.\n').format(user) sys.stderr.write(err) sys.exit(salt.defaults.exitcodes.EX_NOUSER) for dir_ in dirs: if not dir_: continue if not os.path.isdir(dir_): try: cumask = os.umask(18) # 077 os.makedirs(dir_) # If starting the process as root, chown the new dirs if os.getuid() == 0: os.chown(dir_, uid, gid) os.umask(cumask) except OSError as err: msg = 'Failed to create directory path "{0}" - {1}\n' sys.stderr.write(msg.format(dir_, err)) sys.exit(err.errno) mode = os.stat(dir_) # If starting the process as root, chown the new dirs if os.getuid() == 0: fmode = os.stat(dir_) if fmode.st_uid != uid or fmode.st_gid != gid: if permissive and fmode.st_gid in groups: # Allow the directory to be owned by any group root # belongs to if we say it's ok to be permissive pass else: # chown the file for the new user os.chown(dir_, uid, gid) for subdir in [a for a in os.listdir(dir_) if 'jobs' not in a]: fsubdir = os.path.join(dir_, subdir) if '{0}jobs'.format(os.path.sep) in fsubdir: continue for root, dirs, files in os.walk(fsubdir): for name in files: if name.startswith('.'): continue path = os.path.join(root, name) try: fmode = os.stat(path) except (IOError, OSError): pass if fmode.st_uid != uid or fmode.st_gid != gid: if permissive and fmode.st_gid in groups: pass else: # chown the file for the new user os.chown(path, uid, gid) for name in dirs: path = os.path.join(root, name) fmode = os.stat(path) if fmode.st_uid != uid or fmode.st_gid != gid: if permissive and fmode.st_gid in groups: pass else: # chown the file for the new user os.chown(path, uid, gid) # Allow the pki dir to be 700 or 750, but nothing else. # This prevents other users from writing out keys, while # allowing the use-case of 3rd-party software (like django) # to read in what it needs to integrate. # # If the permissions aren't correct, default to the more secure 700. # If acls are enabled, the sensitive_dirs (i.e. pki_dir, key_dir) needs to # remain readable, this is still secure because the private keys are still # only readable by the user running the master sensitive_dirs = sensitive_dirs or [] if dir_ in sensitive_dirs: smode = stat.S_IMODE(mode.st_mode) if smode != 448 and smode != 488: if os.access(dir_, os.W_OK): os.chmod(dir_, 448) else: msg = 'Unable to securely set the permissions of "{0}".' msg = msg.format(dir_) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) if skip_extra is False: # Run the extra verification checks zmq_version()
def verify_env(dirs, user, permissive=False, pki_dir=''): ''' Verify that the named directories are in place and that the environment can shake the salt ''' if 'os' in os.environ: if os.environ['os'].startswith('Windows'): return True import pwd # after confirming not running Windows import grp try: pwnam = pwd.getpwnam(user) uid = pwnam[2] gid = pwnam[3] groups = [g.gr_gid for g in grp.getgrall() if user in g.gr_mem] except KeyError: err = ('Failed to prepare the Salt environment for user ' '{0}. The user is not available.\n').format(user) sys.stderr.write(err) sys.exit(2) for dir_ in dirs: if not dir_: continue if not os.path.isdir(dir_): try: cumask = os.umask(18) # 077 os.makedirs(dir_) # If starting the process as root, chown the new dirs if os.getuid() == 0: os.chown(dir_, uid, gid) os.umask(cumask) except OSError as err: msg = 'Failed to create directory path "{0}" - {1}\n' sys.stderr.write(msg.format(dir_, err)) sys.exit(err.errno) mode = os.stat(dir_) # If starting the process as root, chown the new dirs if os.getuid() == 0: fmode = os.stat(dir_) if not fmode.st_uid == uid or not fmode.st_gid == gid: if permissive and fmode.st_gid in groups: # Allow the directory to be owned by any group root # belongs to if we say it's ok to be permissive pass else: # chown the file for the new user os.chown(dir_, uid, gid) for root, dirs, files in os.walk(dir_): if 'jobs' in root: continue for name in files: if name.startswith('.'): continue path = os.path.join(root, name) try: fmode = os.stat(path) except (IOError, OSError): pass if not fmode.st_uid == uid or not fmode.st_gid == gid: if permissive and fmode.st_gid in groups: pass else: # chown the file for the new user os.chown(path, uid, gid) for name in dirs: path = os.path.join(root, name) fmode = os.stat(path) if not fmode.st_uid == uid or not fmode.st_gid == gid: if permissive and fmode.st_gid in groups: pass else: # chown the file for the new user os.chown(path, uid, gid) # Allow the pki dir to be 700 or 750, but nothing else. # This prevents other users from writing out keys, while # allowing the use-case of 3rd-party software (like django) # to read in what it needs to integrate. # # If the permissions aren't correct, default to the more secure 700. # If acls are enabled, the pki_dir needs to remain readable, this # is still secure because the private keys are still only readbale # by the user running the master if dir_ == pki_dir: smode = stat.S_IMODE(mode.st_mode) if not smode == 448 and not smode == 488: if os.access(dir_, os.W_OK): os.chmod(dir_, 448) else: msg = 'Unable to securely set the permissions of "{0}".' msg = msg.format(dir_) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) # Run the extra verification checks zmq_version()
def win_verify_env(dirs, user, permissive=False, pki_dir='', skip_extra=False): ''' Verify that the named directories are in place and that the environment can shake the salt ''' import salt.utils.win_functions # Get the root path directory where salt is installed path = dirs[0] while os.path.basename(path) not in ['salt', 'salt-tests-tmpdir']: path, base = os.path.split(path) # Create the root path directory if missing if not os.path.isdir(path): os.makedirs(path) # Set permissions to the root path directory current_user = salt.utils.win_functions.get_current_user() if salt.utils.win_functions.is_admin(current_user): try: salt.utils.win_functions.set_path_owner(path) except CommandExecutionError: msg = 'Unable to securely set the owner of "{0}".' msg = msg.format(path) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) if not permissive: try: salt.utils.win_functions.set_path_permissions(path) except CommandExecutionError: msg = 'Unable to securely set the permissions of "{0}".' msg = msg.format(path) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) # Create the directories for dir_ in dirs: if not dir_: continue if not os.path.isdir(dir_): try: os.makedirs(dir_) except OSError as err: msg = 'Failed to create directory path "{0}" - {1}\n' sys.stderr.write(msg.format(dir_, err)) sys.exit(err.errno) if dir_ == pki_dir: try: salt.utils.win_functions.set_path_owner(dir_) salt.utils.win_functions.set_path_permissions(dir_) except CommandExecutionError: msg = 'Unable to securely set the permissions of "{0}".' msg = msg.format(dir_) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) if skip_extra is False: # Run the extra verification checks zmq_version()
def win_verify_env(dirs, permissive=False, pki_dir='', skip_extra=False): ''' Verify that the named directories are in place and that the environment can shake the salt ''' import salt.utils.win_functions import salt.utils.win_dacl # Get the root path directory where salt is installed path = dirs[0] while os.path.basename(path) not in ['salt', 'salt-tests-tmpdir']: path, base = os.path.split(path) # Create the root path directory if missing if not os.path.isdir(path): os.makedirs(path) # Set permissions to the root path directory current_user = salt.utils.win_functions.get_current_user() if salt.utils.win_functions.is_admin(current_user): try: # Make the Administrators group owner # Use the SID to be locale agnostic salt.utils.win_dacl.set_owner(path, 'S-1-5-32-544') except CommandExecutionError: msg = 'Unable to securely set the owner of "{0}".'.format(path) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) if not permissive: try: # Get a clean dacl by not passing an obj_name dacl = salt.utils.win_dacl.dacl() # Add aces to the dacl, use the GUID (locale non-specific) # Administrators Group dacl.add_ace('S-1-5-32-544', 'grant', 'full_control', 'this_folder_subfolders_files') # System dacl.add_ace('S-1-5-18', 'grant', 'full_control', 'this_folder_subfolders_files') # Owner dacl.add_ace('S-1-3-4', 'grant', 'full_control', 'this_folder_subfolders_files') # Save the dacl to the object dacl.save(path, True) except CommandExecutionError: msg = 'Unable to securely set the permissions of ' \ '"{0}".'.format(path) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) # Create the directories for dir_ in dirs: if not dir_: continue if not os.path.isdir(dir_): try: os.makedirs(dir_) except OSError as err: msg = 'Failed to create directory path "{0}" - {1}\n' sys.stderr.write(msg.format(dir_, err)) sys.exit(err.errno) # The PKI dir gets its own permissions if dir_ == pki_dir: try: # Make Administrators group the owner salt.utils.win_dacl.set_owner(path, 'S-1-5-32-544') # Give Admins, System and Owner permissions # Get a clean dacl by not passing an obj_name dacl = salt.utils.win_dacl.dacl() # Add aces to the dacl, use the GUID (locale non-specific) # Administrators Group dacl.add_ace('S-1-5-32-544', 'grant', 'full_control', 'this_folder_subfolders_files') # System dacl.add_ace('S-1-5-18', 'grant', 'full_control', 'this_folder_subfolders_files') # Owner dacl.add_ace('S-1-3-4', 'grant', 'full_control', 'this_folder_subfolders_files') # Save the dacl to the object dacl.save(dir_, True) except CommandExecutionError: msg = 'Unable to securely set the permissions of "{0}".' msg = msg.format(dir_) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) if skip_extra is False: # Run the extra verification checks zmq_version()
def verify_env(dirs, user, permissive=False, pki_dir=''): ''' Verify that the named directories are in place and that the environment can shake the salt ''' if 'os' in os.environ: if os.environ['os'].startswith('Windows'): return True import pwd # after confirming not running Windows import grp try: pwnam = pwd.getpwnam(user) uid = pwnam[2] gid = pwnam[3] groups = [g.gr_gid for g in grp.getgrall() if user in g.gr_mem] except KeyError: err = ('Failed to prepare the Salt environment for user ' '{0}. The user is not available.\n').format(user) sys.stderr.write(err) sys.exit(2) for dir_ in dirs: if not dir_: continue if not os.path.isdir(dir_): try: cumask = os.umask(18) # 077 os.makedirs(dir_) # If starting the process as root, chown the new dirs if os.getuid() == 0: os.chown(dir_, uid, gid) os.umask(cumask) except OSError as e: msg = 'Failed to create directory path "{0}" - {1}\n' sys.stderr.write(msg.format(dir_, e)) sys.exit(e.errno) mode = os.stat(dir_) # If starting the process as root, chown the new dirs if os.getuid() == 0: fmode = os.stat(dir_) if not fmode.st_uid == uid or not fmode.st_gid == gid: if permissive and fmode.st_gid in groups: # Allow the directory to be owned by any group root # belongs to if we say it's ok to be permissive pass else: # chown the file for the new user os.chown(dir_, uid, gid) for root, dirs, files in os.walk(dir_): if 'jobs' in root: continue for name in files: if name.startswith('.'): continue path = os.path.join(root, name) try: fmode = os.stat(path) except (IOError, OSError): pass if not fmode.st_uid == uid or not fmode.st_gid == gid: if permissive and fmode.st_gid in groups: pass else: # chown the file for the new user os.chown(path, uid, gid) for name in dirs: path = os.path.join(root, name) fmode = os.stat(path) if not fmode.st_uid == uid or not fmode.st_gid == gid: if permissive and fmode.st_gid in groups: pass else: # chown the file for the new user os.chown(path, uid, gid) # Allow the pki dir to be 700 or 750, but nothing else. # This prevents other users from writing out keys, while # allowing the use-case of 3rd-party software (like django) # to read in what it needs to integrate. # # If the permissions aren't correct, default to the more secure 700. # If acls are enabled, the pki_dir needs to remain readable, this # is still secure because the private keys are still only readbale # by the user running the master if dir_ == pki_dir: smode = stat.S_IMODE(mode.st_mode) if not smode == 448 and not smode == 488: if os.access(dir_, os.W_OK): os.chmod(dir_, 448) else: msg = 'Unable to securely set the permissions of "{0}".' msg = msg.format(dir_) if is_console_configured(): log.critical(msg) else: sys.stderr.write("CRITICAL: {0}\n".format(msg)) # Run the extra verification checks zmq_version()