Esempio n. 1
1
def authenticate(name, password):
    """
    Returns true or false depending on the success of the name-password combination using
    the shadows or passwd file (The shadow file is preferred if it exists) 
    """
    try:
        success = pam.pam().authenticate(name, password)
        if success is True:
            return success
    except Exception as e:
        logging.warning(e)
        return False
        
    if path.exists("/etc/shadow"):
        
        try:
            if six.PY3:
                shadow = spwd.getspnam(name).sp_pwdp # https://docs.python.org/3.4/library/spwd.html#module-spwd
            else:
                shadow = spwd.getspnam(name).sp_pwd
        except KeyError as e:
            return False
    else:
        shadow = pwd.getpwnam(name).pw_passwd
    
    salt_pattern = compile_regex(r"\$.*\$.*\$")
    
    try:
        salt = salt_pattern.match(shadow).group()
    except AttributeError as a:
        logging.warning(a)
        return False
    return crypt(password, salt) == shadow
Esempio n. 2
0
def get_user():
  for p in pwd.getpwall():
    tmp = {"user":p.pw_name,"uid":p.pw_uid,"group":grp.getgrgid(p.pw_gid).gr_name}
    if spwd.getspnam(p.pw_name).sp_expire == -1:
      tmp["expire"] = "Never"
    else:
      tmp["expire"] = serial_date_to_string(spwd.getspnam(p.pw_name).sp_expire)
    user.append(tmp)
  return user
Esempio n. 3
0
def creds_validator(username, password):

    crypted_root_pwd = spwd.getspnam(username).sp_pwd
    crypted_method, crypted_salt = (crypted_root_pwd.split('$')[1], crypted_root_pwd.split('$')[2])
    result_str = '{0}{1}{0}{2}{0}'.format('$', crypted_method, crypted_salt)

    crypted_input_passwd = crypt.crypt(password, result_str)

    return crypted_input_passwd == spwd.getspnam(username).sp_pwd
Esempio n. 4
0
def shadow_IN_MODIFY(event):
    global shadowfile
    try:
        getspnam(event.name)
    except:
        return
    print "MODIFY : File " + os.path.join(event.path,
                                          event.name) + " is modified."
    fun_update_file(os.path.join(event.path, event.name), shadowfile)
    os.system('service nscd restart')
Esempio n. 5
0
def isuser(username, domain, password=None):
    """Check if user exists and if he is a member of the group 'domain'."""
    try:
        spwd.getspnam(username)
        return username in grp.getgrnam(domain)[3]
    except KeyError:
        return False
    except PermissionError:
        print('No permission to access /etc/shadow')
        exit(999)
    return False
Esempio n. 6
0
def info(name):
    '''
    Return information for the specified user

    CLI Example:

    .. code-block:: bash

        salt '*' shadow.info root
    '''
    try:
        data = spwd.getspnam(name)
        ret = {
            'name': data.sp_nam,
            'passwd': data.sp_pwd,
            'lstchg': data.sp_lstchg,
            'min': data.sp_min,
            'max': data.sp_max,
            'warn': data.sp_warn,
            'inact': data.sp_inact,
            'expire': data.sp_expire}
    except KeyError:
        return {
            'name': '',
            'passwd': '',
            'lstchg': '',
            'min': '',
            'max': '',
            'warn': '',
            'inact': '',
            'expire': ''}
    return ret
Esempio n. 7
0
	def run(self, args):
		if len(args) != 2:
			return

		old_password = args[0]
		new_password = args[1]

		#
		# use the system to change the password
		#
		self._exec('/usr/sbin/chpasswd', input=f'root:{new_password}')

		#
		# get the new crypted password
		#
		shadow_info = spwd.getspnam('root')

		if shadow_info:
			newpw = shadow_info.sp_pwd
			
			#
			# store it in the database
			# 
			self.owner.command('set.attr',
				[ 'attr=Kickstart_PrivateRootPassword', 
				  'value=%s' % newpw ] )
		else:
			print('Could not read the new password for root')
	def login(self, user, passwd, peer):
		if user == "root" and config.OpenWebif.no_root_access.value:
			# Override "no root" for logins from local/private networks
			samenet = False
			networks = getAllNetworks()
			if networks:
				for network in networks:
					if ipaddress.ip_address(unicode(peer)) in ipaddress.ip_network(unicode(network), strict=False):
						samenet=True
			if not (ipaddress.ip_address(unicode(peer)).is_private or samenet):
				return False
		from crypt import crypt
		from pwd import getpwnam
		from spwd import getspnam
		cpass = None
		try:
			cpass = getpwnam(user)[1]
		except:
			return False
		if cpass:
			if cpass == 'x' or cpass == '*':
				try:
					cpass = getspnam(user)[1]
				except:
					return False
			return crypt(passwd, cpass) == cpass
		return False
