Esempio n. 1
0
def ldap_setpass(daan, user, password):
    if not password:
        return
    l = ldap.open(settings.LDAP_HOST)
    l.bind_s(settings.LDAP_USER, settings.LDAP_PASS)
    udn = 'uid=%s,%s' % (user, settings.LDAP_BASE)
    try:
        # Set LDAP password
        l.passwd_s(udn, None, password)
        # Set SAMBA password entries (to support MSCHAPv2 authentication
        # for WiFi via FreeRADIUS via LDAP).
        res = l.search_s(settings.LDAP_BASE, ldap.SCOPE_ONELEVEL,
                         'uid=%s' % user)
        if not res:
            return
        _o = res[0][1]
        if 'sambaNTPassword' in _o:
            l.modify_s(
                udn,
                ldap.modlist.modifyModlist(
                    {'sambaNTPassword': _o['sambaNTPassword'][0]},
                    {'sambaNTPassword': [smbpasswd.nthash(password)]}))
        else:
            # NOTE See /doc/ldap/scheme.ldif
            #      We added the scheme *after* the creation of the database.
            #      Thus, the user may still miss the objectClass knAccount.
            l.modify_s(
                udn,
                ldap.modlist.modifyModlist(
                    {'objectClass': _o['objectClass']}, {
                        'objectClass': _o['objectClass'] + ['knAccount'],
                        'sambaNTPassword': [smbpasswd.nthash(password)]
                    }))
    finally:
        l.unbind_s()
Esempio n. 2
0
def ldap_setpass(daan, user, password):
    if not password:
        return
    l = ldap.open(settings.LDAP_HOST)
    l.bind_s(settings.LDAP_USER, settings.LDAP_PASS)
    udn = 'uid=%s,%s' % (user, settings.LDAP_BASE)
    try:
        # Set LDAP password
        l.passwd_s(udn, None, password)
        # Set SAMBA password entries (to support MSCHAPv2 authentication
        # for WiFi via FreeRADIUS via LDAP).
        res = l.search_s(settings.LDAP_BASE, ldap.SCOPE_ONELEVEL,
                                'uid=%s' % user)
        if not res:
            return
        _o = res[0][1]
        if 'sambaNTPassword' in _o:
            l.modify_s(udn, ldap.modlist.modifyModlist(
                {'sambaNTPassword': _o['sambaNTPassword'][0]},
                {'sambaNTPassword': [smbpasswd.nthash(password)]}))
        else:
            # NOTE See /doc/ldap/scheme.ldif
            #      We added the scheme *after* the creation of the database.
            #      Thus, the user may still miss the objectClass knAccount.
            l.modify_s(udn, ldap.modlist.modifyModlist(
                {'objectClass': _o['objectClass']},
                {'objectClass': _o['objectClass'] + ['knAccount'],
                 'sambaNTPassword': [smbpasswd.nthash(password)]}))
    finally:
        l.unbind_s()
Esempio n. 3
0
def generateHashNTLM(username, randomWords):
    
    password = generatePassword(username, randomWords)
    try:
        print username+':'+str(random.randint(1000,2000))+'%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
    except AttributeError:
        print username+':'+str(random.randint(1000,2000))+'%s:%s:::' % (smbpasswd.nthash(password))
Esempio n. 4
0
def index(request):
    msg = ''
    result = False
    is_valid = False
    pysmb = PySamba()

    if request.method == 'POST':
        form = forms.UserForm(request.POST)
        if form.is_valid():
            is_valid = True
            nickname = form.cleaned_data['nickname']
            oldpasswd = form.cleaned_data['oldpasswd']
            newpasswd = form.cleaned_data['newpasswd']
            retpasswd = form.cleaned_data['retpasswd']
            if newpasswd == retpasswd:
                if not(newpasswd == oldpasswd) and not(newpasswd == settings.DEFAULT_PASSWD):
                    myuser = User.objects.filter(username=nickname)
                    if myuser.count() > 0:
                        u = User.objects.get(username=nickname)
                        records = HistPassword.objects.filter(user=u).order_by('date_change')
                        records.reverse()[:settings.HISTORY_SIZE]
                        gosave = True
                        for rec in records:
                            if rec.password == smbpasswd.nthash(newpasswd):
                                gosave = False
                                break
                        if gosave:
                            result, msg = pysmb.changePasswd(nickname, oldpasswd, newpasswd)
                            if result:
                                histpasswd = HistPassword(user=u, password=smbpasswd.nthash(newpasswd))
                                histpasswd.save()
                        else:
                            msg = _("You can not use old passwords")
                    else:
                        result, msg = pysmb.changePasswd(nickname, oldpasswd, newpasswd)

                        if result:
                            nvuser = User(username=nickname)
                            nvuser.save()
                            histpasswd = HistPassword(user=nvuser, password=smbpasswd.nthash(newpasswd))
                            histpasswd.save()
                else:
                    msg = _("Your new password is not valid")
            else:
                msg = _("Failed confirmation of your new password")
    else:
        form = forms.UserForm()

    return render(request, 'sambaweb/index.html', {
        'form': form,
        'is_valid': is_valid,
        'result': result,
        'message': msg,
    })
