def salt(self, **kwargs): rounds = kwargs.get("rounds", 5000) if (sys.version_info.major, sys.version_info.minor) > (3, 6): salt = crypt.mksalt(method=crypt.METHOD_SHA256, rounds=rounds) else: salt = crypt.mksalt(method=crypt.METHOD_SHA256) return salt
def collect(sssh): global count, collected_random print(sssh) sha_desires=crypt.crypt(sssh, crypt.mksalt(crypt.METHOD_SHA512)) print(" adding %s and %s " % (collected_random, sha_desires)) collected_random=crypt.crypt(collected_random + sha_desires, crypt.mksalt(crypt.METHOD_SHA512)) os.system('clear') print(" **yay!** Your secret %s will be mixed into zcash!!" % things_to_collect)
def test_invalid_rounds(self): for method in (crypt.METHOD_SHA256, crypt.METHOD_SHA512, crypt.METHOD_BLOWFISH): with self.assertRaises(TypeError): crypt.mksalt(method, rounds='4096') with self.assertRaises(TypeError): crypt.mksalt(method, rounds=4096.0) for rounds in (0, 1, -1, 1 << 999): with self.assertRaises(ValueError): crypt.mksalt(method, rounds=rounds) with self.assertRaises(ValueError): crypt.mksalt(crypt.METHOD_BLOWFISH, rounds=1000) for method in (crypt.METHOD_CRYPT, crypt.METHOD_MD5): with self.assertRaisesRegex(ValueError, 'support'): crypt.mksalt(method, rounds=4096)
def ok(event=None): with open(os.path.join(LOCAL_PATH, '.pwd')) as fich: cryptedpwd = fich.read() old = oldpwd.get() pwd = newpwd.get() pwd2 = confpwd.get() if crypt.crypt(old, cryptedpwd) == cryptedpwd: # passwords match if pwd == pwd2: # new passwords match cryptedpwd = crypt.crypt(pwd, crypt.mksalt(crypt.METHOD_SHA512)) with open(os.path.join(LOCAL_PATH, '.pwd'), "w") as fich: fich.write(cryptedpwd) mailboxes = CONFIG.get( "Mailboxes", "active").split(", ") + CONFIG.get( "Mailboxes", "inactive").split(", ") while "" in mailboxes: mailboxes.remove("") for mailbox in mailboxes: server, login, password, folder = decrypt(mailbox, old) if server is not None: encrypt(mailbox, pwd, server, login, password, folder) self.pwd = pwd top.destroy() logging.info('Password changed') return pwd else: showerror(_('Error'), _('Passwords do not match!')) else: showerror(_('Error'), _('Incorrect password!'))
def _crypt_password(self, input_clear_password: str): scheme = str(self) method = getattr(crypt, 'METHOD_' + scheme) salt = crypt.mksalt(method) crypted_pw = crypt.crypt(input_clear_password, salt).encode() encoded_pw = b64encode(crypted_pw).decode('utf-8') return '{' + scheme.upper() + '}' + encoded_pw
def generate_key(): _result_msg = "done" _userkey = "" _public_key = "" _private_key = "" _jsonData = request.get_json() user_agent = request.headers.get('User-Agent', "") if type(_jsonData) is str: _jsonData = json.loads(request.get_json()) _username = _jsonData['username'] _userpassword = _jsonData['userpassword'] try: mydb = pymysql.connect(**setting.mysql_config) dbcursor = mydb.cursor() sql_str = """SELECT * FROM %s.user WHERE name = '%s'; """ % ( setting.mysql_db_name, _username) _mysql_rst = dbcursor.execute(sql_str) _mysql_result = dbcursor.fetchall() if _mysql_rst > 0: _result_msg = "That username is already in use!" else: _datetime = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S") _salt = crypt.mksalt(crypt.METHOD_SHA512) _hash = crypt.crypt( "%s_%s_%s" % (_username, _userpassword, _datetime), _salt) _userkey_bytes = base64.b64encode( ('%s' % (_hash)).encode(encoding="utf-8")) _userkey = str(_userkey_bytes, encoding="utf-8") _keypair_chaindb = generate_keypair() _public_key = _keypair_chaindb.public_key _private_key = _keypair_chaindb.private_key _lastlogin = _datetime sql_str = """insert into %s.user(user.name,user.password,user.key,user.public_key,user.private_key,user.salt,user.generate_date,user.lastlogin_date) values ('%s','%s','%s','%s','%s','%s','%s','%s');""" % ( setting.mysql_db_name, _username, _userpassword, _userkey, _public_key, _private_key, _salt, _datetime, _lastlogin) _mysql_rst = dbcursor.execute(sql_str) mydb.commit() _result_msg = "generate_key done" except Exception as e: _result_msg = e _userkey = "" finally: mydb.close() _resultDict = dict(msg=("%s") % (_result_msg), user_key=_userkey) return _resultDict
def _create_salt() -> gmpy2.mpz: salt = crypt.mksalt(crypt.METHOD_SHA512)[3:] salt_b = salt.encode() salt_hex = binascii.hexlify(salt_b) salt_int = int(salt_hex, 16) assert len(salt) == 16 return gmpy2.mpz(salt_int)
def main(): parser = argparse.ArgumentParser(description='Generate password') parser.add_argument('-l', '--length', type=int, default=8, help='password length') parser.add_argument('-p', '--password', type=str, help='password') parser.add_argument('--pg_user', type=str, help='user name for postgres password') args = parser.parse_args() alphabet = string.ascii_letters + string.digits password = ''.join(choice(alphabet) for i in range(args.length)) if args.password: password = args.password print("Password:"******"sha512:", crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA512))) if args.pg_user: pg_sha265 = EncryptPassword(args.pg_user, password, 'scram-sha-256') print("PG sha256: ", pg_sha265.encrypt().decode()) pg_md5 = EncryptPassword(args.pg_user, password, 'md5') print("PG md5: ", pg_md5.encrypt().decode())
def get_hash(self): self.salt = crypt.mksalt() self.hash = hashlib.pbkdf2_hmac('sha256', bytes(self.password, encoding='UTF-8'), bytes(self.salt, encoding='UTF-8'), 10000, 64) print(f'Salt is {self.salt} Hash is {self.hash}')
def insUser(self, name, passwd, email, force=False): """ insert a user in the database, or raise an error @param name user's name @param passwd user's password @param email user's e-mail @param force will modify the password and/or e-mail forcefully if True """ found=False msg="" res=self.execReq("select * from user where name='{}'".format(name)) if len(res): found=True msg="user {} already exists".format(name) res=self.execReq("select * from user where email='{}'".format(email)) if len(res): found=True msg="the e-mail address {} is already in use".format(name) if force or not found: req="INSERT INTO user VALUES (?,?,?)" c=crypt.crypt(passwd, salt=crypt.mksalt(crypt.METHOD_MD5)) print ("GRRRR req=",req, (name, c, email)) self.execReq(req, (name, c, email)) else: raise Exception('InsertError',msg)
def update_password(user: str, password: str): """ update_password changes a user's password to a given password if and only if a user of that name does already exists. :param username the requested username whose password to update. :param password the new password to to be set for this user. :returns boolean true if the password changed succesfully, false otherwise. """ with ldap3.Connection(ldap_server, auto_bind=True, receive_timeout=5, **config.LDAP_AUTH) as conn: success = conn.search( search_base="dc=netsoc,dc=co", search_filter=f"(&(objectClass=account)(uid={user}))", attributes=["uid", "gidNumber", "userPassword"], ) if not success: return False entry = conn.entries[0] crypt_password = "******" + crypt.crypt( password, crypt.mksalt(crypt.METHOD_SHA512)) if entry["gidNumber"] == 420: conn.modify(f"cn={user},cn=admins,dc=netsoc,dc=co", { "userPassword": [(ldap3.MODIFY_REPLACE, [f"{crypt_password}"])] }) else: conn.modify(f"cn={user},cn=member,dc=netsoc,dc=co", { "userPassword": [(ldap3.MODIFY_REPLACE, [f"{crypt_password}"])] }) return True
def create_user(username, password, firstname, lastname, email, phone, email_to_file=None): if not validate_username(username): return [None, "Wrong user name format (are allowed a-Z|0-9|.|-|_)"] if not validate_email(email): return [None, "Wrong email format"] if Users.objects.filter(username=username): logging.warning("Cannot create account: username {} already exists".format(email)) return [None, "This username already exists"] if Users.objects.filter(email=email): logging.warning("Cannot create account: email {} already exists".format(email)) return [None, "This email already exists"] person = People.objects.create(firstname=firstname, lastname=lastname, phone=phone, is_laboratory=0) role = Roles.objects.get(name=DEFAULT_ROLE) salt = crypt.mksalt(method=crypt.METHOD_SHA256) newuser = Users(username=username, password=crypt.crypt(password, salt), salt=salt, email=email, person=person, role=role, is_active=0, is_password_reset=0, code=utils.random_string()) newuser.save() allow_access_to_demo(newuser) text = "Your account '{}' has been created. ".format(username) + \ "It will be validated by an admin shortly. You will receive an email at this " + \ "address when your account has been activated." html = text send_email(email, "New varapp account", text=text, html=html, tofile=email_to_file) send_email(settings.EMAIL_ADMIN, "Account for user {} awaits validation".format(username), text='', html='', tofile=email_to_file) return [newuser, '']
def create(username, domain, email, password=None): # domain = get_domain_top(domain) print(f'Creating {email}@{domain} for user {username}') if os.popen(f'grep {domain} /etc/apache2/sites-available/001-mail.conf').read().strip() == '': configure(username, domain) uid = get_uid(username) gid = get_gid(username) home = f'/home/{username}' if not password: password = random_password(12) password_hash = crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA256)) global emails emails = [] conn = sqlite3.connect('/etc/dovecot/authdb.sqlite') c = conn.cursor() c.execute('DELETE FROM users WHERE username = ? AND domain = ?;', (email, domain)) c.execute('INSERT INTO users (username, domain, password, home, uid, gid) VALUES (?, ?, ?, ?, ?, ?);', (email, domain, password_hash, home, uid, gid)) conn.commit() conn.close() print(f'\n\n\t\tNew password of {email}@{domain}: {password}') domain = get_domain_top(domain) print(f'\t\tPOP3 hostname: pop3.{domain}') print(f'\t\tSMTP hostname: smtp.{domain}\n\n') print('Restarting Dovecot...') os.system('service dovecot restart')
def gen_password(pw_len): password = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(pw_len)) # python2 #print crypt.crypt(password, "$6$random_salt")' # python3 return password, crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA512))
def serve(user): print("--------Entered sheets_on function----------------") user.status[c.USER_STATUS_SALT] = crypt.mksalt(crypt.METHOD_SHA512) user.status[c.USER_STATUS_SALT_TIME] = time.time() user.status[c.USER_INTEGRATIONS][c.INTEGRATIONS_SHEETS] = c.INTEGRATION_STATUS_AGREED state = {'id': user.id, c.USER_STATUS_SALT: user.status[c.USER_STATUS_SALT]} state = json.dumps(state) #state = urllib.parse.quote_plus(state) # Use the client_secret.json file to identify the application requesting # authorization. The client ID (from that file) and access scopes are required. flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'keys/'+c.GOOGLE_OAUTH_CLIENT_SECRET_FILE, scopes=[c.SHEETS_INTEGRATIONS_SCOPE]) # Indicate where the API server will redirect the user after the user completes # the authorization flow. The redirect URI is required. flow.redirect_uri = c.GOOGLE_INTEGRATIONS_REDIRECT_URI # Generate URL for request to Google's OAuth 2.0 server. # Use kwargs to set optional request parameters. authorization_url, state = flow.authorization_url( # Enable offline access so that you can an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline', state=state, # Enable incremental authorization. Recommended as a best practice. include_granted_scopes='true') user.update_service_messages(s.click_auth_url + '\n' + authorization_url)
def addbasiclogin(username): loadlogins(ignoreerrors=True) password = secrets.token_urlsafe() print("New password for {}: {}".format(username, password)) BASIC_AUTH_LOGINS[username.lower()] = crypt.crypt(password, crypt.mksalt()) savefile(BASIC_AUTH_LOGINS, BASIC_AUTH_LOGINS_FILE)
def enable_telnet(squashfs_1): print('') print('######################################') print('Enabling telnet') print('######################################') print('Enabling persistent telnet server...') print('Changing root password...') pwd = getpass.getpass() pwd_confirm = getpass.getpass('Retype password: '******'Passwords do not match. Try again') pwd = getpass.getpass() pwd_confirm = getpass.getpass('Retype password: '******'root:' + crypt.crypt(pwd, crypt.mksalt( crypt.METHOD_MD5)) + ':10933:0:99999:7:::' shadow_path = os.path.join(squashfs_1, 'etc', 'shadow') with open(shadow_path, 'w') as shadow_file: shadow_file.write(hash_string) shadow_file.close() print('Done!') print('Updating init rcS', end='... ') rcS_file = os.path.join(squashfs_1, 'etc', 'init.d', 'rcS') with open(rcS_file, 'r+') as f: text = f.read() text = re.sub('telnetd &', 'busybox telnetd &', text) f.seek(0) f.write(text) f.truncate() print('Done!')
def add(self, **kwargs): """ Add host :param kwargs: mac = str location_id = str domain_id = str organization_id = str medium_id = str architecture_id = str operatingsystem_id = str ptable_id = str hostgroup_id = str build = bool managed = bool """ mac_address = kwargs.pop("mac", None) if not mac_address: mac_address = self.host.network.get_mac_by_ip(self.host.ip) host_d = { "name": self.host.fqdn, "mac": mac_address, "ip": self.host.ip, "root_pass": crypt.crypt( self.host.root_user.password, crypt.mksalt(method=crypt.METHOD_MD5) ) } host_d.update(kwargs) super(ForemanHost, self).add(**host_d) self.host_id = self.get_element_id(self.host.fqdn)
def make_salt(): """Generate a random salt with the indicator tag for password type. :returns: a valid salt for use with crypt.crypt """ return crypt.mksalt(method=PASSWORD_HASH_FORMAT[ CONF.conductor.rescue_password_hash_algorithm])
def system_session(self): """Set system parameters of the current session.""" self.user['kernel'] = self.packages['kernel'][self.user['kernel']] # Set cpu parameters if 'intel' in self.system['cpu'].lower(): self.user['cpu'] = { 'name': self.system['cpu'], 'microcode': self.packages['microcode'][0] } elif 'AMD' in self.system['cpu']: self.user['cpu'] = { 'name': self.system['cpu'], 'microcode': self.packages['microcode'][1] } else: self.user['cpu'] = {'name': self.system['cpu'], 'microcode': None} # Crypt and append passwords rootpasswd = crypt(self.user['root_passwd'], mksalt(METHOD_SHA512)) userpasswd = crypt(self.user['user_passwd'], mksalt(METHOD_SHA512)) self.user['passwords'] = {'root': rootpasswd, 'user': userpasswd} # Set keymap if 'keymap' not in self.system: self.user['keymap'] = self.user['language'].split('_')[0] else: self.user['keymap'] = self.system['keymap'] # Append NTFS packages self.user['ntfs'] = self.system['ntfs'] if self.system['ntfs'] is True: self.user['ntfs'] = self.packages['ntfs'] # Set system firmware self.user['firmware'] = { 'type': self.system['firmware'], 'version': self.system['efi'], 'driver': self.user['firmware'] } # Append firmware packages if self.user['firmware']['driver'] is True: self.user['firmware']['driver'] = self.packages['firmware'] # Set mirrorlist self.user['mirrorlist'] = self.system['mirrorlist']
def create_user(name, plain_passwd, gid, no_login=False): """ method to create user :param name: user name :param plain_passwd: password for user :param gid: primary group id for user :param no_login: True/False for log in shell """ if not isinstance(name, str) or not name.strip(): raise InvalidParameter('GINUSER0009E', {'user': name}) if not type(gid) in [int, int]: raise InvalidParameter('GINUSER0025E', {'user': name, 'gid': gid}) if not isinstance(no_login, bool): raise InvalidParameter('GINUSER0026E', { 'user': name, 'no_login': no_login }) adm = libuser.admin() if adm.lookupUserByName(name): raise OperationFailed('GINUSER0008E', {'user': name}) if not adm.lookupGroupById(gid): raise OperationFailed('GINUSER0030E', { 'user': name, 'err': "group with id %s doesn't exist" % gid }) try: new_user = adm.initUser(name) # Ensure user is normal and not system user if new_user[libuser.UIDNUMBER][0] < 1000: new_user.set(libuser.UIDNUMBER, adm.getFirstUnusedUid(1000)) new_user.set(libuser.GIDNUMBER, gid) if no_login: new_user[libuser.LOGINSHELL] = '/sbin/nologin' adm.addUser(new_user) # Setting user password. Crypt in Python 3.3 and some 2.7 backports # bring mksalt function, so, use it or use our self salt generator # Creates strongest encryption (SHA512 + 16 bytes SALT) if hasattr(crypt, "mksalt"): salt = crypt.mksalt(crypt.METHOD_SHA512) else: salt = gen_salt() enc_pwd = crypt.crypt(plain_passwd, salt) adm.setpassUser(new_user, enc_pwd, True) except UnicodeEncodeError as ue: err_msg = ue.message if ue.message else 'Username / password \ has NON - ASCII charater' raise OperationFailed('GINUSER0030E', {'user': name, 'err': err_msg}) except Exception as e: err_msg = e.message if e.message else e raise OperationFailed('GINUSER0030E', {'user': name, 'err': err_msg})
def set_user_passwd(params): """ test API for setUserPassword in class virDomain """ logger = params["logger"] guest = params["guestname"] username = params["username"] userpasswd = params["userpassword"] if "flags" in params: if params["flags"] == "encrypted": flags = libvirt.VIR_DOMAIN_PASSWORD_ENCRYPTED else: flags = 0 else: flags = 0 try: if "conn" in params: conn = libvirt.open(params["conn"]) else: conn = libvirt.open(optional_params["conn"]) logger.info("get connection to libvirtd") vm = conn.lookupByName(guest) logger.info("test guest name: %s" % guest) if not check_agent_status(vm): logger.error("guest agent is not connected") return 1 mac = get_guest_mac(vm) if not mac: logger.error("cannot get guest interface mac") return 1 ipaddr = utils.mac_to_ip(mac, 180) if not ipaddr: logger.error("cannot get guest IP") return 1 if flags > 0: passwd = crypt.crypt("123456", crypt.mksalt(crypt.METHOD_SHA512)) else: passwd = "123456" if create_new_user(ipaddr, "usertestapi", username, userpasswd, logger) != 0: return 1 vm.setUserPassword("usertestapi", passwd, flags) if verify_cur_user(ipaddr, "usertestapi", "123456") != 0: logger.error("cannot login guest via new user") return 1 except libvirtError, e: logger.error("API error message: %s" % e.message) return 1
def make_hash(password, method='SHA512'): if method == 'SHA512': method = crypt.METHOD_SHA512 elif method == 'SHA256': method = crypt.METHOD_SHA256 elif method == 'MD5': method = crypt.METHOD_MD5 return crypt.crypt(password, crypt.mksalt(method))
def _generate_salt(self) -> str: """Generate salt string Returns: str -- the salt string """ return crypt.mksalt(crypt.METHOD_SHA512)
def generate_private_key() -> int: """ Static function to generate a 16 byte random key. :return: the key as an integer """ private_key = crypt.mksalt(crypt.METHOD_SHA512)[3:].encode() return int.from_bytes(private_key, "big")
def post(request): data = json.loads(request.body) password = data["password"] data.pop("password") data["salt"] = crypt.mksalt() data["hashs"] = crypt.crypt(password, salt=data["salt"]) user = User(**data) user.save()
def create_users(file): with open(file, 'r') as csvfile: for row in csv.reader(csvfile, delimiter=','): user = row[0] passw = row[1] pwd = crypt.crypt(passw, crypt.mksalt(crypt.METHOD_SHA512)) s = "useradd -m -b /home -p '" + pwd + "' " + user os.system(s)
def update(cls, *args, **kwargs): """Update password hash on update""" if 'password' in kwargs.keys(): kwargs['phash'] = crypt.crypt(kwargs.pop('password'), crypt.mksalt()) return super().update(*args, **kwargs)
def save(self, *args, **kwargs): """Update password hash on save""" if getattr(self, 'password', None) is not None: self.phash = crypt.crypt(self.password, crypt.mksalt()) del self.password return super().save(*args, **kwargs)
def new_pw(shadow, secret_file): if check_perm(shadow): pw1 = getpass.getpass('Insert your password to generate keepsecret vault: ') hashed = crypt.crypt(pw1, crypt.mksalt(crypt.METHOD_SHA512)) manage_vault(pw1, secret_file, True) with open(shadow, 'w') as f: f.write( hashed + '\n') f.close()
def test_saltedcrypt(self): for method in crypt.methods: cr = crypt.crypt('assword', method) self.assertEqual(len(cr), method.total_size) cr2 = crypt.crypt('assword', cr) self.assertEqual(cr2, cr) cr = crypt.crypt('assword', crypt.mksalt(method)) self.assertEqual(len(cr), method.total_size)
def test_salt(self): self.assertEqual(len(crypt._saltchars), 64) for method in crypt.methods: salt = crypt.mksalt(method) self.assertIn(len(salt) - method.salt_chars, {0, 1, 3, 4, 6, 7}) if method.ident: self.assertIn(method.ident, salt[:len(salt) - method.salt_chars])
def createRestUser(session=None): """ Create the MySQL Router REST API user in MySQL MetaData. Args: session (object): The optional session object used to query the database. If omitted the MySQL Shell's current session will be used. """ import mysqlsh shell = mysqlsh.globals.shell if session is None: session = shell.get_session() if session is None: print("No session specified. Either pass a session object to this " "function or connect the shell to a database") return # check if we are connected to a server with metadat table stmt = """SELECT major FROM mysql_innodb_cluster_metadata.schema_version""" result = session.run_sql(stmt) if result: if result.fetch_one()[0] < 2: print( "ERROR: this is not a valid MySQL Server, the mysql_innodb_cluster_metada is to old!" ) return else: print( "ERROR: this is not a valid MySQL Server, no mysql_innodb_cluster_metada found!" ) return #get the current user connected username = shell.prompt("Enter the username: "******"Enter the password: "******"Enter the password again: ", {'type': 'password'}) if userpassword == userpassword_check: nok = False else: print("Passwords do not match, try again !") crypted_pwd = crypt.crypt(userpassword, crypt.mksalt(method=crypt.METHOD_SHA256)) stmt = """REPLACE INTO mysql_innodb_cluster_metadata.router_rest_accounts VALUES ((SELECT cluster_id FROM mysql_innodb_cluster_metadata.v2_clusters LIMIT 1), "{}", "modular_crypt_format", "{}", NULL, NULL, NULL);""".format(username, crypted_pwd) result = session.run_sql(stmt) if result: print( "You can now use '{}' to authenticate to MySQL Router's REST API.". format(username)) print( "Use myrouter=router.create(\"{}@<router IP>:8443\") to create an object to monitor." .format(username))
def addbasiclogin(username): username = username.lower() password = secrets.token_urlsafe() print("New password for {}: {}".format(username, password)) passwordhash = crypt.crypt(password, crypt.mksalt()) user = BasicUser(username=username, password=passwordhash) db.session.add(user) db.session.commit() return password
def create_user(name, plain_passwd, gid, no_login=False): """ method to create user :param name: user name :param plain_passwd: password for user :param gid: primary group id for user :param no_login: True/False for log in shell """ if not isinstance(name, str) or not name.strip(): raise InvalidParameter('GINUSER0009E', {'user': name}) if not type(gid) in [int, long]: raise InvalidParameter('GINUSER0025E', {'user': name, 'gid': gid}) if not isinstance(no_login, bool): raise InvalidParameter('GINUSER0026E', {'user': name, 'no_login': no_login}) adm = libuser.admin() if adm.lookupUserByName(name): raise OperationFailed('GINUSER0008E', {'user': name}) if not adm.lookupGroupById(gid): raise OperationFailed( 'GINUSER0009E', {'user': name, 'err': "group with id %s doesn't exist" % gid}) try: new_user = adm.initUser(name) # Ensure user is normal and not system user if new_user[libuser.UIDNUMBER][0] < 1000: new_user.set(libuser.UIDNUMBER, adm.getFirstUnusedUid(1000)) new_user.set(libuser.GIDNUMBER, gid) if no_login: new_user[libuser.LOGINSHELL] = '/sbin/nologin' adm.addUser(new_user) # Setting user password. Crypt in Python 3.3 and some 2.7 backports # bring mksalt function, so, use it or use our self salt generator # Creates strongest encryption (SHA512 + 16 bytes SALT) if hasattr(crypt, "mksalt"): salt = crypt.mksalt(crypt.METHOD_SHA512) else: salt = gen_salt() enc_pwd = crypt.crypt(plain_passwd, salt) adm.setpassUser(new_user, enc_pwd, True) except UnicodeEncodeError as ue: err_msg = ue.message if ue.message else 'Username / password \ has NON - ASCII charater' raise OperationFailed('GINUSER0009E', {'user': name, 'err': err_msg}) except Exception as e: err_msg = e.message if e.message else e raise OperationFailed('GINUSER0009E', {'user': name, 'err': err_msg})
def sanitize_settings(self, settings): """sanitizes removes the cleartext password and replaces with the proper hashes""" accounts = settings.get('accounts') if accounts is None: return creds = accounts.get('credentials') if creds is None: return for cred in creds: cleartext_password = cred.get('passwordCleartext') if cleartext_password is None: continue print("Santizing password...") # Remove the cleartext password. We don't want to save this. del cred['passwordCleartext'] # Replace with the hashed versions of the password cred['passwordHashMD5'] = crypt.crypt(cleartext_password, crypt.mksalt(crypt.METHOD_MD5)) cred['passwordHashSHA512'] = crypt.crypt(cleartext_password, crypt.mksalt(crypt.METHOD_SHA512)) cred['passwordHashSHA256'] = crypt.crypt(cleartext_password, crypt.mksalt(crypt.METHOD_SHA256)) return
def testPassword(cryptPass, dictionaryFile): """ tests each password against all dictionary words""" #salt = cryptPass[0:2] salt = crypt.mksalt(crypt.METHOD_SHA512) # Updated for SHA512 encrypted passwords dictFile = open(dictionaryFile, 'r') for word in dictFile.readlines(): word = word.strip('\n') cryptWord = crypt.crypt(word, salt) if cryptWord == cryptPass: print('[+] Found Password: '******'\n') return print('[-] Password Not Found.\n') return
def change_user_password(user, new_password): """ Changes the user's password """ try: shadow_password = crypt.crypt(new_password, crypt.mksalt(crypt.METHOD_SHA512)) except: logging.warning(_("Error creating password hash for user {0}".format(user))) return False try: chroot_run(['usermod', '-p', shadow_password, user]) except: logging.warning(_("Error changing password for user {0}".format(user))) return False return True
def initialize(self): self.set("max_returned_values", 500) self.set("database_type", "postgresql+psycopg2") self.set("username", "citizenwatt") self.set("password", "citizenwatt") self.set("database", "citizenwatt") self.set("host", "localhost") self.set("debug", False) self.set("url_energy_providers", "http://dev.citizenwatt.paris/providers/electricity_providers.json") self.set("salt", crypt.mksalt()) self.set("named_fifo", "/tmp/sensor") self.set("default_timestep", 8) self.set("port", 8080) self.set("autoreload", False) self.save()
def pwd_chg(arguments): if misc.arg_range(arguments): exit(" Error! Usage: onyx-api --userpwd username old_pwd") import crypt username = arguments[0] old_pwd = arguments[1] gen_pwd = misc.pass_gen() if pwd_chk([username, old_pwd], False) is True: new_pwd = crypt.crypt(gen_pwd, crypt.mksalt(crypt.METHOD_SHA512)) print(gen_pwd) else: print(False) return False
def _mksalt(self): if hasattr(crypt, 'mksalt'): mname = 'METHOD_' + self.method.upper() method = getattr(crypt, mname, None) if method is None: raise ValueError('Unsupported crypt(3) method: %s' % (self.method,)) return crypt.mksalt(method) salt_chars = string.ascii_letters + string.digits + './' if self.method == 'sha256': return '$5$%s' % (get_salt_string(16, salt_chars),) if self.method == 'sha512': return '$6$%s' % (get_salt_string(16, salt_chars),) raise ValueError('Unsupported crypt(3) method: %s' % (self.method,))
def adduser(gp=True): """ Adds Users specified by 'users' & creates group :param gp: Set True if password should be the same on all hosts :return: Nothing Usage: Global passwords across all hosts $ fab adduser Different password for each hosts: $ fab adduser:gp=False """ with settings(hide('warnings', 'stdout', 'stderr'), warn_only=True): if groups: for group in groups.split(','): addgroup = sudo("groupadd %s" % group) if addgroup.return_code == 0: print("Group added %s: " % group) elif addgroup.return_code == 9: print("Group already exists: %s" % group) else: print("An error occurred while adding group: %s" % group) for i in users: if len(i) == 3: pw = generatepw() i.append(pw) with settings(hide('warnings', 'stdout', 'stderr'), warn_only=True): if groups: sudo("adduser -c \"%s - %s\" -m -G %s %s" % (i[0], i[1], groups, i[2])) else: sudo("adduser -c \"%s - %s\" -m %s" % (i[0], i[1], i[2])) crypted_password = crypt.crypt(i[3], crypt.mksalt(crypt.METHOD_CRYPT)) sudo('usermod --password %s %s' % (crypted_password, i[2]), pty=True) # Modify the following rules to your needs: (Read chage manpage) sudo("chage -E -1 -W 14 -m 0 -M -1 -I -1 %s" % i[2]) print("\nUsers for %s\n" % env.host) for i in users: # Print the list of Users with credentials print("%s" % i[0]) print("User: %s\nPassword: %s" % (i[2], i[3])) if not gp: for i in users: if len(i) == 4: i.pop()
def set_password_mandragore(self, raw_password): """ Set the password in Mandragore This method is meant to replace the default set_password method of :py:class:`django.contrib.auth.models.User` Uses :py:func:`crypt.crypt` to generate a ``SHA512`` hash of raw_password. raw_password is salted with a random salt generated by :py:func:`crypt.mksalt`. """ # Use only 8 characters in the salt. Otherwise the generated hash will be # to long for the mandragore MotDePasse Field. the_hash = crypt.crypt(raw_password, salt=crypt.mksalt(method=crypt.METHOD_SHA512)[:11]) update_user_password(self.username, the_hash) self.save()
def set_rootcredentials(self): """ Set root password and ssh public key of the initramfs """ logging.debug('>>> entering initramfs.append.set_rootcredentials') process('mkdir -p %s' % self.temp['work']+'/initramfs-rootcredentials-temp/etc', self.verbose) process('mkdir -p %s' % self.temp['work']+'/initramfs-rootcredentials-temp/root', self.verbose) process('cp /etc/shells %s' % self.temp['work']+'/initramfs-rootcredentials-temp/etc', self.verbose) process('chown root:root %s'% self.temp['work']+'/initramfs-rootcredentials-temp/root', self.verbose) # If we are called only for ssh pubkeys and don't have a pass configured we use * as a pass if self.rootpasswd is '': password_hash="*" else: password_hash=crypt.crypt(self.rootpasswd, crypt.mksalt()) #create the user and group files print(green(' * ') + '... ' + '/etc/passwd') process('echo "root:x:0:0:root:/root:/bin/sh" > %s'% self.temp['work']+'/initramfs-rootcredentials-temp/etc/passwd', self.verbose) print(green(' * ') + '... ' + '/etc/shadow') process("echo 'root:%s:::::::' > %s"% (password_hash, self.temp['work']+'/initramfs-rootcredentials-temp/etc/shadow'), self.verbose) process('chmod 640 %s'% self.temp['work']+'/initramfs-rootcredentials-temp/etc/shadow', self.verbose) print(green(' * ') + '... ' + '/etc/group') process('echo "root:x:0:root" > %s' % self.temp['work']+'/initramfs-rootcredentials-temp/etc/group', self.verbose) # Add the ssh pubkeys if required if self.ssh_pubkeys is True: print(green(' * ') + '... ' + '/root/.ssh/authorized_keys') process('mkdir -p %s' % self.temp['work']+'/initramfs-rootcredentials-temp/root/.ssh', self.verbose) process('cp %s %s' % (self.ssh_pubkeys_file, self.temp['work']+'/initramfs-rootcredentials-temp/root/.ssh/authorized_keys'), self.verbose) # # HACK quick ninja chroot to set password - leave for history museum of horror coding - actually send the whole project ;) # slash = os.open('/', os.O_RDONLY) # os.chroot(self.temp['work']+'/initramfs-rootpasswd-temp/') # dive in # PROBLEM we don't have the FULL initramfs, hence no /bin/sh to chroot in # os.system('echo "root:%s" | busybox chpasswd' % self.rootpasswd) # # HACK break out of chroot # os.fchdir(slash) # for i in range(100): # assume we haven't gone deeper than 100 # os.chdir('..') # os.chroot('.') os.chdir(self.temp['work']+'/initramfs-rootcredentials-temp') return os.system(self.cpio())
def add_user(self, username, password, name='', email=''): """Insert a user into the database""" salt = crypt.mksalt() encrypted_pw = crypt.crypt(password, salt) query = """ INSERT INTO "{table}" ("{login}", "{password}", "{salt}", "{name}", "{email}") VALUES (:login, :password, :salt, :name, :email) """.format(**self.schema) self.__query(query, { "login": username, "password": encrypted_pw, "salt": salt, "name": name, "email": email }, write=True)
def user_register(self, proto, name, gecos, password, command): if name is None: self.error(proto, command, 'No handle', False) return False if valid_handle.match(name) is None: self.error(proto, command, 'Invalid handle', False, {'handle': [name]}) return False if len(name) > parser.MAXTARGET: self.error(proto, command, 'Handle is too long', False, {'handle': [name]}) return False f = yield from self.proto_store.get_user(name.lower()) if f is not None: self.error(proto, command, 'Handle already registered', False, {'handle': [name]}) return False if len(gecos) > parser.MAXTARGET: self.error(proto, command, 'GECOS is too long', False, {'gecos': [gecos]}) return False if password is None or len(password) < 5: # Password is not sent back for security reasons self.error(proto, command, 'Bad password', False) return False password = crypt.crypt(password, crypt.mksalt()) # Bang yield from self.proto_store.create_user(name.lower(), gecos, password) # Clear the user cache self.get_any_target.cache_clear() # Poop out a new user object return User(self, name, gecos, password)
def adduser(user=None, comment=None): """ Adds a single user to hosts specified :param: user: userid/login :param: comment: user comment string :return: Usage: $ fab -H <host(s)> adduser:user=<user>,comment=<comment string> """ if all([user, comment]): if user in temp.data: pw = temp.getpassword(user) else: generatepw(user=user) pw = temp.getpassword(user) with settings(warn_only=True): checkuser = run("id %s" % user) if checkuser.return_code == 0: print("%s: " % env.host + white("Account: ") + "%s " % user + blue("..already exists")) else: sudo("adduser -c \"%s\" -m %s" % (comment, user)) crypted_password = crypt.crypt( pw, crypt.mksalt(crypt.METHOD_CRYPT)) sudo('usermod --password %s %s' % (crypted_password, user), pty=True) # Modify the following rules to your needs (see chage manpage) sudo("chage -E -1 -W 11 -m 7 -M 42 -I 30 -d now-44days %s" % user) print("%s: " % env.host + white("Create Account: ") + "%s " % user + white("Password: "******"%s " % pw + green("..Success")) logger.lugmslog(logtemplate % (env.host, env.user, 'adduser', user, "'%s'" % comment))
def add_new_user(username,uid,homedir): """This function adds a new system user with specified parameters""" res = subprocess.run([ 'useradd', '--comment="WEB_USER_'+str(uid)+',,,"', '--home-dir='+homedir, '--no-log-init', '--create-home', '--shell=/bin/bash', '--uid='+str(uid), username], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if res.stderr != b'': sys.stdout.write('Error adding user %s with uid %d: %s\n' % (username,uid,res.stderr)) sys.exit(1) enc_password = crypt.crypt(USER_PASSWORD,crypt.mksalt(crypt.METHOD_SHA512)) res = subprocess.run([ 'usermod', '-p', enc_password, username], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if res.stderr != b'': sys.stdout.write('Error setting password for user %s: %s\n' % (username,res.stderr)) sys.exit(1)
def create_user(name, plain_passwd, profile=None, gid=None): adm = libuser.admin() user = adm.lookupUserByName(name) if user: msg = 'User/Login "%s" already in use' % name wok_log.error(msg) raise OperationFailed('GINUSER0008E', {'user': name}) try: new_user = adm.initUser(name) # Ensure user is normal and not system user if new_user[libuser.UIDNUMBER][0] < 1000: new_user.set(libuser.UIDNUMBER, adm.getFirstUnusedUid(1000)) new_user.set(libuser.GIDNUMBER, adm.getFirstUnusedGid(1000)) if gid is not None: new_user.set(libuser.GIDNUMBER, gid) if profile == "kimchiuser": new_user[libuser.LOGINSHELL] = '/sbin/nologin' adm.addUser(new_user) # Setting user password. Crypt in Python 3.3 and some 2.7 backports # bring mksalt function, so, use it or use our self salt generator # Creates strongest encryption (SHA512 + 16 bytes SALT) if hasattr(crypt, "mksalt"): salt = crypt.mksalt(crypt.METHOD_SHA512) else: salt = gen_salt() enc_pwd = crypt.crypt(plain_passwd, salt) adm.setpassUser(new_user, enc_pwd, True) except Exception as e: wok_log.error('Could not create user %s, error: %s', name, e) raise OperationFailed('GINUSER0009E', {'user': name}) return new_user
def main(): parser = argparse.ArgumentParser(description='Kickstart a Centos 7 KVM') parser.add_argument("-n", "--name", dest="name", help="VM Name", required=True) parser.add_argument("-c", "--cpu", dest="cpu", default="1", help="How many vCPUs,") parser.add_argument("-r", "--ram", dest="ram", default="1024", help="How much ram do you need,") parser.add_argument("-d", "--disk", dest="size", default="10", help="How much disk space in gigs") parser.add_argument("-p", "--pass", dest="pass", default="password", help="Root password") parser.add_argument("-u", "--user", dest="user", default=False, help="User besides root to add and will have the same password as root", required=True) try: options = parser.parse_args() except: if len(sys.argv) == 1: parser.print_help() return options = vars(options) hostname = options['name'] passwd = options['pass'] passwd_hash = crypt.crypt(passwd , crypt.mksalt(crypt.METHOD_SHA512)) user = options['user'] ram = options['ram'] size = options['size'] cpus = options['cpu'] kickstart_file_content = """ install cmdline #version=DEVEL # System authorization information auth --enableshadow --passalgo=sha512 # Use network installation url --url="http://www.gtlib.gatech.edu/pub/centos/7/os/x86_64/" # Use text mode install text # Run the Setup Agent on first boot firstboot --enable # use the whole disk ignoredisk --only-use=vda # Keyboard layouts keyboard --vckeymap=us --xlayouts='us' # System language lang en_US.UTF-8 # repository repo --name="CentOS Repo" --baseurl=http://www.gtlib.gatech.edu/pub/centos/7/os/x86_64/ # by specifying the update Repo the install process will automatically update to the latest version. # If you wish to stay at the initial release version, comment the following line. repo --name="CentOS Repo Update" --baseurl=http://www.gtlib.gatech.edu/pub/centos/7/updates/x86_64/ # Network information # dhcp network --bootproto=dhcp --device=eth0 --ipv6=auto --activate # hostname network --hostname=%s # firewall firewall --enabled --ssh # Root password # to generate your own hash, run the following command # python -c 'import crypt; print(crypt.crypt("passwordhere", crypt.mksalt(crypt.METHOD_SHA512)))' rootpw --iscrypted %s # add your own user user --groups=wheel --name=%s --password=%s --iscrypted --gecos="%s" # Do not configure the X Window System skipx # System timezone timezone America/New_York --isUtc # System bootloader configuration bootloader --append=" crashkernel=auto" --location=mbr --boot-drive=vda # thin partition autopart --type=thinp # Partition clearing information clearpart --all --initlabel --drives=vda # accept licensing eula --agreed # poweroff after install poweroff %%packages @core kexec-tools %%end %%addon com_redhat_kdump --enable --reserve-mb='auto' %%end %%post # cleanup the installation yum clean all # create default ssh keys ssh-keygen -q -t rsa -N "" -f /root/.ssh/id_rsa # create default authorized_keys file cp -p -f --context=system_u:object_r:ssh_home_t:s0 /root/.ssh/id_rsa.pub /root/.ssh/authorized_keys chmod 600 /root/.ssh/authorized_keys # run Aide to generate initial database aide -i # update yum -y update %%end """ % (hostname, passwd_hash, user, passwd_hash, user) with open('/data/centos7kvm/tmp.ks', 'w') as f: f.write(kickstart_file_content) kickstartfile = "tmp.ks" virt_command = """virt-install --name %s --ram %s --disk """ + \ """path=/data/images/%s.img,size=%s --vcpus %s --os-type linux """ + \ """--os-variant centos7.0 --network bridge=br0 --graphics none """ + \ """--console pty,target_type=serial --location """ + \ """'http://www.gtlib.gatech.edu/pub/centos/7/os/x86_64/' """ + \ """--initrd-inject=/data/centos7kvm/%s --extra-args """ + \ """'ks=file:/%s console=ttyS0,115200n8 serial'""" os.system(virt_command % (hostname, ram, hostname, size, cpus, kickstartfile, kickstartfile))
def hash_sha512(password): salt = crypt.mksalt(crypt.METHOD_SHA512) sha512pw = crypt.crypt(password, salt) return(sha512pw)
#!/usr/bin/python3 # -*- coding: utf-8 -*- import crypt raw_password = input('Enter password: ') hashed_password = crypt.crypt(raw_password, crypt.mksalt(crypt.METHOD_SHA512)) print(hashed_password)
#!/usr/bin/env python3 ### WARNING ### # requires Python >= 3.3 import sys, crypt, getpass; # this script generate a password using salted SHA512 whitch is the default on debian wheezy cleartext = getpass.getpass("Password:"******"Again:") if cleartext2 != cleartext: print ('Not matched!') sys.exit(1) salt = crypt.mksalt(crypt.METHOD_SHA512) print (crypt.crypt(cleartext, salt))
def __mksalt(self): """Return a crypt style salt string.""" return crypt.mksalt(crypt.METHOD_SHA512)
def __init__(self, filename, build_dir=None): self._parsed = configparser.ConfigParser() try: self._parsed.read(filename) except configparser.Error as err: raise ConfigError("Could not load the {0!r} file: {1}" .format(filename, err)) try: self._config = self._parsed["config"] except KeyError: raise ConfigError("No [config] section in build.conf") if build_dir is None: build_dir = os.path.join(os.path.dirname(filename), "build") self.build_dir = build_dir if os.path.isdir("../.git"): version = subprocess.check_output(["git", "describe", "--dirty"]) self.version = version.decode("utf-8").strip() else: self.version = self._config.get("version", fallback="unknown") self.arch = self._config.get("arch") if not self.arch: self.arch = _get_default_arch() modules = self._config.get("modules", "base,basic") self.modules = [m.strip() for m in modules.split(",")] self.module_files = [m + ".cpi" for m in self.modules] self.module_sqf_files = [m + ".sqf" for m in self.modules] self.module_lst_files = [m + ".lst" for m in self.modules] self.initramfs_files = ["_init.cpi"] self.compression = self._config.get("compression", fallback="xz") self.compress_cmd = [self.compression] if self.compression == "xz": self.compress_cmd += ["--check=crc32"] if self.compression == "gzip": self.compressed_ext = ".gz" else: self.compressed_ext = ".{0}".format(self.compression) self.compression_level = self._config.get("compression_level", fallback=None) if self.compression_level: self.compression_level = int(self.compression_level) self.compress_cmd.append("-{0}".format(self.compression_level)) self.efi = self._config.getboolean("efi", fallback=False) self.bios = self._config.getboolean("bios", fallback=True) self.net_boot = self._config.getboolean("net_boot", fallback=False) self.early_net = self._config.getboolean("early_net", fallback=False) if self.early_net: self.initramfs_files += ["_net.cpi"] self.efi_arch = self._config.get("efi_arch") if not self.efi_arch: if X86_64_RE.match(self.arch): self.efi_arch = "x64" elif X86_RE.match(self.arch): self.efi_arch = "ia32" else: self.efi_arch = None else: self.efi_arch = self.efi_arch.lower() if X86_64_RE.match(self.arch): self.bits = 64 else: self.bits = 32 grub_platforms = self._config.get("grub_platforms") if grub_platforms: self.grub_platforms = [p.strip() for p in grub_platforms.split(",")] else: self._choose_grub_platforms() if self.net_boot: self.net_grub_images = [NET_IMAGES[p] for p in self.grub_platforms if p in NET_IMAGES] else: self.net_grub_images = [] if all(os.path.exists("/lib/grub/{0}/progress.mod".format(p)) for p in self.grub_platforms): self.grub_progress_mod = "progress" else: self.grub_progress_mod = "" if all(os.path.exists("/lib/grub/{0}/linuxefi.mod".format(p)) for p in self.grub_platforms if p.endswith("-efi")): self.grub_linuxefi = "linuxefi" self.grub_initrdefi = "initrdefi" else: self.grub_linuxefi = "linux" self.grub_initrdefi = "initrd" self.memtest86 = self._config.getboolean("memtest86", fallback=False) self.memtest86_plus = self._config.getboolean("memtest86+", fallback=False) if self.efi: self.efi_shell = self._config.getboolean("efi_shell", fallback=False) else: self.efi_shell = False self.hashed_root_password = self._config.get("hashed_root_password") if not self.hashed_root_password: root_password = self._config.get("root_password") if root_password: self.hashed_root_password = crypt.crypt(root_password, crypt.mksalt(crypt.METHOD_MD5)) else: self.hashed_root_password = "" locales = self._config.get("locales") if locales.strip(): self.locales = [l.strip() for l in locales.split(",")] else: self.locales = ["en_US"] self.hostname = self._config.get("hostname", fallback="pld-new-rescue") # dummy values self.uuid = uuid.UUID("0"*32) self.efi_vol_id = "0000-0000" self.cd_vol_id = "0000-00-00-00-00-00-00" self.load_uuids() self.defaults = {k[8:]: v for k, v in self._config.items() if k.startswith("default_")} if os.getuid() == 0: self.c_sudo = [] else: self.c_sudo = ["sudo"] self.extra_path = self._config.get("extra_path", None) self.update_path()
def gen_crypt_password(password): crypt_password = crypt(password, mksalt(METHOD_SHA512)) return crypt_password
def get_crypt_password(self, password_clear): prefix = "" return prefix + crypt.crypt(password_clear, crypt.mksalt(crypt.METHOD_SHA512))
def generate_password_hash(self, new_password, method=None): """ See PasswordMethod Interface for details """ return "{%s}%s" % (self.hash_name, crypt.crypt(new_password, crypt.mksalt(getattr(crypt, "METHOD_" + method) if method else None)))