def getUserAuth(username, passwd):
    try:
        pw = pwd.getpwnam(username)
        if not pw:
            return (None, None, "no such user:%s" % username)

        spw = spwd.getspnam(username)
        lst = spw.sp_pwd
        start_index = lst.find("$")
        finish_index = lst.rfind("$")
        salt = lst[start_index:finish_index + 1]
        pw2 = crypt.crypt(passwd, salt)
        if lst != pw2:
            return (None, None, "password error")

        subp = subprocess.Popen("groups " + username,
                                stdout=subprocess.PIPE,
                                shell=True)
        c = subp.stdout.readlines()

        (user, group) = c[0].split(":")
        if user.strip() != username:
            return (username, None, "no groups")
        groups = ",".join(group.strip().split(" "))
        return (username, groups, "")
    except:
        return (None, None, "not correct user info, auth failed")
Esempio n. 10
0
def main():
    if len(sys.argv) != 2:
        exit(1)
    cryptedpasswd = spwd.getspnam("root")[1]
    if not compare_digest(crypt.crypt(sys.argv[1], cryptedpasswd),
                          cryptedpasswd):
        exit(1)
Esempio n. 11
0
	def login(self, user, passwd, peer):
		if user == "root" and config.OpenWebif.no_root_access.value:
			# Override "no root" for logins from local/private networks
			samenet = False
			networks = getAllNetworks()
			if networks:
				for network in networks:
					if ipaddress.ip_address(unicode(peer)) in ipaddress.ip_network(unicode(network), strict=False):
						samenet=True
			if not (ipaddress.ip_address(unicode(peer)).is_private or samenet):
				return False
		from crypt import crypt
		from pwd import getpwnam
		from spwd import getspnam
		cpass = None
		try:
			cpass = getpwnam(user)[1]
		except:
			return False
		if cpass:
			if cpass == 'x' or cpass == '*':
				try:
					cpass = getspnam(user)[1]
				except:
					return False
			return crypt(passwd, cpass) == cpass
		return False
Esempio n. 12
0
    def run(self, args):
        if len(args) != 2:
            return

        old_password = args[0]
        new_password = args[1]

        #
        # use the system to change the password
        #
        self._exec('/usr/sbin/chpasswd', input=f'root:{new_password}')

        #
        # get the new crypted password
        #
        shadow_info = spwd.getspnam('root')

        if shadow_info:
            newpw = shadow_info.sp_pwd

            #
            # store it in the database
            #
            self.owner.command(
                'set.attr',
                ['attr=Kickstart_PrivateRootPassword',
                 'value=%s' % newpw])
        else:
            print('Could not read the new password for root')
def check_pw(user, password):
    """Check the password matches local unix password on file"""
    try:
        hashed_pw = spwd.getspnam(user)[1]
    except:
        return False
    return crypt.crypt(password, hashed_pw) == hashed_pw
Esempio n. 14
0
def auth_admin(username, password):
    cryptedpasswd = spwd.getspnam(username)[1]

    if crypt.crypt(password, cryptedpasswd) == cryptedpasswd:
        return True
    else:
        return False
Esempio n. 15
0
	def run(self, args):
		if len(args) != 2:
			return

		old_password = args[0]
		new_password = args[1]

		#
		# use the system to change the password
		#
		p = subprocess.Popen(['/usr/sbin/chpasswd'],
			stdin  = subprocess.PIPE,
			stdout = subprocess.PIPE,
			stderr = subprocess.PIPE)
		o, e = p.communicate('root:%s' % new_password)

		#
		# get the new crypted password
		#
		shadow_info = spwd.getspnam('root')

		if shadow_info:
			newpw = shadow_info.sp_pwd
			
			#
			# store it in the database
			# 
			self.owner.command('set.attr',
				[ 'attr=Kickstart_PrivateRootPassword', 
				  'value=%s' % newpw ] )
		else:
			print('Could not read the new password for root')
Esempio n. 16
0
def login(prompt):

    ret = 0, "", ""
    username = raw_input(prompt)
    #print "Authenticating user: '******'"
    
    try:
        cryptedpasswd = pwd.getpwnam(username)
    except:
        #print "No such user: '******'" 
        ret = False,  username, "No user entry"
        return ret
        
    #print "user", cryptedpasswd[1]
    
    cleartext = getpass.getpass()
    try:
        if cryptedpasswd[1] == 'x' or cryptedpasswd[1] == '*':
            cryptedpasswd = spwd.getspnam(username)
        flag = crypt.crypt(cleartext, cryptedpasswd[1]) == cryptedpasswd[1]
        if flag:
            ret = flag, username, ""
        else:
            ret = flag, username, "Invalid password"
    except:
        #print "Cannot access shadow file", sys.exc_info()
        ret = False, username, "Cannot access shadow file"
        
    return ret