Esempio n. 5
0
def mkpasswd(pwd, sambaver=3, default='ssha'):
    ''' Make a given password cryptated, possibly with different
        crypt-algorihtms. This module was written for use with
	    LDAP - so default is seeded sha
    '''
    alg = {
        'sha': 'Secure Hash Algorithm',
        'ssha': 'Seeded SHA',
        'md5': 'MD5',
        'smd5': 'Seeded MD5',
    }
    if _crypt:
        alg['crypt'] = 'standard unix crypt'

    if smb:
        alg['lmhash'] = 'lan man hash'
        alg['nthash'] = 'nt hash'
    if default not in alg.keys():
        return 'algorithm <%s> not supported in this version.' % default
    else:
        salt = getsalt()
        if default == 'ssha':
            pwString = "{SSHA}" + base64.encodestring(
                sha.new(str(pwd) + salt).digest() + salt)
            return pwString[:-1]
        elif default == 'sha':
            pwString = "{SHA}" + base64.encodestring(
                sha.new(str(pwd)).digest())
            return pwString[:-1]
        elif default == 'md5':
            pwString = "{MD5}" + base64.encodestring(
                md5.new(str(pwd)).digest())
            return pwString[:-1]
        elif default == 'smd5':
            salt = getsalt(
                length=4
            )  # Newer versions of OpenLDAP should support the default length 16
            pwString = "{SMD5}" + base64.encodestring(
                md5.new(str(pwd) + salt).digest() + salt)
            return pwString[:-1]
        elif default == 'crypt':
            return "{CRYPT}" + crypt.crypt(str(pwd), getsalt(
                length=2))  # crypt only uses a salt of length 2
        elif default == 'lmhash':
            if sambaver == 3:
                return "{sambaLMPassword}" + smbpasswd.lmhash(pwd)
            elif sambaver == 2:
                return "{lmPassword}" + smbpasswd.lmhash(pwd)
        elif default == 'nthash':
            if sambaver == 3:
                return "{sambaNTPassword}" + smbpasswd.nthash(pwd)
            elif sambaver == 2:
                return "{NTPassword}" + smbpasswd.nthash(pwd)
Esempio n. 6
0
def admin(request):
    admin_member = retrieve_member(request)
    if not request.user.profile.is_ldap_admin:
        return render(request, 'access_denied.html')
    users = admin_member.list_users()
    if request.method == 'POST':
        form = AdminForm(request.POST, request=request, users=users)

        if form.is_valid():
            new_password = form.cleaned_data['password1']
            admin_member.admin_change_password(form.cleaned_data['username'],
                                               new_password)

            member = MemberValues(form.cleaned_data['username'], new_password)
            member.set('sambaLMPassword', smbpasswd.lmhash(new_password))
            member.set('sambaNTPassword', smbpasswd.nthash(new_password))
            member.save()

            new_form = AdminForm(request=request, users=users)
            return render(
                request, 'admin.html', {
                    'message':
                    _('The password for %s was changed. Thank you!' %
                      form.cleaned_data['username']),
                    'form':
                    new_form
                })
        else:
            return render(request, 'admin.html', {'form': form})
    else:
        form = AdminForm(request=request, users=users)
        return render(request, 'admin.html', {'form': form})
Esempio n. 7
0
    def changeUserPasswd(self, uid, passwd, oldpasswd = None, bind = False):
        """
        change SAMBA user password

        @param uid: user name
        @type  uid: str

        @param passwd: non encrypted password
        @type  passwd: str
        """

        # Don't update the password if we are using smbk5passwd
        conf = SambaConf()
        if conf.isValueTrue(conf.getContent("global", "ldap passwd sync")) in (0, 1):
            userdn = self.searchUserDN(uid)
            r = AF().log(PLUGIN_NAME, AA.SAMBA_CHANGE_USER_PASS, [(userdn,AT.USER)])
            # If the passwd has been encoded in the XML-RPC stream, decode it
            if isinstance(passwd, xmlrpclib.Binary):
                passwd = str(passwd)
            s = self.l.search_s(userdn, ldap.SCOPE_BASE)
            c, old = s[0]
            new = old.copy()
            new['sambaLMPassword'] = [smbpasswd.lmhash(passwd)]
            new['sambaNTPassword'] = [smbpasswd.nthash(passwd)]
            new['sambaPwdLastSet'] = [str(int(time()))]
            # Update LDAP
            modlist = ldap.modlist.modifyModlist(old, new)
            self.l.modify_s(userdn, modlist)
            self.runHook("samba.changeuserpasswd", uid, passwd)
            r.commit()

        return 0
Esempio n. 8
0
def mkpasswd(pwd,hash='ssha'):
    """Generate hashed passwords. Originated from mkpasswd in Luma
    """
    alg = {
        'ssha':'Seeded SHA-1',
        'sha':'Secure Hash Algorithm',
        'smd5':'Seeded MD5',
        'md5':'MD5',
        'crypt':'Standard unix crypt'
    }
    # Don't add support for sambapasswords unless we're using it
    if (update_sambapassword):
        alg['lmhash'] = 'Lanman hash'
        alg['nthash'] = 'NT Hash'
    if hash not in alg.keys():
        return "Algorithm <%s> not supported in this version." % hash
    else:
        salt = getsalt()
        if hash == "ssha":
            return "{SSHA}" + base64.encodestring(sha.new(str(pwd) + salt).digest() + salt)
        elif hash == "sha":
            return "{SHA}" + base64.encodestring(sha.new(str(pwd)).digest())
        elif hash == "md5":
            return "{SHA}" + base64.encodestring(md5.new(str(pwd)).digest())
        elif hash == "smd5":
            return "{SMD%}" + base64.encodestring(md5.new(str(pwd) + salt).digest() + salt)
        elif hash == "crypt":
            return "{CRYPT}" + crypt.crypt(str(pwd),getsalt(length=2))
        # nt/lm-hash are used directly in their own password-attributes.. no need to prefix the hash
        elif hash == "lmhash":
            return smbpasswd.lmhash(pwd)
        elif hash == "nthash":
            return smbpasswd.nthash(pwd)
