def authenticate_owner_password(self, password):
# Algorithm 3.7
password = (password + self.PASSWORD_PADDING)[:32]
hash = md5.md5(password)
if self.r >= 3:
for _ in range(50):
hash = md5.md5(hash.digest())
n = 5
if self.r >= 3:
n = self.length // 8
key = hash.digest()[:n]
if self.r == 2:
user_password = ARC4.new(key).decrypt(self.o)
else:
user_password = self.o
for i in range(19, -1, -1):
k = b''.join(chr(ord(c) ^ i) for c in key)
user_password = ARC4.new(k).decrypt(user_password)
return self.authenticate_user_password(user_password)
python类new()的实例源码
def authenticate(self, password):
password = password.encode('utf-8')[:127]
hash = SHA256.new(password)
hash.update(self.o_validation_salt)
hash.update(self.u)
if hash.digest() == self.o_hash:
hash = SHA256.new(password)
hash.update(self.o_key_salt)
hash.update(self.u)
return AES.new(hash.digest(), mode=AES.MODE_CBC, IV=b'\x00' * 16).decrypt(self.oe)
hash = SHA256.new(password)
hash.update(self.u_validation_salt)
if hash.digest() == self.u_hash:
hash = SHA256.new(password)
hash.update(self.u_key_salt)
return AES.new(hash.digest(), mode=AES.MODE_CBC, IV=b'\x00' * 16).decrypt(self.ue)
return None
def decrypt_secret(secret, key):
"""Python implementation of SystemFunction005.
Decrypts a block of data with DES using given key.
Note that key can be longer than 7 bytes."""
decrypted_data = ''
j = 0 # key index
for i in range(0, len(secret), 8):
enc_block = secret[i:i + 8]
block_key = key[j:j + 7]
des_key = hashdump.str_to_key(block_key)
des = DES.new(des_key, DES.MODE_ECB)
decrypted_data += des.decrypt(enc_block)
j += 7
if len(key[j:j + 7]) < 7:
j = len(key[j:j + 7])
(dec_data_len,) = struct.unpack("<L", decrypted_data[:4])
return decrypted_data[8:8 + dec_data_len]
def GSS_GetMIC(self, sessionKey, data, sequenceNumber, direction = 'init'):
GSS_GETMIC_HEADER = '\x60\x23\x06\x09\x2a\x86\x48\x86\xf7\x12\x01\x02\x02'
token = self.MIC()
# Let's pad the data
pad = (4 - (len(data) % 4)) & 0x3
padStr = chr(pad) * pad
data += padStr
token['SGN_ALG'] = GSS_HMAC
if direction == 'init':
token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + '\x00'*4
else:
token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + '\xff'*4
Ksign = HMAC.new(sessionKey.contents, 'signaturekey\0', MD5).digest()
Sgn_Cksum = MD5.new( struct.pack('<L',15) + str(token)[:8] + data).digest()
Sgn_Cksum = HMAC.new(Ksign, Sgn_Cksum, MD5).digest()
token['SGN_CKSUM'] = Sgn_Cksum[:8]
Kseq = HMAC.new(sessionKey.contents, struct.pack('<L',0), MD5).digest()
Kseq = HMAC.new(Kseq, token['SGN_CKSUM'], MD5).digest()
token['SND_SEQ'] = ARC4.new(Kseq).encrypt(token['SND_SEQ'])
finalData = GSS_GETMIC_HEADER + token.getData()
return finalData
def decrypt(cls, key, keyusage, ciphertext):
if len(ciphertext) < 24:
raise ValueError('ciphertext too short')
cksum, basic_ctext = ciphertext[:16], ciphertext[16:]
ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()
ke = HMAC.new(ki, cksum, MD5).digest()
basic_plaintext = ARC4.new(ke).decrypt(basic_ctext)
exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()
ok = _mac_equal(cksum, exp_cksum)
if not ok and keyusage == 9:
# Try again with usage 8, due to RFC 4757 errata.
ki = HMAC.new(key.contents, pack('<I', 8), MD5).digest()
exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()
ok = _mac_equal(cksum, exp_cksum)
if not ok:
raise InvalidChecksum('ciphertext integrity failure')
# Discard the confounder.
return basic_plaintext[8:]
def ComputeSessionKeyStrongKey(sharedSecret, clientChallenge, serverChallenge, sharedSecretHash = None):
# added the ability to receive hashes already
if sharedSecretHash is None:
M4SS = ntlm.NTOWFv1(sharedSecret)
else:
M4SS = sharedSecretHash
md5 = hashlib.new('md5')
md5.update('\x00'*4)
md5.update(clientChallenge)
md5.update(serverChallenge)
finalMD5 = md5.digest()
hm = hmac.new(M4SS)
hm.update(finalMD5)
return hm.digest()
def DecryptAttributeValue(dce, attribute):
sessionKey = dce.get_session_key()
# Is it a Kerberos Session Key?
if isinstance(sessionKey, crypto.Key):
# Extract its contents and move on
sessionKey = sessionKey.contents
encryptedPayload = ENCRYPTED_PAYLOAD(attribute)
md5 = hashlib.new('md5')
md5.update(sessionKey)
md5.update(encryptedPayload['Salt'])
finalMD5 = md5.digest()
cipher = ARC4.new(finalMD5)
plainText = cipher.decrypt(attribute[16:])
#chkSum = (binascii.crc32(plainText[4:])) & 0xffffffff
#if unpack('<L',plainText[:4])[0] != chkSum:
# print "RECEIVED 0x%x" % unpack('<L',plainText[:4])[0]
# print "CALCULATED 0x%x" % chkSum
return plainText[4:]
# 5.16.4 ATTRTYP-to-OID Conversion
def __decryptSecret(self, key, value):
# [MS-LSAD] Section 5.1.2
plainText = ''
encryptedSecretSize = unpack('<I', value[:4])[0]
value = value[len(value)-encryptedSecretSize:]
key0 = key
for i in range(0, len(value), 8):
cipherText = value[:8]
tmpStrKey = key0[:7]
tmpKey = self.__cryptoCommon.transformKey(tmpStrKey)
Crypt1 = DES.new(tmpKey, DES.MODE_ECB)
plainText += Crypt1.decrypt(cipherText)
key0 = key0[7:]
value = value[8:]
# AdvanceKey
if len(key0) < 7:
key0 = key[len(key0):]
secret = LSA_SECRET_XP(plainText)
return secret['Secret']
def __decryptLSA(self, value):
if self.__vistaStyle is True:
# ToDo: There could be more than one LSA Keys
record = LSA_SECRET(value)
tmpKey = self.__sha256(self.__bootKey, record['EncryptedData'][:32])
plainText = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:])
record = LSA_SECRET_BLOB(plainText)
self.__LSAKey = record['Secret'][52:][:32]
else:
md5 = hashlib.new('md5')
md5.update(self.__bootKey)
for i in range(1000):
md5.update(value[60:76])
tmpKey = md5.digest()
rc4 = ARC4.new(tmpKey)
plainText = rc4.decrypt(value[12:60])
self.__LSAKey = plainText[0x10:0x20]
def test_MimiCommand(self):
dce, rpctransport, pHandle, key = self.connect()
from Crypto.Cipher import ARC4
cipher = ARC4.new(key[::-1])
command = cipher.encrypt('token::whoami\x00'.encode('utf-16le'))
#command = cipher.encrypt('sekurlsa::logonPasswords\x00'.encode('utf-16le'))
#command = cipher.encrypt('process::imports\x00'.encode('utf-16le'))
request = mimilib.MimiCommand()
request['phMimi'] = pHandle
request['szEncCommand'] = len(command)
request['encCommand'] = list(command)
resp = dce.request(request)
cipherText = ''.join(resp['encResult'])
cipher = ARC4.new(key[::-1])
plain = cipher.decrypt(cipherText)
print '='*80
print plain
#resp.dump()
def SEALKEY(flags, randomSessionKey, mode = 'Client'):
if flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:
if flags & NTLMSSP_NEGOTIATE_128:
sealKey = randomSessionKey
elif flags & NTLMSSP_NEGOTIATE_56:
sealKey = randomSessionKey[:7]
else:
sealKey = randomSessionKey[:5]
if mode == 'Client':
md5 = hashlib.new('md5')
md5.update(sealKey + 'session key to client-to-server sealing key magic constant\x00')
sealKey = md5.digest()
else:
md5 = hashlib.new('md5')
md5.update(sealKey + 'session key to server-to-client sealing key magic constant\x00')
sealKey = md5.digest()
elif flags & NTLMSSP_NEGOTIATE_56:
sealKey = randomSessionKey[:7] + '\xa0'
else:
sealKey = randomSessionKey[:5] + '\xe5\x38\xb0'
return sealKey
def decrypt_single_hash(rid, hbootkey, enc_hash, lmntstr):
(des_k1,des_k2) = sid_to_key(rid)
d1 = DES.new(des_k1, DES.MODE_ECB)
d2 = DES.new(des_k2, DES.MODE_ECB)
md5 = MD5.new()
md5.update(hbootkey[:0x10] + pack("<L",rid) + lmntstr)
rc4_key = md5.digest()
rc4 = ARC4.new(rc4_key)
obfkey = rc4.encrypt(enc_hash)
hash = d1.decrypt(obfkey[:8]) + d2.decrypt(obfkey[8:])
return hash
def authenticate_user(self):
# we should check to see if we are already authenticated before blindly
# doing it again
if CoprHDCLIDriver.AUTHENTICATED is False:
utils.COOKIE = None
objauth = auth.Authentication(
self.coprhdhost,
self.port)
cookiedir = self.cookiedir
if( (self.coprhdcli_security_file is not '')
and (self.coprhdcli_security_file is not None)):
from Crypto.Cipher import ARC4
import getpass
objarc = ARC4.new(getpass.getuser())
security_file = open(self.coprhdcli_security_file, 'r')
cipher_text = security_file.readline().rstrip()
self.username = objarc.decrypt(cipher_text)
cipher_text = security_file.readline().rstrip()
self.password = objarc.decrypt(cipher_text)
security_file.close()
objauth.authenticate_user(self.username,
self.password,
cookiedir,
None)
CoprHDCLIDriver.AUTHENTICATED = True
def get_volume_lunid(self, vol):
self.authenticate_user()
Message.new(Info="coprhd-get_volume_lunid" + vol).write(_logger)
try:
volumeuri = self.volume_obj.volume_query(
self.tenant +
"/" +
self.project
+ "/" + vol)
if not volumeuri:
return
volumedetails = self.volume_obj.show_by_uri(volumeuri)
groupdetails = self.exportgroup_obj.exportgroup_show(
self.hostexportgroup,
self.project,
self.tenant)
exportedvolumes = groupdetails['volumes']
Message.new(Info="coprhd-get_volume_lunid for loop").write(_logger)
for evolumes in exportedvolumes:
if volumeuri == evolumes['id']:
return evolumes['lun']
return
except utils.SOSError as e:
if e.err_code == utils.SOSError.NOT_FOUND_ERR:
Message.new(Debug="Volume : doesnot exist").write(_logger)
elif(e.err_code == utils.SOSError.HTTP_ERR):
raise utils.SOSError(
utils.SOSError.HTTP_ERR,
"coprhd get volume lunid http error" + e.err_text)
elif(e.err_code == utils.SOSError.SOS_FAILURE_ERR):
raise utils.SOSError(
utils.SOSError.SOS_FAILURE_ERR,
"coprhd get volume lunid failed" + e.err_text)
else:
Message.new(Debug="coprhd-get_volume_lunid failed").write(_logger)
def get_volume_wwn(self, vol):
self.authenticate_user()
Message.new(Info="coprhd-get_volume_wwn" + vol).write(_logger)
try:
volumeuri = self.volume_obj.volume_query(
self.tenant +
"/" +
self.project
+ "/" + vol)
if not volumeuri:
return
volumedetails = self.volume_obj.show_by_uri(volumeuri)
groupdetails = self.exportgroup_obj.exportgroup_show(
self.hostexportgroup,
self.project,
self.tenant)
exportedvolumes = groupdetails['volumes']
Message.new(Info="coprhd-get_volume_wwn for loop").write(_logger)
for evolumes in exportedvolumes:
if volumeuri == evolumes['id']:
return volumedetails['wwn']
return
except utils.SOSError as e:
if e.err_code == utils.SOSError.NOT_FOUND_ERR:
Message.new(Debug="Volume : doesnot exist").write(_logger)
return None
elif(e.err_code == utils.SOSError.HTTP_ERR):
raise utils.SOSError(
utils.SOSError.HTTP_ERR,
"coprhd get volume wwn http error" + e.err_text)
elif(e.err_code == utils.SOSError.SOS_FAILURE_ERR):
raise utils.SOSError(
utils.SOSError.SOS_FAILURE_ERR,
"coprhd get volume wwn details failed" + e.err_text)
else:
Message.new(Debug="coprhd-get_volume_wwn failed").write(_logger)
def get_volume_details(self, vol):
self.authenticate_user()
volume_dict = {}
Message.new(Info="coprhd-get-volume-details" + vol).write(_logger)
try:
volumeuri = self.volume_obj.volume_query(
self.tenant +
"/" +
self.project
+ "/" + vol)
if not volumeuri:
return
volumedetails = self.volume_obj.show_by_uri(volumeuri)
groupdetails = self.exportgroup_obj.exportgroup_show(
self.hostexportgroup,
self.project,
self.tenant)
exportedvolumes = groupdetails['volumes']
Message.new(Info="coprhd-get-volume-details for loop").write(_logger)
for evolumes in exportedvolumes:
if volumeuri == evolumes['id']:
volume_dict[volumedetails['name'][8:]]={'size':volumedetails['provisioned_capacity_gb'],'attached_to':self.host}
return volume_dict
volume_dict[volumedetails['name'][8:]]={'size':volumedetails['provisioned_capacity_gb'],'attached_to':None}
return volume_dict
except utils.SOSError as e:
if e.err_code == utils.SOSError.NOT_FOUND_ERR:
Message.new(Debug="Volume : doesnot exist").write(_logger)
elif(e.err_code == utils.SOSError.HTTP_ERR):
raise utils.SOSError(
utils.SOSError.HTTP_ERR,
"coprhd get volume http error" + e.err_text)
elif(e.err_code == utils.SOSError.SOS_FAILURE_ERR):
raise utils.SOSError(
utils.SOSError.SOS_FAILURE_ERR,
"coprhd get volume details failed" + e.err_text)
else:
Message.new(Debug="coprhd get volume details failed").write(_logger)
def add_initiators(self,sync, hostlabel, protocol, portwwn,initname):
self.authenticate_user()
portwwn = None
try:
f = open ('/etc/iscsi/initiatorname.iscsi','r')
for line in f:
if ( line[0] != '#' ):
s1=line.split('=')
portwwn = str(s1[1])
if "\n" in portwwn:
portwwn = portwwn.split('\n')[0]
break
initname = portwwn
initiatorwwn = None
self.hostinitiator_obj.create(sync,hostlabel,protocol,initiatorwwn,portwwn)
except utils.SOSError as e:
if(e.err_code == utils.SOSError.HTTP_ERR):
if(e.err_text.find('same Initiator Port already exists') != -1):
Message.new(Debug="coprhd add initiators already added").write(_logger)
else:
raise utils.SOSError(
utils.SOSError.HTTP_ERR,
"coprhd add initiators HTTP_ERR" + e.err_text)
elif(e.err_code == utils.SOSError.SOS_FAILURE_ERR):
raise utils.SOSError(
utils.SOSError.SOS_FAILURE_ERR,
"coprhd add initiators failed" + e.err_text)
else:
Message.new(Debug="coprhd add initiators failed").write(_logger)
def create_network(self,name,nwtype):
self.authenticate_user()
try:
networkid = self.network_obj.query_by_name(name)
if networkid:
Message.new(Debug="Network Already Exists").write(_logger)
else:
self.network_obj.create(name,nwtype)
"Adding Host Ports to Network"
f = open ('/etc/iscsi/initiatorname.iscsi','r')
for line in f:
if line[0] != '#':
current_line=line.split('=')
host_port = current_line[1]
if "\n" in host_port[1]:
host_port = host_port.split('\n')[0]
tz = self.network_obj.show(name)
if ("endpoints" in tz):
endpoints = tz['endpoints']
if host_port not in endpoints:
self.network_obj.add_endpoint(name,endpoint=host_port)
break
except utils.SOSError as e:
if(e.err_code == utils.SOSError.HTTP_ERR):
raise utils.SOSError(
utils.SOSError.HTTP_ERR,
"coprhd create network HTTP_ERR" + e.err_text)
elif(e.err_code == utils.SOSError.SOS_FAILURE_ERR):
raise utils.SOSError(
utils.SOSError.SOS_FAILURE_ERR,
"coprhd create network failed" + e.err_text)
else:
Message.new(Debug="coprhd create network failed").write(_logger)