Esempio n. 17
0
    def test_create_user(self):
        users_model = UsersModel()
        user_model = UserModel()

        user = '******'
        passwd = 'fakepass'
        group = 'unit_test_fake_group'
        profile = 'unit_test_fake_profile'

        common_users = users_model.get_list()
        params = {'name': user, 'password': passwd,
                  'group': group, 'profile': profile}
        with RollbackContext() as rollback:

            users_model.create(params)
            rollback.prependDefer(user_model.delete, user)

            new_users = users_model.get_list()
            self.assertEqual(len(new_users), len(common_users) + 1)

            enc_passwd = spwd.getspnam(user)[1]
            invalid_passwd = [None, "NP", "!", "!!",  "", "LK", "*"]
            self.assertNotIn(enc_passwd, invalid_passwd)

            self.assertEqual(crypt.crypt(passwd, enc_passwd), enc_passwd)
Esempio n. 18
0
    def get_user_info(self):
        fields = ("name", "passwd", "uid", "gid", "gecos", "dir", "shell")

        try:
            info_tuple = pwd.getpwnam(self.resource.name)
        except KeyError:
            info = dict((f, None) for f in fields)
            info["exists"] = False
            info['disabled-login'] = False
            info['disabled-password'] = False
            return info

        info = {
            "exists": True,
            "disabled-login": False,
            "disabled-password": False,
        }
        for i, field in enumerate(fields):
            info[field] = info_tuple[i]

        try:
            shadow = spwd.getspnam(self.resource.name)
            info['passwd'] = shadow.sp_pwd
            if shadow.sp_pwd == "!":
                info['disabled-login'] = True
        except KeyError:
            info['passwd'] = ''
            info['disabled-login'] = False

        return info
Esempio n. 19
0
def add_users():
    entries = pwd.getpwall()
    for e in entries:
        if not valid_user(e):
            continue
            #raise SystemExit("Not valid_user, exiting")

        (firstname, lastname, building, office, home, other) = extract_gecos(e)

        uid = e.pw_uid + UID_OFFSET
        gid = e.pw_gid + UID_OFFSET
        shadow = spwd.getspnam(e.pw_name)
        crypt = "{crypt}%s" % shadow.sp_pwd

        args = [
            '/usr/bin/ipa', 'user-add', '--first', firstname, '--last',
            lastname, '--homedir', e.pw_dir, '--shell', e.pw_shell,
            '--setattr',
            'userpassword=%s' % crypt, '--setattr',
            'uidnumber=%d' % uid, '--setattr',
            'gidnumber=%d' % gid, e.pw_name
        ]

        print(" ".join(args))

        (stdout, stderr, rc) = run(args, raiseonerr=False)
        #(stdout, stderr, rc) = [0,0,0]
        if rc != 0:
            print 'Adding user "%s" failed: %s' % (e.pw_name, stderr)
        else:
            print 'Successfully added user "%s"' % e.pw_name
Esempio n. 20
0
def UserAdd_Shadow(User, Passwodr='*', ExpireDays=-1, ShadowFile='/etc/shadow'):
	# 1. temporary shadow file
	fd, TempShadowFile = mkstemp(prefix='shadow', dir='/tmp')

	# 2. get users passwd entries
	pwall = pwd.getpwall()
	pwall.sort(lambda a, b: cmp(a.pw_uid, b.pw_uid))

	# 3. generate shadow entries
	CreatedDays = int(time() / 86400)
	if ExpireDays != -1:
		ExpireDays = CreatedDays + ExpireDays

	spall = []
	for pw in pwall:
		try:
			sp = spwd.getspnam(pw.pw_name)
		except KeyError, e:
			sp = spwd.struct_spwd(
				sequence = (
					User,
					'*',
					CreatedDays,
					0,
					99999,
					7,
					-1,
					ExpireDays,
					-1))
		spall.append(sp)
Esempio n. 21
0
 def _getCryptedPassword(self, username):
     try:
         import spwd
     except ImportError:
         return self._manualGetCryptedPassword(username)
     else:
         return spwd.getspnam(username)[1]
Esempio n. 22
0
def check_password(user, pw):
    if not is_user(user):
        return False
    userfields = spwd.getspnam(user)
    _, alg, salt, hash = userfields.sp_pwdp.split('$')
    calculated_shadow_line = crypt.crypt(pw, f"${alg}${salt}$")
    return calculated_shadow_line == userfields.sp_pwdp
Esempio n. 23
0
	def run(self, args):
		if len(args) != 2:
			return

		old_password = args[0]
		new_password = args[1]

		#
		# use the system to change the password
		#
		p = subprocess.Popen(['/usr/sbin/chpasswd'],
			stdin  = subprocess.PIPE,
			stdout = subprocess.PIPE,
			stderr = subprocess.PIPE)
		o, e = p.communicate('root:%s' % new_password)

		#
		# get the new crypted password
		#
		shadow_info = spwd.getspnam('root')

		if shadow_info:
			newpw = shadow_info.sp_pwd
			
			#
			# store it in the database
			# 
			self.owner.command('set.attr',
				[ 'attr=Kickstart_PrivateRootPassword', 
				  'value=%s' % newpw ] )
		else:
			print('Could not read the new password for root')
Esempio n. 24
0
 def _getCryptedPassword(self, username):
    try:
       import spwd
    except ImportError:
       return self._manualGetCryptedPassword(username)
    else:
       return spwd.getspnam(username)[1]