Esempio n. 9
0
 def addSmbAttr(self, uid, password):
     """
     Add SAMBA password and attributes on a new user
     """
     # Get domain info
     domainInfo = self.getDomain()
     # Get current user entry
     userdn = self.searchUserDN(uid)
     r = AF().log(PLUGIN_NAME, AA.SAMBA_ADD_SAMBA_CLASS, [(userdn,AT.USER)])
     s = self.l.search_s(userdn, ldap.SCOPE_BASE)
     c, old = s[0]
     new = self._applyUserDefault(old.copy(), self.configSamba.userDefault)
     if not "sambaSamAccount" in new['objectClass']:
         new['objectClass'].append("sambaSamAccount")
     new["sambaAcctFlags"] = ["[U          ]"]
     new["sambaSID"] = [domainInfo['sambaSID'][0] + '-' + str(int(domainInfo['sambaNextRid'][0]) + 1)]
     # If the passwd has been encoded in the XML-RPC stream, decode it
     if isinstance(password, xmlrpclib.Binary):
         password = str(password)
     # If the passwd is in a dict
     # {'scalar': 'thepassword', 'xmlrpc_type': 'base64'}
     # take scalar
     if isinstance(password, dict):
         password = password['scalar']
     new['sambaLMPassword'] = [smbpasswd.lmhash(password)]
     new['sambaNTPassword'] = [smbpasswd.nthash(password)]
     new['sambaPwdLastSet'] = [str(int(time()))]
     # Update LDAP
     modlist = ldap.modlist.modifyModlist(old, new)
     self.l.modify_s(userdn, modlist)
     self.updateDomainNextRID()
     self.runHook("samba.addsmbattr", uid, password)
     r.commit()
Esempio n. 10
0
 def change_password(cls, self, password):
     if isinstance(password, unicode):
         password = password.encode()
     self.sambaNTPassword=smbpasswd.nthash(password)
     self.sambaLMPassword=smbpasswd.lmhash(password)
     self.sambaPwdMustChange=None
     self.sambaPwdLastSet=datetime.datetime.now()
Esempio n. 11
0
File: views.py Progetto: c-base/cbmi
def password(request):
    """
    View that changes the password on the LDAP server.
    """
    member = retrieve_member(request)

    if request.method == 'POST':
        form = PasswordForm(request.POST, request=request)

        if form.is_valid():
            new_password = form.cleaned_data['password1']

            # change the password for the Wifi
            member.set('sambaLMPassword', smbpasswd.lmhash(new_password))
            member.set('sambaNTPassword', smbpasswd.nthash(new_password))
            member.save()

            # change the LDAP password
            member.change_password(new_password)

            key = store_ldap_password(request, new_password)
            request.session.save()
            new_form = PasswordForm()
            response = render(request, 'password.html',
                {'message': _('Your password was changed. Thank you!'),
                 'form': new_form, 'member': member.to_dict()})
            response.set_cookie('sessionkey', key)
            return response
        else:
            return render(request, 'password.html',
                {'form': form, 'member': member.to_dict()})
    else:
        form = PasswordForm()
        return render(request, 'password.html',
            {'form': form, 'member': member.to_dict()})
Esempio n. 12
0
def mkpasswd(pwd, hash='ssha'):
    """Generate hashed passwords. Originated from mkpasswd in Luma
    """
    alg = {
        'ssha': 'Seeded SHA-1',
        'sha': 'Secure Hash Algorithm',
        'smd5': 'Seeded MD5',
        'md5': 'MD5',
        'crypt': 'Standard unix crypt'
    }
    # Don't add support for sambapasswords unless we're using it
    if (update_sambapassword):
        alg['lmhash'] = 'Lanman hash'
        alg['nthash'] = 'NT Hash'
    if hash not in alg.keys():
        return "Algorithm <%s> not supported in this version." % hash
    else:
        salt = getsalt()
        if hash == "ssha":
            return "{SSHA}" + base64.encodestring(
                sha.new(str(pwd) + salt).digest() + salt)
        elif hash == "sha":
            return "{SHA}" + base64.encodestring(sha.new(str(pwd)).digest())
        elif hash == "md5":
            return "{SHA}" + base64.encodestring(md5.new(str(pwd)).digest())
        elif hash == "smd5":
            return "{SMD%}" + base64.encodestring(
                md5.new(str(pwd) + salt).digest() + salt)
        elif hash == "crypt":
            return "{CRYPT}" + crypt.crypt(str(pwd), getsalt(length=2))
        # nt/lm-hash are used directly in their own password-attributes.. no need to prefix the hash
        elif hash == "lmhash":
            return smbpasswd.lmhash(pwd)
        elif hash == "nthash":
            return smbpasswd.nthash(pwd)
Esempio n. 13
0
def hash_passwd(passwd, hash_type):
    import base64
    hash_type = hash_type.upper()
    if hash_type == "MD5":
        m = hashlib.md5()
        m.update(passwd)
        md5_hash = '{MD5}' + base64.encodestring(m.digest())
        return md5_hash
    elif hash_type == "SMD5":
        m = hashlib.md5()
        salt = get_salt()
        m.update(passwd + salt)
        md5_hash = '{SMD5}' + base64.encodestring(m.digest() + salt)
        return md5_hash
    elif hash_type == "SHA":
        m = hashlib.sha1()
        m.update(passwd)
        sha_hash = '{SHA}' + base64.encodestring(m.digest())
        return sha_hash
    elif hash_type == "SSHA":
        m = hashlib.sha1()
        salt = get_salt()
        m.update(passwd + salt)
        ssha_hash = '{SSHA}' + base64.encodestring(m.digest() + salt)
        return ssha_hash
    elif hash_type == "NT":
        NT_hash = smbpasswd.nthash(passwd)
        return NT_hash
Esempio n. 14
0
File: views.py Progetto: c-base/cbmi
def admin(request):
    admin_member = retrieve_member(request)
    if len(request.user.groups.filter(name__in=['ldap_admins'])) < 1:
        return render(request, 'access_denied.html')
    users = admin_member.list_users()
    if request.method == 'POST':
        form = AdminForm(request.POST, request=request, users=users)

        if form.is_valid():
            new_password = form.cleaned_data['password1']
            admin_member.admin_change_password(form.cleaned_data['username'], new_password)

            member = MemberValues(form.cleaned_data['username'], new_password)
            member.set('sambaLMPassword', smbpasswd.lmhash(new_password))
            member.set('sambaNTPassword', smbpasswd.nthash(new_password))
            member.save()

            new_form = AdminForm(request=request, users=users)
            return render(request, 'admin.html',
                {'message': _('The password for %s was changed. Thank you!' % form.cleaned_data['username']),
                 'form': new_form})
        else:
            return render(request, 'admin.html',
                {'form': form})
    else:
        form = AdminForm(request=request, users=users)
        return render(request, 'admin.html',
            {'form': form})