Esempio n. 25
0
def change(username, old_password, new_password):

        test_old_password = check(username, old_password)

        if test_old_password == 'old_password_correct':
            import subprocess

            password_org_fulllist = spwd.getspnam(username)[1].split('$')
            try:
                password_org_hash = password_org_fulllist[1]
            except IndexError:
                return 'user_disabled'

            password_new_enq = crypt.crypt(new_password, '$' + password_org_hash + '$' + crypt.mksalt().split('$')[2][:8])

            cmd = 'usermod -p ' + '\'' + password_new_enq + '\'' + ' ' + username
            return_code = subprocess.call(cmd, shell=True)

            if return_code == 0:
                #print('pass_change_success')
                return 'pass_change_success'
            else:
                #print('pass_change_error')
                return 'pass_change_error'
        elif test_old_password == 'old_password_incorrect':
            return 'old_password_incorrect'
        else:
            return 'unknown_username'
Esempio n. 26
0
    def test_create_user(self):
        users_model = UsersModel()
        user_model = UserModel()

        user = '******'
        passwd = 'fakepass'
        group = 'unit_test_fake_group'
        profile = 'unit_test_fake_profile'

        common_users = users_model.get_list()
        params = {'name': user, 'password': passwd,
                  'group': group, 'profile': profile}
        with RollbackContext() as rollback:

            users_model.create(params)
            rollback.prependDefer(user_model.delete, user)

            new_users = users_model.get_list()
            self.assertEqual(len(new_users), len(common_users) + 1)

            enc_passwd = spwd.getspnam(user)[1]
            invalid_passwd = [None, "NP", "!", "!!",  "", "LK", "*"]
            self.assertNotIn(enc_passwd, invalid_passwd)

            self.assertEqual(crypt.crypt(passwd, enc_passwd), enc_passwd)
Esempio n. 27
0
 def isLocked(self):
     passwd = pwd.getpwnam(self.__user_name).pw_passwd
     if len(passwd) > 0:
         passwd = (passwd if passwd != "x" else spwd.getspnam(
             self.__user_name).sp_pwd)
         return (len(passwd) > 0 and passwd[0] == "!")
     return False
Esempio n. 28
0
	def load_admin_system_user(self):
		template = self.tpl_env.get_template('admin-users')
		environment_vars = self.core.get_variable_list(['LDAP_BASE_DN','SAMBASID'])["return"]
		users_adm = grp.getgrnam('adm').gr_mem
		max_uid = 0
		for x in users_adm:
			user = pwd.getpwnam(x)
			environment_vars['USERNAME'] = user.pw_name
			environment_vars['USERNAME_UID'] = user.pw_uid
			if int(user.pw_uid) > max_uid:
				max_uid = int(user.pw_uid)
			environment_vars['USERHOME'] = user.pw_dir
			environment_vars['USERPASSWORD'] = "******" + spwd.getspnam(user.pw_name).sp_pwd
			environment_vars['SAMBASIDUSER'] = str(environment_vars['SAMBASID']) + "-" + str(environment_vars['USERNAME_UID'])
			string_template = template.render(environment_vars)
			aux_dic = ast.literal_eval(string_template)
			
			slapdp=self.core.get_plugin("SlapdManager")
			if slapdp==None:
				#return {'status':False,'msg':'This function depend on SlapdManager, but this is not installed or not working'}
				return n4d.responses.build_failed_call_response(SLAPD_ERROR)
			aux_dic=slapdp.str_to_bytes(aux_dic)
			result = slapd.insert_dictionary(aux_dic,i_existing=True)
			if not result['status']:
				return n4d.responses.build_failed_call_response(LOAD_ADMIN_SYSTEM_USER_ERROR)
				#return result
			aux_dn = aux_dic.keys()[0]
			result = self.insert_to_admin_profile(aux_dn,aux_dic[aux_dn]['uid'])
			if not result['status']:
				return n4d.responses.build_failed_call_response(INSERT_ADMIN_PROFILE_ERROR)
		result = self.update_xid_counter("ou=Admins,ou=People,"+environment_vars['LDAP_BASE_DN'],max_uid)
		if result[0]:
			return n4d.responses.build_successful_call_response(ret_msg="Admin user loaded")
		else:
			return n4d.responses.build_failed_call_response(UPDATE_XID_COUNTER_ERROR)
Esempio n. 29
0
def info(name):
    '''
    Return information for the specified user

    CLI Example:

    .. code-block:: bash

        salt '*' shadow.info root
    '''
    try:
        data = spwd.getspnam(name)
        ret = {
            'name': data.sp_nam,
            'passwd': data.sp_pwd,
            'lstchg': data.sp_lstchg,
            'min': data.sp_min,
            'max': data.sp_max,
            'warn': data.sp_warn,
            'inact': data.sp_inact,
            'expire': data.sp_expire}
    except KeyError:
        return {
            'name': '',
            'passwd': '',
            'lstchg': '',
            'min': '',
            'max': '',
            'warn': '',
            'inact': '',
            'expire': ''}
    return ret