Esempio n. 15
0
 def set_password(self, password):
     self.password = hash_password(password)
     if settings.GRANADILLA_USE_SAMBA:
         import smbpasswd
         self.samba_ntpassword = smbpasswd.nthash(password)
         self.samba_lmpassword = smbpasswd.lmhash(password)
         self.samba_pwdlastset = int(time.time())
Esempio n. 16
0
def ntpwchk(password, lmhash, nthash):
    """Performs mutation on a cleartext to find it in NT"""
    try:
        import smbpasswd
    except ImportError:
        raise Exception("Requires smbpasswd module. Please install it")

    def generate_perm(word, val):
        for i in range(0,len(word)):
            if (val & 1 << i):
                word = word[:i] + word[i].upper() + word[i+1:]
        return word

    #----------------------------------------------------------------------
    def permutations(word):
        val = 0
        perms = []
        word = word.lower()
        while (val < (1 << len(word))):
            perms.append(generate_perm(word,val))
            val += 1
        return perms

    permutations = permutations(password)

    for mutation in permutations:
        if nthash.upper() == smbpasswd.nthash(mutation):
            return (True, mutation.strip('\n'))

    return (False, None)
Esempio n. 17
0
    def changePasswd(self, user, oldpass, password):
	'''
	check & use self.saveUser to modify user's password
	'''
        status = False
        try:
            with open(SMB_DB) as file:
                lines = file.readlines()
            for line in lines:
                user_info = line.strip().split(':')
                if user in user_info:
                    if smbpasswd.nthash(oldpass) in user_info:
                        if self.saveUser(user, password):
                            status = True
                            msg = ("Changed successfully")
                            break
                        else:
                            msg = ("Failed change")
                            break
                    else:
                        msg = ("Wrong password")
                        break
            return status, msg
        except Exception, e:
            return status, e
Esempio n. 18
0
def ntpwchk(password, lmhash, nthash):
    """Performs mutation on a cleartext to find it in NT"""
    try:
        import smbpasswd
    except ImportError:
        raise Exception("Requires smbpasswd module. Please install it")

    def generate_perm(word, val):
        for i in range(0,len(word)):
            if (val & 1 << i):
                word = word[:i] + word[i].upper() + word[i+1:]
        return word

    #----------------------------------------------------------------------
    def permutations(word):
        val = 0
        perms = []
        word = word.lower()
        while (val < (1 << len(word))):
            perms.append(generate_perm(word,val))
            val += 1
        return perms

    permutations = permutations(password)

    for mutation in permutations:
        if nthash.upper() == smbpasswd.nthash(mutation):
            return (True, mutation.strip('\n'))

    return (False, None)
Esempio n. 19
0
def check_smb_passwd(username, passwd):
    passdb = tdb.open(smb_passdb)
    try:
        user_record = passdb.get("USER_%s\x00" % username.lower())
        if not user_record: return False
        return binascii.a2b_hex(smbpasswd.nthash(passwd)) in user_record
    finally:
        passdb.close()
Esempio n. 20
0
 def _hash_password(self, password):
     """
     Returns a dict of key value pairs where keys are ldap password
     attributes and values are the hashed passwords
     """
     ssha_hash = self._ssha(password)
     nt_hash = smbpasswd.nthash(password)
     return {'sambaNTPassword': nt_hash, 'userPassword': ssha_hash}
Esempio n. 21
0
def ntlm(password):
	"""return tuple with NT and LanMan hash"""

	nt = smbpasswd.nthash(password)

	if configRegistry.is_true('password/samba/lmhash', False):
		lm = smbpasswd.lmhash(password)
	else:
		lm = ''

	return (nt, lm)
Esempio n. 22
0
 def _hash_password(self, password):
     """
     Returns a dict of key value pairs where keys are ldap password
     attributes and values are the hashed passwords
     """
     ssha_hash = self._ssha(password)
     nt_hash = smbpasswd.nthash(password)
     return {
         'sambaNTPassword': nt_hash,
         'userPassword': ssha_hash
     }
Esempio n. 23
0
def ntlm(password):
    """return tuple with NT and LanMan hash"""

    nt = smbpasswd.nthash(password)

    if configRegistry.is_true('password/samba/lmhash', False):
        lm = smbpasswd.lmhash(password)
    else:
        lm = ''

    return (nt, lm)
Esempio n. 24
0
def mkpasswd(pwd, sambaver=3, default="ssha"):
    """ Make a given password cryptated, possibly with different
        crypt-algorihtms. This module was written for use with
	    LDAP - so default is seeded sha
    """
    alg = {"sha": "Secure Hash Algorithm", "ssha": "Seeded SHA", "md5": "MD5", "smd5": "Seeded MD5"}
    if _crypt:
        alg["crypt"] = "standard unix crypt"

    if smb:
        alg["lmhash"] = "lan man hash"
        alg["nthash"] = "nt hash"
    if default not in alg.keys():
        return "algorithm <%s> not supported in this version." % default
    else:
        salt = getsalt()
        if default == "ssha":
            pwString = "{SSHA}" + base64.encodestring(sha.new(str(pwd) + salt).digest() + salt)
            return pwString[:-1]
        elif default == "sha":
            pwString = "{SHA}" + base64.encodestring(sha.new(str(pwd)).digest())
            return pwString[:-1]
        elif default == "md5":
            pwString = "{MD5}" + base64.encodestring(md5.new(str(pwd)).digest())
            return pwString[:-1]
        elif default == "smd5":
            salt = getsalt(length=4)  # Newer versions of OpenLDAP should support the default length 16
            pwString = "{SMD5}" + base64.encodestring(md5.new(str(pwd) + salt).digest() + salt)
            return pwString[:-1]
        elif default == "crypt":
            return "{CRYPT}" + crypt.crypt(str(pwd), getsalt(length=2))  # crypt only uses a salt of length 2
        elif default == "lmhash":
            if sambaver == 3:
                return "{sambaLMPassword}" + smbpasswd.lmhash(pwd)
            elif sambaver == 2:
                return "{lmPassword}" + smbpasswd.lmhash(pwd)
        elif default == "nthash":
            if sambaver == 3:
                return "{sambaNTPassword}" + smbpasswd.nthash(pwd)
            elif sambaver == 2:
                return "{NTPassword}" + smbpasswd.nthash(pwd)
Esempio n. 25
0
    def getHashPasswd(self, password, SecHashAlg):
        """Генерация хеша пароля,

        Поддерживаемые алгоритмы шифрования пароля:
        plain, md5, smd5, crypt, sha, ssha, lm, nt
        """
        if not password:
            print _("ERROR") + " getHashPasswd: " +\
                            _("password empty")
            return False

        hashPwd = ""
        if SecHashAlg == "plain":
            hashPwd = password

        elif SecHashAlg == "md5":
            h = hashlib.md5(password)
            hashPwd = "{MD5}" + b64encode(h.digest())

        elif SecHashAlg == "smd5":
            salt = os.urandom(4)
            h = hashlib.md5(password)
            h.update(salt)
            hashPwd = "{SMD5}" + b64encode(h.digest() + salt)

        elif SecHashAlg == "crypt":
            salt = self.__GenCryptSalt__()
            hashPwd = "{CRYPT}" + crypt.crypt(password, salt)

        elif SecHashAlg == "sha":
            h = hashlib.sha1(password)
            hashPwd = "{SHA}" + b64encode(h.digest())

        elif SecHashAlg == "ssha":
            salt = os.urandom(4)
            h = hashlib.sha1(password)
            h.update(salt)
            hashPwd = "{SSHA}" + b64encode(h.digest() + salt)

        elif SecHashAlg == "lm":
            hashPwd = smbpasswd.lmhash(password)

        elif SecHashAlg == "nt":
            hashPwd = smbpasswd.nthash(password)

        else:
            print _("ERROR") + " getHashPasswd: " +\
                            _("Can not support '%s' crypto algorithm")%SecHashAlg
            return False
        return hashPwd
Esempio n. 26
0
 def nt(self):
     try:
         try:
             import smbpasswd
             hash =  smbpasswd.nthash(self.password)
         except:
             from Crypto.Hash import MD4
             hash = MD4.new(self.password.encode("utf-16-le")).hexdigest().upper()
         self.out['nt'] = {
             'header': '{nt}',
             'salt': None,
             'hash': hash }
         return hash
     except:
         return None
Esempio n. 27
0
 def sambaAuth(self, user, passwd):
     status = False
     try:
         with open(SMB_DB) as file:
             lines = file.readlines()
         for line in lines:
             user_info = line.strip().split(':')
             if user in user_info:
                 if smbpasswd.nthash(passwd) in user_info:
                     return (True, '登陆成功')
                 else:
                     return (False, '您的用户名/密码错误,请检查后重试')
         return (False, '您还没有登陆过本系统,请使用您的邮箱密码登陆')
     except Exception, e:
         return (False, e)
def ntlm(password):
	# type: (str) -> Tuple[str, str]
	"""
	Return tuple with NT and LanMan hash.

	:param password: password string.
	:returns: 2-tuple (NT, LanMan)
	"""
	nt = smbpasswd.nthash(password)

	if configRegistry.is_true('password/samba/lmhash', False):
		lm = smbpasswd.lmhash(password)
	else:
		lm = ''

	return (nt, lm)
Esempio n. 29
0
	def expected_attributes(self):
		attr = dict(
			departmentNumber=[self.school],
			givenName=[self.firstname],
			homeDirectory=[self.homedir],
			krb5KDCFlags=['126'] if self.is_active() else ['254'],
			mail=[self.mail] if self.mail else [],
			mailPrimaryAddress=[self.mail] if self.mail else [],
			sambaAcctFlags=['[U          ]'] if self.is_active() else ['[UD         ]'],
			shadowExpire=[] if self.is_active() else ['1'],
			sn=[self.lastname],
			uid=[self.username],
		)

		if self.source_uid:
			attr['ucsschoolSourceUID'] = [self.source_uid]
		if self.record_uid:
			attr['ucsschoolRecordUID'] = [self.record_uid]
		if self.description:
			attr['description'] = [self.description]
		if not self.legacy:
			attr['ucsschoolSchool'] = self.schools
		if self.password:
			attr['sambaNTPassword'] = [smbpasswd.nthash(self.password)]
		if self.birthday:
			attr['univentionBirthday'] = [self.birthday]

		if not self.is_staff():
			if configRegistry.get('ucsschool/import/set/netlogon/script/path'):
				attr['sambaLogonScript'] = [configRegistry.get('ucsschool/import/set/netlogon/script/path')]
			if configRegistry.get('ucsschool/import/set/homedrive'):
				attr['sambaHomeDrive'] = [configRegistry.get('ucsschool/import/set/homedrive')]

			samba_home_path_server = self.get_samba_home_path_server()
			if samba_home_path_server:
				attr['sambaHomePath'] = ['\\\\%s\\%s' % (samba_home_path_server, self.username)]

			profile_path_server = self.get_profile_path_server()
			if profile_path_server:
				attr['sambaProfilePath'] = [profile_path_server]
		else:
			attr['sambaLogonScript'] = []
			attr['sambaHomeDrive'] = []
			attr['sambaHomePath'] = []
			attr['sambaProfilePath'] = []

		return attr
Esempio n. 30
0
def password(request):
    """
    View that changes the password on the LDAP server.
    """
    member = retrieve_member(request)

    if request.method == 'POST':
        form = PasswordForm(request.POST, request=request)

        if form.is_valid():
            new_password = form.cleaned_data['password1']

            # change the password for the Wifi
            member.set('sambaLMPassword', smbpasswd.lmhash(new_password))
            member.set('sambaNTPassword', smbpasswd.nthash(new_password))
            member.save()

            # change the LDAP password
            member.change_password(new_password)

            key = store_ldap_password(request, new_password)
            request.session.save()
            new_form = PasswordForm()
            response = render(
                request, 'password.html', {
                    'message': _('Your password was changed. Thank you!'),
                    'form': new_form,
                    'member': member.to_dict()
                })
            response.set_cookie('sessionkey', key)
            return response
        else:
            return render(request, 'password.html', {
                'form': form,
                'member': member.to_dict()
            })
    else:
        form = PasswordForm()
        return render(request, 'password.html', {
            'form': form,
            'member': member.to_dict()
        })