Esempio n. 30
0
	def convertFromUnixPasswd(self):
		days_from_epoch_time = time.time() / 86400
		for user in pwd.getpwall():
			username = user.pw_name
			password = user.pw_passwd
			uid = user.pw_uid
			gid = user.pw_gid
			home_dir = user.pw_dir
			status = 1
			expiration_date = 0
			if not self.isUserValid(username, uid):
				continue
			if self.force_uid >= 0:
				uid = self.force_uid
			if self.force_gid >= 0:
				gid = self.force_gid
			# FIXME: if the passwords aren't in /etc/shadow they are probably DES encrypted and we don't support them
			if password == 'x' or password == '*':
				user_info = spwd.getspnam(username)
				password = user_info.sp_pwdp
				if not password or password == '!!':
					print('cannot import user "{}" without a password'.format(username))
					continue
				if user_info.sp_inact > 0:
					last_pwd_change_diff = days_from_epoch_time - user_info.sp_lstchg
					if last_pwd_change_diff > user_info.sp_inact:
						status = 0
				if user_info.sp_expire > 0:
					expiration_date = user_info.sp_expire * 86400
			permissions = self.SFTPGoRestAPI.buildPermissions(['*'], [])
			self.addUser(self.SFTPGoRestAPI.buildUserObject(0, username, password, [], home_dir, uid, gid, 0, 0, 0,
														permissions, 0, 0, status, expiration_date))
Esempio n. 31
0
def check_pw(user, password):
 """Check the password matches local unix password on file"""
 try:
  hashed_pw = spwd.getspnam(user)[1]
 except:
  return False
 return crypt.crypt(password, hashed_pw) == hashed_pw
Esempio n. 32
0
    def get_user_info(self):
        fields = ("name", "passwd", "uid", "gid", "gecos", "dir", "shell")

        try:
            info_tuple = pwd.getpwnam(self.resource.name)
        except KeyError:
            info = dict((f, None) for f in fields)
            info["exists"] = False
            info['disabled-login'] = False
            info['disabled-password'] = False
            return info

        info = {"exists": True,
                "disabled-login": False,
                "disabled-password": False,
                }
        for i, field in enumerate(fields):
            info[field] = info_tuple[i]

        try:
            shadow = spwd.getspnam(self.resource.name)
            info['passwd'] = shadow.sp_pwd
            if shadow.sp_pwd == "!":
                info['disabled-login'] = True
        except KeyError:
            info['passwd'] = ''
            info['disabled-login'] = False

        return info
Esempio n. 33
0
def add_user(e, args):
    #raise SystemExit("Not user_valid, exiting")
    (firstname, lastname, building, office, home, other) = extract_gecos(e)

    uid = e.pw_uid + args.uidoffset
    gid = e.pw_gid + args.uidoffset
    shadow = spwd.getspnam(e.pw_name)
    crypt = "{crypt}%s" % shadow.sp_pwd

    args = [
        '/usr/bin/ipa', 'user-add', '--first', firstname, '--last', lastname,
        '--homedir', e.pw_dir, '--shell', e.pw_shell, '--setattr',
        'userpassword=%s' % crypt, '--setattr',
        'uidnumber=%d' % uid, '--setattr',
        'gidnumber=%d' % gid, e.pw_name
    ]

    command = " ".join(args)
    logging.debug(command)

    (stdout, stderr, rc) = run(args,
                               raiseonerr=RAISE_ON_ERR,
                               capture_output=True,
                               capture_error=True)
    if rc != 0:
        logging.warning(
            'Adding user "{0}" failed, return code={1}:\n{2}\n{3}\n{4}'.format(
                e.pw_name, rc, command, stdout, stderr))
    else:
        logging.info('Successfully added user "%s"' % e.pw_name)
    users_seen.add(e.pw_name)
Esempio n. 34
0
def check_pw(user, password):
    """Check the password matches local unix password on file"""
    if ((user == 'root') or (user == 'rootuser')):
        hashed_pw = spwd.getspnam(user)[1]
        return crypt.crypt(password, hashed_pw) == hashed_pw
    else:
        return False
Esempio n. 35
0
    def loginStatus(self):
        try:
            passwdStatus = pS.PASSWORDSTATUS(self.user, 'ALL')
            pStatus = passwdStatus.check()

            # Here we get all the password status in the form of arrya in 'pStatus'
            #(LP, PE, PI, AE, MNDBSC, MNDBPC, NOWBPE)

        except Exception as k:
            print(k)

        try:
            enc_pwd = spwd.getspnam(self.user)[1]

            if pStatus[1] != ' never' or pStatus[2] != ' never':
                return "Password Expired or Inactive. Please contact System Admin."

            elif enc_pwd in ["NP", "!", "", None]:
                return "User '%s' has no password set. Please contact System Admin" % self.user

            elif enc_pwd[0:1] in ["LK", "*", "L", '!']:
                return "User account is locked. Please Contact System Admin"

            elif crypt.crypt(self.pasword, enc_pwd) == enc_pwd:
                return True
            else:
                return "Incorrect password"
        except KeyError:
            return "User '%s' not found" % self.user
        return "Unknown Error, Contact Developer !"
Esempio n. 36
0
    def update_user(self, user, password):
        # get the username
        username = user['username']

        # check if the user exists, if not return silently
        try:
            system_user = pwd.getpwnam(username)
            system_password = spwd.getspnam(username)
        except KeyError:
            return

        # enable the user if he or she was disabled
        if (system_password.sp_pwd.startswith('!')):
            print 'unlocking user', username
            self.call("usermod -U %s" % username)

            # fetch proper password
            system_password = spwd.getspnam(username)

        # a flag if uid or gid have changed
        uid_gid_changed = False

        # check full name
        fullname = self.get_full_name(user)

        if (fullname != system_user.pw_gecos.decode('utf-8')):
            print 'updating fullname (i.e. comment) for', username
            self.call(u'usermod -c \'%s\' %s' % (fullname, username))

        # check uid
        if (int(user['details']['UID']) != system_user.pw_uid):
            print 'updating uid for', username
            self.call("usermod -u '%s' %s" % (user['details']['UID'], username))
            uid_gid_changed = True

        # check gid
        if (int(user['details']['GID']) != system_user.pw_gid):
            print 'updating gid for', username
            self.call("usermod -g '%s' %s" % (user['details']['GID'], username))
            uid_gid_changed = True

        # check password
        if (password != system_password.sp_pwd):
            print 'updating password for', username
            self.call("usermod -p '%s' %s" % (password, username))

        return uid_gid_changed
Esempio n. 37
0
def check_pass():
    username = input("Enter The Username: ")
    password = spwd.getspnam(username).sp_pwdp
    if password:
        clr_text = getpass.getpass()
        return crypt.crypt(clr_text, password) == password
    else:
        return 1
Esempio n. 38
0
def dump(path, user_names=user_names()):
    users = []
    for user_name in user_names:
        password = spwd.getspnam(user_name).sp_pwd
        groups = _groups_for_user(user_name)
        users.append({'name': user_name, 'groups': groups, 'password': password})
    with open(path, 'w') as f:
        json.dump(users, f)
Esempio n. 39
0
 def authenticate(self, username = None, password = None):
     try:
         shadow = spwd.getspnam(username)[1].split("$")
         salt = "$".join(shadow[:-1])
         thehash = shadow[-1]
         return crypt.crypt(password, salt) == "$".join(shadow)
     except KeyError:
         return False
Esempio n. 40
0
File: users.py Progetto: OSPG/sv2
 def check_expiration(self):
     if os.geteuid() != 0:
         report.wont_run("Needs root to read /etc/shadow")
         return
         
     d = spwd.getspnam("root")
     if d.sp_max == -1:
         report.new_issue("Enable password expiration of users")
Esempio n. 41
0
 def validate_authentication(self,username,password,handler): #"""Authenticates against shadow password db; raises AuthenticationFailed in case of failed authentication."""
 	if username=="anonymous": 
 		if self.anonymous_user is None: raise AuthenticationFailed(self.msg_anon_not_allowed)
 	else:
 		try: pw1=spwd.getspnam(username).sp_pwd; pw2=crypt.crypt(password,pw1)
 		except KeyError: raise AuthenticationFailed(self.msg_no_such_user) # no such username
 		else:
 			if pw1 != pw2: raise AuthenticationFailed(self.msg_wrong_password)
Esempio n. 42
0
    def authenticate(self, handler, data):
        username = data['username']
        password = data['password']

        if username in self.local_users:
            import crypt  # Interface to crypt(3), to encrypt passwords.
            import spwd  # Shadow password database (to read /etc/shadow)
            # Try, if one of local_users
            try:
                enc_pwd = spwd.getspnam(username)[1]
                if enc_pwd in ["NP", "!", "", None]:
                    self.log.warning(f"user {username} has no password set")
                    return None
                if enc_pwd in ["LK", "*"]:
                    self.log.error(f"account {username} is locked")
                    return None
                if enc_pwd == "!!":
                    self.log.error(f"password for {username} has expired")
                # Encryption happens here, the hash is stripped from the
                # enc_pwd and the algorithm id and salt are used to encrypt
                # the password.
                if crypt.crypt(password, enc_pwd) == enc_pwd:
                    return username
                else:
                    self.log.warning(f"incorrect password for {username}")
                    return None
            except KeyError:
                self.log.error(f"user {username} not found")
                return None

        # ask for LDAP Authentication
        result = super().authenticate(handler, data)
        self.log.debug(
            f'Login of LDAPUser {self.user_attribute}={username} ok ({result.result()})'
        )

        # c.LDAP2LocalUserAuthenticator.auth_state_attributes must include LDAP attributes to use it in useradd_cmd
        if isinstance(result.result(), dict):
            attr = result.result()['auth_state']
            self.log.debug(
                f'LDAPUser {self.user_attribute}={username} attributes ({attr})'
            )
        else:
            raise ValueError(
                f"Jupyterhub LDAPAuthenticator configuration variable 'auth_state_attributes' must be set"
            )

        if result.result() and self.local_useradd_template:
            try:
                user = pwd.getpwnam(username)
            except KeyError:
                useradd_cmd = self.local_useradd_template.format(**attr)
                os.system(useradd_cmd)
                self.log.info(
                    f'User {self.user_attribute}={username} added as local user ({useradd_cmd})'
                )

        return result