Esempio n. 31
0
 def changePasswd(self, user, oldpass, password):
     is_saved = False
     msg = _("User not found")
     try:
         with open(settings.SMB_DB) as file:
             lines = file.readlines()
         for line in lines:
             user_info = line.strip().split(':')
             if user in user_info:
                 if smbpasswd.nthash(oldpass) in user_info:
                     if self.saveUser(user, password):
                         is_saved = True
                         msg = _("Changed successfully")
                         break
                     else:
                         msg = _("Failed change")
                         break
                 else:
                     msg = _("Wrong password")
                     break
         return is_saved, msg
     except Exception, e:
         msg = _("Failed change")
         return is_saved, e
Esempio n. 32
0
 def changePasswd(self, user, oldpass, password):
     is_saved = False
     msg = _("User not found")
     try:
         with open(settings.SMB_DB) as file:
             lines = file.readlines()
         for line in lines:
             user_info = line.strip().split(':')
             if user in user_info:
                 if smbpasswd.nthash(oldpass) in user_info:
                     if self.saveUser(user, password):
                         is_saved = True
                         msg = _("Changed successfully")
                         break
                     else:
                         msg = _("Failed change")
                         break
                 else:
                     msg = _("Wrong password")
                     break
         return is_saved, msg
     except Exception, e:
         msg = _("Failed change")
         return is_saved, e
Esempio n. 33
0
def generateHashNTLM(username):
    emptyLM = 'AAD3B435B51404EEAAD3B435B51404EE'
    if randomNumber <= 3:  # 3%
        password = pass_Username(username)
        print username + ':' + str(
            random.randint(1000, 2000)
        ) + ':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(
            password)
    else:
        if randomNumber <= 6:  # 3%
            password = pass_Password()
            print username + ':' + str(
                random.randint(1000, 2000)
            ) + ':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(
                password)
        else:
            if randomNumber <= 12:  # 6%
                password = pass_DictWord_DigitsFirst()
                print username + ':' + str(
                    random.randint(1000, 2000)
                ) + ':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(
                    password)
            else:
                if randomNumber <= 64:  # 52%
                    password = pass_DictWord()
                    print username + ':' + str(
                        random.randint(1000, 2000)
                    ) + ':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(
                        password)
                else:
                    if randomNumber <= 74:  # 10%
                        password = random_Password_ULD()
                        print username + ':' + str(
                            random.randint(1000, 2000)
                        ) + ':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(
                            password)
                    else:
                        if randomNumber <= 80:  # 6%
                            password = random_ShittyWord()
                            print username + ':' + str(
                                random.randint(1000, 2000)
                            ) + ':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(
                                password)
                        else:
                            if randomNumber <= 87:  # 7%
                                password = random_Password_LD()
                                print username + ':' + str(
                                    random.randint(1000, 2000)
                                ) + ':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(
                                    password)
                            else:
                                if randomNumber <= 88:  # 1%
                                    password = ""
                                    print username + ':' + str(
                                        random.randint(1000, 2000)
                                    ) + ':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(
                                        password)
                                else:
                                    if randomNumber <= 89:  # 1%
                                        password = "******"
                                        print username + ':' + str(
                                            random.randint(1000, 2000)
                                        ) + ':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(
                                            password)
                                    else:
                                        if randomNumber <= 98:  # 9%
                                            password = pass_DictWord_Upper()
                                            try:
                                                print username + ':' + str(
                                                    random.randint(1000, 2000)
                                                ) + 'AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(
                                                    password)
                                            except AttributeError:  # This is in case the word starts with something other than a letter
                                                print username + ':' + str(
                                                    random.randint(1000, 2000)
                                                ) + ':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(
                                                    password)
                                        else:
                                            if randomNumber <= 100:  # 2%
                                                password = random_Password_ULDS(
                                                )
                                                print username + ':' + str(
                                                    random.randint(1000, 2000)
                                                ) + ':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(
                                                    password)
Esempio n. 34
0
            passwd = 'Winter14'
        if count>75 and count<=110:
            passwd = name+'Acme2016'
        if count>110 and count<=130:
            passwd = name+'Acme!'
        if count>130 and count<=150:
            passwd = name+':Acme'
        if count>150 and count<=205:
            passwd = last
        if count>205 and count<=250:
            passwd = name+'Bank!'
        if count>250 and count<=270:     
            passwd = name+'Bank2016\n'
        if count>270 and count<=280:
            passwd = '' 
        if count>280 and count<=298:
            passwd = 'Password'
        if count == 299:
            passwd = 'letmeinAcme'
        if count == 300:
            passwd = 'secret:Acme'
        pair = name + "::" + smbpasswd.lmhash(passwd)+":"+smbpasswd.nthash(passwd)+":::\n" 
        pass_my.write(pair)
        last = name 
    elif count >= 300:
        break
print 'index is %d' % index
print count
pass_john.close()
pass_my.close()
Esempio n. 35
0
import smbpasswd

passwd = 'mypassword'

#print 'LANMAN hash is', smbpasswd.lmhash(passwd)
print 'NT hash is', smbpasswd.nthash(passwd)