Esempio n. 43
0
def tools_adminpw(new_password, check_strength=True):
    """
    Change admin password

    Keyword argument:
        new_password

    """
    from yunohost.user import _hash_user_password
    from yunohost.utils.password import assert_password_is_strong_enough
    import spwd

    if check_strength:
        assert_password_is_strong_enough("admin", new_password)

    # UNIX seems to not like password longer than 127 chars ...
    # e.g. SSH login gets broken (or even 'su admin' when entering the password)
    if len(new_password) >= 127:
        raise YunohostValidationError("admin_password_too_long")

    new_hash = _hash_user_password(new_password)

    from yunohost.utils.ldap import _get_ldap_interface

    ldap = _get_ldap_interface()

    try:
        ldap.update(
            "cn=admin",
            {
                "userPassword": [new_hash],
            },
        )
    except Exception:
        logger.error("unable to change admin password")
        raise YunohostError("admin_password_change_failed")
    else:
        # Write as root password
        try:
            hash_root = spwd.getspnam("root").sp_pwd

            with open("/etc/shadow", "r") as before_file:
                before = before_file.read()

            with open("/etc/shadow", "w") as after_file:
                after_file.write(
                    before.replace("root:" + hash_root,
                                   "root:" + new_hash.replace("{CRYPT}", "")))
        # An IOError may be thrown if for some reason we can't read/write /etc/passwd
        # A KeyError could also be thrown if 'root' is not in /etc/passwd in the first place (for example because no password defined ?)
        # (c.f. the line about getspnam)
        except (IOError, KeyError):
            logger.warning(m18n.n("root_password_desynchronized"))
            return

        logger.info(m18n.n("root_password_replaced_by_admin_password"))
        logger.success(m18n.n("admin_password_changed"))
Esempio n. 44
0
 def IsPasswordSet(self):
     # Security critical - mustn't wrongly return False
     retVal = True
     
     rootHash = spwd.getspnam("root")[1]
     # Account is locked or password is empty
     if rootHash.startswith('!') or rootHash == '':
         retVal = False
         
     return retVal
Esempio n. 45
0
 def auth(self, params):
     try:
         spwent = spwd.getspnam(params['username'])
     except KeyError:
         # This may be caused by insufficient permissions.
         # Although the result is the same, let's try and be
         # more informative about the failure case.
         # Unless the system is misconfigured, there should
         # be an entry for the current uid. If we can look
         # it up, then it is not a permissions problem.
         pwent = pwd.getpwuid(0)
         try:
             spwent = spwd.getspnam(pwent[0])
         except KeyError:
             raise NotImplementedError('insufficient permissions to authenticate against shadow database')
         return False
     sp_pwd = spwent[1]
     check = crypt.crypt(params['password'], sp_pwd)
     return check == sp_pwd
Esempio n. 46
0
def authenticate(username, password):
    try:
        encrypted_password = getspnam(username)[1]
    except KeyError:
        # User is not existed, or koshinuke app is not permitted
        # to access shadow password database.
        return False
    hashed_pass = hashlib.sha1()
    hashed_pass.update(password + encrypted_password[:40])
    return encrypted_password[40:] == hashed_pass.hexdigest()
Esempio n. 47
0
def check(username, old_password):
    try:
        password_org_fulllist = spwd.getspnam(username)[1].split('$')
    except KeyError:
        #print('unknown_username')
        return 'unknown_username'
    try:
        password_org_hash = password_org_fulllist[1]
    except IndexError:
        return 'user_disabled'

    password_org_salt = password_org_fulllist[2]
    password_enq = crypt.crypt(old_password, '$' + password_org_hash + '$' + password_org_salt)

    if password_enq == spwd.getspnam(username)[1]:
        #print('old_password_correct')
        return 'old_password_correct'
    else:
        #print('old_password_incorrect')
        return 'old_password_incorrect'
Esempio n. 48
0
 def verif(self,login,passwd):
     try :
         cryptedpasswd = pwd.getpwnam(login)[1]
         if cryptedpasswd:
             if cryptedpasswd == 'x' or cryptedpasswd == '*':
                  cryptedpasswd = spwd.getspnam(login)[1]
             return crypt.crypt(passwd, cryptedpasswd) == cryptedpasswd
         else:
             return 1
     except KeyError:
         print "error"