print 'both hashes at once = %s:%s' % smbpasswd.hash(passwd)
Esempio n. 36
0
File: pug.py Progetto: bupt007/PUG
def generateHashNTLM(username):
	emptyLM = 'AAD3B435B51404EEAAD3B435B51404EE'
	if randomNumber <=3: # 3%
		password = pass_Username(username)
		print username+':'+str(random.randint(1000,2000))+':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(password)
	else:
		if randomNumber <=6: # 3%
			password = pass_Password()
			print username+':'+str(random.randint(1000,2000))+':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(password)
		else:
			if randomNumber <=12: # 6%
				password = pass_DictWord_DigitsFirst()
				print username+':'+str(random.randint(1000,2000))+':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(password)
			else:
				if randomNumber <=64: # 52%
					password = pass_DictWord()
					print username+':'+str(random.randint(1000,2000))+':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(password)
				else:
					if randomNumber <=74: # 10%
						password = random_Password_ULD()
						print username+':'+str(random.randint(1000,2000))+':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(password)
					else:
						if randomNumber <=80: # 6%
							password = random_ShittyWord()
							print username+':'+str(random.randint(1000,2000))+':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(password)
						else:
							if randomNumber <=87: # 7%
								password = random_Password_LD()
								print username+':'+str(random.randint(1000,2000))+':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(password)
							else:
								if randomNumber <=88: # 1%
									password = ""
									print username+':'+str(random.randint(1000,2000))+':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(password)
								else:
									if randomNumber <=89: # 1%
										password = "******"
										print username+':'+str(random.randint(1000,2000))+':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(password)
									else:
										if randomNumber <=98: # 9%
											password = pass_DictWord_Upper()
											try: print username+':'+str(random.randint(1000,2000))+'AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(password)
											except AttributeError: # This is in case the word starts with something other than a letter
												print username+':'+str(random.randint(1000,2000))+':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(password)
										else:
											if randomNumber <=100: # 2%
												password = random_Password_ULDS()
												print username+':'+str(random.randint(1000,2000))+':AAD3B435B51404EEAAD3B435B51404EE:%s:::' % smbpasswd.nthash(password)
 def update_password_fields(self, password):
     self.google_password = "" + hashlib.sha1(password.encode("utf8")).hexdigest()
     self.samba_password = smbpasswd.nthash(password)
     self.shadow_max = calculate_password_valid_days()
     self.shadow_last_change = (now() - EPOCH).days
Esempio n. 38
0
def test_hash_is_same():
    assert nthash("hoge") == smbpasswd.nthash("hoge")
Esempio n. 39
0
 def update_password_fields(self, password):
     self.google_password = "" + hashlib.sha1(
         password.encode("utf8")).hexdigest()
     self.samba_password = smbpasswd.nthash(password)
     self.shadow_max = calculate_password_valid_days()
     self.shadow_last_change = (now() - EPOCH).days
Esempio n. 40
0
def add_ntlm_hashes(pwds):
    for p in pwds:
        nt = {'plain': p, 'count': 0}
        nt_db.set(smbpasswd.nthash(p).upper(), json.dumps(nt))
Esempio n. 41
0
def generateHashNTLM(username, randomNumber, randomWords):
	if randomNumber <=3: # 3%
		password = pass_Username(username)
		print username+':'+str(random.randint(1000,2000))+':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
	elif randomNumber <=6: # 3%
		password = pass_Password()
		print username+':'+str(random.randint(1000,2000))+':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
	elif randomNumber <=12: # 6%
		password = pass_DictWord_DigitsFirst(randomWords)
		print username+':'+str(random.randint(1000,2000))+':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
	elif randomNumber <=64: # 52%
		password = pass_DictWord(randomWords)
		print username+':'+str(random.randint(1000,2000))+':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
	elif randomNumber <=74: # 10%
		password = random_Password_ULD()
		print username+':'+str(random.randint(1000,2000))+':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
	elif randomNumber <=80: # 6%
		password = random_ShittyWord()
		print username+':'+str(random.randint(1000,2000))+':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
	elif randomNumber <=87: # 7%
		password = random_Password_LD()
		print username+':'+str(random.randint(1000,2000))+':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
	elif randomNumber <=88: # 1%
		password = ""
		print username+':'+str(random.randint(1000,2000))+':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
	elif randomNumber <=89: # 1%
		password = "******"
		print username+':'+str(random.randint(1000,2000))+':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
	elif randomNumber <=98: # 9%
		password = pass_DictWord_Upper(randomWords)
		try: 
			print username+':'+str(random.randint(1000,2000))+'%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
		except AttributeError: # This is in case the word starts with something other than a letter
			print username+':'+str(random.randint(1000,2000))+':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
	elif randomNumber <=100: # 2%
		password = random_Password_ULDS()
		print username+':'+str(random.randint(1000,2000))+':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
Esempio n. 42
0
'''
Created on Oct 12, 2012

@author: tivalat
'''
 
import smbpasswd

passwd = 'mypassword'

print 'LANMAN hash is', smbpasswd.lmhash(passwd)               
print 'NT hash is', smbpasswd.nthash(passwd)

print 'both hashes at once = %s:%s (lm:nt)' % smbpasswd.hash(passwd)
Esempio n. 43
0
import json

if len(sys.argv) != 2:
    print 'USAGE: add_passwords.py file'
    sys.exit()

lm_db = redis.StrictRedis(host='localhost', port=6379, db=1)
nt_db = redis.StrictRedis(host='localhost', port=6379, db=2)


def add_lm_hash(hash, plain):
    # print 'Adding LM hash {0}'.format(hash)
    lm = {'plain': plain, 'count': 0}
    lm_db.set(hash.upper(), json.dumps(lm))


def add_nt_hash(hash, plain):
    # print 'Adding NT hash {0}'.format(hash)
    nt = {'plain': plain, 'count': 0}
    nt_db.set(hash.upper(), json.dumps(nt))

for line in open(sys.argv[1]
):
    line = line.rstrip('\r\n')
    print 'Adding ' + line

    # LM truncates at 14 characters.
    if len(line) <= 14:
        add_lm_hash(smbpasswd.lmhash(line), line)
    add_nt_hash(smbpasswd.nthash(line), line)
Esempio n. 44
0
    def getHashPasswd(self, password, SecHashAlg):
        """Генерация хеша пароля,

        Поддерживаемые алгоритмы шифрования пароля:
        plain, md5, smd5, crypt, sha, ssha, lm, nt, shadow_ssha512,
        shadow_ssha256, shadow_md5
        """
        if not password:
            self.printERROR(_("ERROR") + " getHashPasswd: " +
                            _("empty password"))
            return False

        hashPwd = ""
        if SecHashAlg == "plain":
            hashPwd = password

        elif SecHashAlg == "md5":
            h = hashlib.md5(password)
            hashPwd = "{MD5}" + b64encode(h.digest())

        elif SecHashAlg == "smd5":
            salt = os.urandom(4)
            h = hashlib.md5(password)
            h.update(salt)
            hashPwd = "{SMD5}" + b64encode(h.digest() + salt)

        elif SecHashAlg == "shadow_ssha512":
            salt = self.__GenCryptSalt__(8)
            hashPwd = crypt.crypt(password, "$6$%s$"%salt)

        elif SecHashAlg == "shadow_ssha256":
            salt = self.__GenCryptSalt__(8)
            hashPwd = crypt.crypt(password, "$5$%s$"%salt)

        elif SecHashAlg == "shadow_md5":
            salt = self.__GenCryptSalt__(8)
            hashPwd = crypt.crypt(password, "$1$%s$"%salt)

        elif SecHashAlg == "crypt":
            salt = self.__GenCryptSalt__()
            hashPwd = "{CRYPT}" + crypt.crypt(password, salt)

        elif SecHashAlg == "sha":
            h = hashlib.sha1(password)
            hashPwd = "{SHA}" + b64encode(h.digest())

        elif SecHashAlg == "ssha":
            salt = os.urandom(4)
            h = hashlib.sha1(password)
            h.update(salt)
            hashPwd = "{SSHA}" + b64encode(h.digest() + salt)

        elif SecHashAlg == "lm" and lmhash:
            hashPwd = lmhash(password)
        elif SecHashAlg == "nt" and nthash:
            hashPwd = nthash(password)
        else:
            if SecHashAlg in ("lm","nt"):
                self.printERROR(_("ERROR") + " getHashPasswd: " +
                            (_("Failed to support '%s' crypto algorithm")
                            %SecHashAlg) + " " +  _("without py-smbpasswd"))
            else:
                self.printERROR(_("ERROR") + " getHashPasswd: " +
                            _("Failed to support '%s' crypto algorithm")
                            %SecHashAlg)
            return False
        return hashPwd
Esempio n. 45
0
uid: %(uid)s
cn: %(cn)s
uidNumber: %(uid_num)s
gidNumber: %(uid_num)s
homeDirectory: %(home_dir)s
sambaSID: %(sid)s
sambaNTPassword: %(ntpwd)s
sambaLMPassword: %(lmpwd)s
userPassword: %(pwd)s

"""

n = int(sys.argv.pop(1))

print container_template
for x in range(n):
    secret = 'secret%d' % x
    nt_secret = smbpasswd.nthash(secret)
    lm_secret = smbpasswd.lmhash(secret)
    print user_template % dict(
            uid='uid%d' % x,
            cn='cn%d' % x,
            uid_num=str(x),
            gid_num=str(x),
            home_dir='/home/uid%d' % x,
            sid='12345-%d' % x,
            pwd=secret,
            ntpwd=nt_secret,
            lmpwd=lm_secret,
            ),
Esempio n. 46
0
def sambaNTPassword(passwd):
    return smbpasswd.nthash(passwd)
Esempio n. 47
0
def sambaNTPassword(passwd):              
    return smbpasswd.nthash(passwd)
Esempio n. 48
0
 def authSetSmbPassword(self, username, password):
     '''Set a user's smb password
     '''
     self.config.setVar(
         'user.%s.spasswd' % username,
         '%s:%s' % (smbpasswd.lmhash(password), smbpasswd.nthash(password)))
Esempio n. 49
0
File: pug.py Progetto: karunix/PUG
def generateHashNTLM(username, randomNumber, randomWords):
    if randomNumber <= 3:  # 3%
        password = pass_Username(username)
        print username + ':' + str(random.randint(
            1000, 2000)) + ':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
    elif randomNumber <= 6:  # 3%
        password = pass_Password()
        print username + ':' + str(random.randint(
            1000, 2000)) + ':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
    elif randomNumber <= 12:  # 6%
        password = pass_DictWord_DigitsFirst(randomWords)
        print username + ':' + str(random.randint(
            1000, 2000)) + ':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
    elif randomNumber <= 64:  # 52%
        password = pass_DictWord(randomWords)
        print username + ':' + str(random.randint(
            1000, 2000)) + ':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
    elif randomNumber <= 74:  # 10%
        password = random_Password_ULD()
        print username + ':' + str(random.randint(
            1000, 2000)) + ':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
    elif randomNumber <= 80:  # 6%
        password = random_ShittyWord()
        print username + ':' + str(random.randint(
            1000, 2000)) + ':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
    elif randomNumber <= 87:  # 7%
        password = random_Password_LD()
        print username + ':' + str(random.randint(
            1000, 2000)) + ':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
    elif randomNumber <= 88:  # 1%
        password = ""
        print username + ':' + str(random.randint(
            1000, 2000)) + ':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
    elif randomNumber <= 89:  # 1%
        password = "******"
        print username + ':' + str(random.randint(
            1000, 2000)) + ':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
    elif randomNumber <= 98:  # 9%
        password = pass_DictWord_Upper(randomWords)
        try:
            print username + ':' + str(random.randint(
                1000,
                2000)) + '%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
        except AttributeError:  # This is in case the word starts with something other than a letter
            print username + ':' + str(random.randint(
                1000,
                2000)) + ':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
    elif randomNumber <= 100:  # 2%
        password = random_Password_ULDS()
        print username + ':' + str(random.randint(
            1000, 2000)) + ':%s:%s:::' % (emptyLM, smbpasswd.nthash(password))
Esempio n. 50
0
 def test_nt(self):
     self.assertEqual(smbpasswd.nthash('foo'),
                      'AC8E657F83DF82BEEA5D43BDAF7800CC')
     self.assertEqual(smbpasswd.nthash('passphrase'),
                      '7F8FE03093CC84B267B109625F6BBF4B')