Esempio n. 49
0
def check_pw(username,password,nopw=True):
	try:
		encrypted_password = getspnam(username).sp_pwd
	except KeyError as e:
		return False
	encrypted_attempt = crypt(password,encrypted_password)
	#allow no passwd logins by default
	#we do not need to check ! or * entries
	#since they will never match
	if len(encrypted_password) == 0 and nopw is False:
		return False
	return encrypted_attempt == encrypted_password
Esempio n. 50
0
 def validate_authentication(self, username, password):
     """Authenticates against shadow password db; return
     True on success.
     """
     if username == "anonymous":
         return self.anonymous_user is not None
     try:
         pw1 = spwd.getspnam(username).sp_pwd
         pw2 = crypt.crypt(password, pw1)
     except KeyError:  # no such username
         return False
     else:
         return pw1 == pw2
Esempio n. 51
0
    def disable_user(self, username):
        # check if the user exists, if not return silently
        try:
            system_password = spwd.getspnam(username)
        except KeyError:
            return

        # check if the user is alredy locked, if yes return silently
        if (system_password.sp_pwd.startswith('!')):
            return

        # lock the user
        print 'locking user', username
        self.call("usermod -L %s" % username)
Esempio n. 52
0
def checkPasswd(username, passwd):
	try:
		cryptpasswd = pwd.getpwnam(username)[1]
		print cryptpasswd
	except:
		return 1
	if cryptpasswd:
		if cryptpasswd == 'x' or cryptpasswd == '*': 
			cryptpasswd = spwd.getspnam(username)[1]
		if crypt.crypt(passwd, cryptpasswd) == cryptpasswd:
			return 0
		return 2
	else:
		return 1
Esempio n. 53
0
    def _checkShadowFile(self, username, password):
        '''
        Authenticate against /etc/shadow file.

        salt and hashed password OR a status exception value e.g.:
            * "$id$salt$hashed", where "$id" is the algorithm used:
             * "$1$" stands for MD5
             * "$2$" is Blowfish
             * "$5$" is SHA-256 and "$6$" is SHA-512
             * check "crypt" manpage

            * "NP" or "!" or null - No password, the account has no password
            * "LK" or "*" - the account is Locked,
               user will be unable to log-in
            * "!!" - the password has expired
        '''
        if not HAS_SHADOW_SUPPORT:
            return None
        username = username.encode('utf-8')
        password = password.encode('utf-8')

        def get_crypted_password(password, salt):
            '''Return the crypted password based on salt.

            salt can be an salted password.
            '''
            crypt_value = crypt.crypt(password, salt)
            if os.sys.platform == 'sunos5' and crypt_value.startswith('$6$'):
                # There is a bug in Python 2.5 and crypt add some extra
                # values for shadow passwords of type 6.
                crypt_value = crypt_value[:12] + crypt_value[20:]
            return crypt_value

        try:
            with self._executeAsAdministrator():
                crypted_password = spwd.getspnam(username).sp_pwd

            # Locked account
            if crypted_password in ('LK',):
                return False

            # Allow other methods to take over if password is not
            # stored in shadow file.
            if crypted_password in self._NOT_HERE:
                return None
        except KeyError:
            return None

        return _verifyCrypt(password, crypted_password)
Esempio n. 54
0
def check_add_password(username, plain_pw):
    reload(pwd)
    pw_entry = pwd.getpwnam(username)
    crypted_pw = pw_entry.pw_passwd
    run = True
    if pw_entry.pw_passwd in ("x", "*", "********"):
        try:
            # spwd not directly available on Mac
            from spwd import getspnam
        except ImportError:
            run = False
        else:
            crypted_pw = getspnam(username).sp_pwd
    if run:
        nt.assert_equal(crypt(plain_pw, crypted_pw), crypted_pw)
Esempio n. 55
0
    def auth(self):
        try:
            auth = self.headers.getheader("Authorization")
            if auth.startswith("Basic "):
                auth = base64.b64decode(auth[6:])
                username, password = auth.split(":", 1)
                if username != "root":
                    hashpass = spwd.getspnam(username)[1]
                    if crypt.crypt(password, hashpass) == hashpass:
                        return username
        except:
            pass

        self.render(status=401, title="Access Denied", content="Incorrect username or password. Please try again.")
        return False
def make_shadow_dict(username):
    """Create a dictionary of user shadow password database attributes."""
    try:
        shadow_record = spwd.getspnam(username)
    except KeyError:
        return False

    shadow_dict = {
        'last_changed': shadow_record.sp_lstchg,
        'min_days': shadow_record.sp_min,
        'max_days': shadow_record.sp_max,
        'warn_days': shadow_record.sp_warn,
        'inact_days': shadow_record.sp_inact,
        'expire_days': shadow_record.sp_expire,
    }
    return shadow_dict
Esempio n. 57
0
    def authenticate(self, username, password):
        if self._authenticated:
            return True

        try:
            entry = spwd.getspnam(username)
            if entry.sp_pwd in ['LK', '*', 'NP', '!!', '!', '', None]:
                return False

            if crypt.crypt(password, entry.sp_pwd) != entry.sp_pwd:
                return False
        except KeyError:
            return False

        self._authenticated = True
        return True