finfake = "" for i in xrange(len(fakeflag)): if random() > 0.5: finfake += fakeflag[i] else: finfake += chr(35) for i in xrange(17): rep = reps[(j * 17) + i] smtpObj.sendmail( sender, rep.name + '@dnc.gov', "Date: 4/" + str(j + 1) + "/16\nEncryption Type: RSA-2048\nContent: " + hex(rep.enc(str(finfake)))[2:-1]) #print "Successfully sent email from " + rep.name + '@dnc.gov' except: print "Error: unable to send email" for line in open("reps.txt", 'rb').readlines(): line = line.split(',') n = int(line[1]) * int(line[2]) pkcs1_seq = univ.Sequence() pkcs1_seq.setComponentByPosition(0, univ.Integer(n)) pkcs1_seq.setComponentByPosition(1, univ.Integer(17)) f = open("../handout/pubkeys/" + line[0], "wb") f.write('-----BEGIN RSA PUBLIC KEY-----\n') f.write(base64.encodestring(der_encoder.encode(pkcs1_seq))) f.write('-----END RSA PUBLIC KEY-----') f.close()
class AuthorizationData(univ.SequenceOf): componentType = univ.Sequence(componentType=namedtype.NamedTypes( _sequence_component('ad-type', 0, Int32()), _sequence_component('ad-data', 1, univ.OctetString())))
class SequenceOrSequenceOfDecoder(UniversalConstructedTypeDecoder): protoRecordComponent = univ.Sequence() protoSequenceComponent = univ.SequenceOf()
CMCStatusInfoV2.componentType = namedtype.NamedTypes( namedtype.NamedType('cMCStatus', CMCStatus()), namedtype.NamedType('bodyList', univ.SequenceOf(componentType=BodyPartReference())), namedtype.OptionalNamedType('statusString', char.UTF8String()), namedtype.OptionalNamedType( 'otherInfo', univ.Choice(componentType=namedtype.NamedTypes( namedtype.NamedType('failInfo', CMCFailInfo()), namedtype.NamedType('pendInfo', PendInfo()), namedtype.NamedType( 'extendedFailInfo', univ.Sequence(componentType=namedtype.NamedTypes( namedtype.NamedType('failInfoOID', univ.ObjectIdentifier( )), namedtype.NamedType('failInfoValue', AttributeValue())))))))) class GetCRL(univ.Sequence): pass GetCRL.componentType = namedtype.NamedTypes( namedtype.NamedType('issuerName', rfc5280.Name()), namedtype.OptionalNamedType('cRLName', rfc5280.GeneralName()), namedtype.OptionalNamedType('time', useful.GeneralizedTime()), namedtype.OptionalNamedType('reasons', rfc5280.ReasonFlags())) id_pkix = _buildOid(1, 3, 6, 1, 5, 5, 7)
def ASN1Sequence(*vals): seq = univ.Sequence() for i in range(len(vals)): seq.setComponentByPosition(i, vals[i]) return seq
def setUp(self): BaseTestCase.setUp(self) self.s = univ.Sequence() self.s.setComponentByPosition(0, univ.Null('')) self.s.setComponentByPosition(1, univ.OctetString('quick brown')) self.s.setComponentByPosition(2, univ.Integer(1))
def addAuthorityInformationAccess(self, ocspURI): sequence = univ.Sequence() accessDescription = stringToAccessDescription(ocspURI) sequence.setComponentByPosition(0, accessDescription) self.addExtension(rfc2459.id_pe_authorityInfoAccess, sequence)
def _toString_OPENSSH(self, extra): """ Return a public or private OpenSSH string. See _fromString_PUBLIC_OPENSSH and _fromString_PRIVATE_OPENSSH for the string formats. If extra is present, it represents a comment for a public key, or a passphrase for a private key. @param extra: Comment for a public key or passphrase for a private key @type extra: L{bytes} @rtype: L{bytes} """ data = self.data() if self.isPublic(): if self.type() == 'EC': if not extra: extra = b'' return (self._keyObject.public_bytes( serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH) + b' ' + extra).strip() b64Data = encodebytes(self.blob()).replace(b'\n', b'') if not extra: extra = b'' return (self.sshType() + b' ' + b64Data + b' ' + extra).strip() else: if self.type() == 'EC': # EC keys has complex ASN.1 structure hence we do this this way. if not extra: # unencrypted private key encryptor = serialization.NoEncryption() else: encryptor = serialization.BestAvailableEncryption(extra) return self._keyObject.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, encryptor) lines = [ b''.join((b'-----BEGIN ', self.type().encode('ascii'), b' PRIVATE KEY-----')) ] if self.type() == 'RSA': p, q = data['p'], data['q'] objData = (0, data['n'], data['e'], data['d'], p, q, data['d'] % (p - 1), data['d'] % (q - 1), data['u']) else: objData = (0, data['p'], data['q'], data['g'], data['y'], data['x']) asn1Sequence = univ.Sequence() for index, value in izip(itertools.count(), objData): asn1Sequence.setComponentByPosition(index, univ.Integer(value)) asn1Data = berEncoder.encode(asn1Sequence) if extra: iv = randbytes.secureRandom(8) hexiv = ''.join(['%02X' % (ord(x), ) for x in iterbytes(iv)]) hexiv = hexiv.encode('ascii') lines.append(b'Proc-Type: 4,ENCRYPTED') lines.append(b'DEK-Info: DES-EDE3-CBC,' + hexiv + b'\n') ba = md5(extra + iv).digest() bb = md5(ba + extra + iv).digest() encKey = (ba + bb)[:24] padLen = 8 - (len(asn1Data) % 8) asn1Data += (chr(padLen) * padLen).encode('ascii') encryptor = Cipher(algorithms.TripleDES(encKey), modes.CBC(iv), backend=default_backend()).encryptor() asn1Data = encryptor.update(asn1Data) + encryptor.finalize() b64Data = encodebytes(asn1Data).replace(b'\n', b'') lines += [b64Data[i:i + 64] for i in range(0, len(b64Data), 64)] lines.append(b''.join((b'-----END ', self.type().encode('ascii'), b' PRIVATE KEY-----'))) return b'\n'.join(lines)
ldap.ExtendedResponse())))), namedtype.OptionalNamedType( 'controls', ldap.Controls().subtype(implicitTag=tag.Tag( tag.tagClassContext, tag.tagFormatConstructed, 0)))) oid2asn = { "1.3.6.1.4.1.42.2.27.9.6.1": { "name": "REPL_TRS_START_REQ_OID", "asn": TRSStartReq(), 'loglevel': INFO }, "1.3.6.1.4.1.42.2.27.9.6.2": { "name": "REPL_TRS_RESUME_REQ_OID", "asn": univ.Sequence(), 'loglevel': INFO }, "1.3.6.1.4.1.42.2.27.9.6.3": { "name": "REPL_TRS_SUSPEND_REQ_OID", "asn": univ.Sequence(), 'loglevel': INFO }, "1.3.6.1.4.1.42.2.27.9.6.4": { "name": "REPL_TRS_ACQUIRE_REQ_OID", "asn": TRSAcquireReq(), 'loglevel': INFO }, "1.3.6.1.4.1.42.2.27.9.6.5": { "name": "REPL_TRS_RELEASE_REQ_OID", "asn": TRSReleaseReq(),
def _stupidAddress(s): res = univ.Sequence(componentType=namedtype.NamedTypes( namedtype.NamedType('ub-postal-string', char.UTF8String()))) res.setComponentByName('ub-postal-string', char.UTF8String(s)) return res
class ExtendedNetworkAddress(univ.Choice): pass ExtendedNetworkAddress.componentType = namedtype.NamedTypes( namedtype.NamedType( 'e163-4-address', univ.Sequence(componentType=namedtype.NamedTypes( namedtype.NamedType( 'number', char.NumericString().subtype( subtypeSpec=constraint.ValueSizeConstraint( 1, ub_e163_4_number_length)).subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), namedtype.OptionalNamedType( 'sub-address', char.NumericString().subtype( subtypeSpec=constraint.ValueSizeConstraint( 1, ub_e163_4_sub_address_length)).subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1)))))), namedtype.NamedType( 'psap-address', PresentationAddress().subtype(implicitTag=tag.Tag( tag.tagClassContext, tag.tagFormatConstructed, 0)))) terminal_type = univ.Integer(23) id_domainComponent = _OID(0, 9, 2342, 19200300, 100, 1, 25)
class RafDeliveryMode(DeliveryMode): pass class RafGetParameter(univ.Choice): pass RafGetParameter.componentType = namedtype.NamedTypes( namedtype.NamedType( 'parBufferSize', univ.Sequence(componentType=namedtype.NamedTypes( namedtype.NamedType('parameterName', ParameterName()), namedtype.NamedType('parameterValue', IntPosShort()))).subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))), namedtype.NamedType( 'parDeliveryMode', univ.Sequence(componentType=namedtype.NamedTypes( namedtype.NamedType('parameterName', ParameterName()), namedtype.NamedType('parameterValue', RafDeliveryMode()))).subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1))), namedtype.NamedType( 'parLatencyLimit', univ.Sequence(componentType=namedtype.NamedTypes( namedtype.NamedType('parameterName', ParameterName()), namedtype.NamedType( 'parameterValue',
def create_rsa(self, output): """Create RSA SSH key file""" if self.mem[0:7] == "ssh-rsa": # FIXME: This needs to be cleaned up. start = 10 size = self.unpack_bigint(self.mem[start:(start + 2)]) start += 2 n = self.unpack_bigint(self.mem[start:(start + size)]) start = start + size + 2 size = self.unpack_bigint(self.mem[start:(start + 2)]) start += 2 e = self.unpack_bigint(self.mem[start:(start + size)]) start = start + size + 2 size = self.unpack_bigint(self.mem[start:(start + 2)]) start += 2 d = self.unpack_bigint(self.mem[start:(start + size)]) start = start + size + 2 size = self.unpack_bigint(self.mem[start:(start + 2)]) start += 2 c = self.unpack_bigint(self.mem[start:(start + size)]) start = start + size + 2 size = self.unpack_bigint(self.mem[start:(start + 2)]) start += 2 p = self.unpack_bigint(self.mem[start:(start + size)]) start = start + size + 2 size = self.unpack_bigint(self.mem[start:(start + 2)]) start += 2 q = self.unpack_bigint(self.mem[start:(start + size)]) e1 = d % (p - 1) e2 = d % (q - 1) self.mem = self.mem[start + size:] else: print("Error: This is not a RSA SSH key file") sys.exit(2) seq = ( univ.Integer(0), univ.Integer(n), univ.Integer(e), univ.Integer(d), univ.Integer(p), univ.Integer(q), univ.Integer(e1), univ.Integer(e2), univ.Integer(c), ) struct = univ.Sequence() for i in xrange(len(seq)): struct.setComponentByPosition(i, seq[i]) raw = encoder.encode(struct) data = base64.b64encode(raw) # chop data up into lines of certain width width = 64 chopped = [data[i:i + width] for i in xrange(0, len(data), width)] # assemble file content content = """-----BEGIN RSA PRIVATE KEY----- %s -----END RSA PRIVATE KEY----- """ % '\n'.join(chopped) output = open(output, 'w') output.write(content) output.close()
class AttributeList(univ.SequenceOf): componentType = univ.Sequence(componentType=namedtype.NamedTypes( namedtype.NamedType('type', AttributeDescription()), namedtype.NamedType('vals', univ.SetOf( componentType=AttributeValue()))))
def testValues(self): s = univ.Sequence() s.setComponentByPosition(0, univ.OctetString('abc')) s.setComponentByPosition(1, univ.Integer(123)) assert list(s.values()) == [str2octs('abc'), 123]
def extractRSAKey(data): keybytes = base64.b64decode(data) offset = keybytes.find(b"ssh-rsa") if not offset: print("[!] No valid RSA key found") return None keybytes = keybytes[offset:] # This code is re-implemented code originally written by soleblaze in sshkey-grab start = 10 size = getInt(keybytes[start:(start + 2)]) # size = unpack_bigint(keybytes[start:(start+2)]) start += 2 n = getInt(keybytes[start:(start + size)]) start = start + size + 2 size = getInt(keybytes[start:(start + 2)]) start += 2 e = getInt(keybytes[start:(start + size)]) start = start + size + 2 size = getInt(keybytes[start:(start + 2)]) start += 2 d = getInt(keybytes[start:(start + size)]) start = start + size + 2 size = getInt(keybytes[start:(start + 2)]) start += 2 c = getInt(keybytes[start:(start + size)]) start = start + size + 2 size = getInt(keybytes[start:(start + 2)]) start += 2 p = getInt(keybytes[start:(start + size)]) start = start + size + 2 size = getInt(keybytes[start:(start + 2)]) start += 2 q = getInt(keybytes[start:(start + size)]) e1 = d % (p - 1) e2 = d % (q - 1) keybytes = keybytes[start + size:] seq = ( univ.Integer(0), univ.Integer(n), univ.Integer(e), univ.Integer(d), univ.Integer(p), univ.Integer(q), univ.Integer(e1), univ.Integer(e2), univ.Integer(c), ) struct = univ.Sequence() for i in range(len(seq)): struct.setComponentByPosition(i, seq[i]) raw = encoder.encode(struct) data = base64.b64encode(raw).decode('utf-8') width = 64 chopped = [data[i:i + width] for i in range(0, len(data), width)] top = "-----BEGIN RSA PRIVATE KEY-----\n" content = "\n".join(chopped) bottom = "\n-----END RSA PRIVATE KEY-----" return top + content + bottom
def testItems(self): s = univ.Sequence() s.setComponentByPosition(0, univ.OctetString('abc')) s.setComponentByPosition(1, univ.Integer(123)) assert list(s.items()) == [('field-0', str2octs('abc')), ('field-1', 123)]
def BuildPkinit_pa(user_cert, cert_pass, reqbodyHex, diffieHellmanExchange): paAsReq = PA_PK_AS_REQ() timestamp = (datetime.datetime.utcnow().isoformat()[:-7] + 'Z').replace( '-', '').replace(':', '').replace('T', '') authpack = AuthPack() checksum = hashlib.sha1(reqbodyHex).hexdigest() authpack['pkAuthenticator']['cusec'] = 275425 authpack['pkAuthenticator']['ctime'] = timestamp authpack['pkAuthenticator']['nonce'] = 0 authpack['pkAuthenticator']['paChecksum'] = bytearray.fromhex( checksum) #reqBodyChecksum aidentifier2 = AlgorithmIdentifier() seq = univ.Sequence(componentType=namedtype.NamedTypes( namedtype.NamedType('1', univ.Integer()), namedtype.NamedType( '2', univ.Integer()))) # public key for DH y = g^x mod p # longPrime- n or p seq['1'] = int( '00ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff', 16) # safe prime # generator- g seq['2'] = 2 aidentifier2['algorithm'] = '1.2.840.10046.2.1' aidentifier2['parameters'] = seq # client public key as g^privateKey mod n subjectPublicKey = '0e64a81b095929c181cf8037ef49d5b12ac1e1b192b58b3309c1165d5a42f1e588973bc41a47381c1347f72e9573c1458bb1e818a1b03036860ac539e081461eaab3c80c6099ea8c1552f0b146f125f300da3e776b3b298d31b5a564a26918bbe1d1f3a9aafea80f2b6bb20327aeb6e4c61ab6d55d412d2e2290f73b10937b69' sub = '80000000000000000000000000000000000' subjectPublicKeyHex = '038184000281800e64a81b095929c181cf8037ef49d5b12ac1e1b192b58b3309c1165d5a42f1e588973bc41a47381c1347f72e9573c1458bb1e818a1b03036860ac539e081461eaab3c80c6099ea8c1552f0b146f125f300da3e776b3b298d31b5a564a26918bbe1d1f3a9aafea80f2b6bb20327aeb6e4c61ab6d55d412d2e2290f73b10937b69' # added BitString - 03 and then sizes 81, 85 and encapsulation 00 to Integer encodedPublic = encode( univ.Integer( diffieHellmanExchange[1].public_key().public_numbers().y)).encode( 'hex') sizeWithoutTags = str( hex( len( hex(diffieHellmanExchange[1].public_key().public_numbers().y) [2:-1]) / 2 + 1)[2:]) sizeWithTags = str(hex(len(encodedPublic) / 2 + 1)[2:]) #sizeWithoutTags encodedPublic = '03' + '81' + sizeWithTags + '00' + encodedPublic authpack['clientPublicValue']['algorithm'] = aidentifier2 authpack['clientPublicValue']['subjectPublicKey'] = bytearray.fromhex( encodedPublic) dhNonce = '6B328FA66EEBDFD3D69ED34E5007776AB30832A2ED1DCB1699781BFE0BEDF87A' authpack['clientDHNonce'] = bytearray.fromhex(dhNonce) authPackData = encode(authpack).encode('hex') return sign_msg(user_cert, cert_pass, authPackData)
pass TerseOrVerbose.namedValues = namedval.NamedValues( ('terse', 1), ('verbose', 2) ) class HardwareSerialEntry(univ.Choice): pass HardwareSerialEntry.componentType = namedtype.NamedTypes( namedtype.NamedType('all', univ.Null()), namedtype.NamedType('single', univ.OctetString()), namedtype.NamedType('block', univ.Sequence(componentType=namedtype.NamedTypes( namedtype.NamedType('low', univ.OctetString()), namedtype.NamedType('high', univ.OctetString()) )) ) ) class HardwareModules(univ.Sequence): pass HardwareModules.componentType = namedtype.NamedTypes( namedtype.NamedType('hwType', univ.ObjectIdentifier()), namedtype.NamedType('hwSerialEntries', univ.SequenceOf( componentType=HardwareSerialEntry()).subtype( subtypeSpec=constraint.ValueSizeConstraint(1, MAX))) )
def build(self): seq = univ.Sequence() seq.setComponentByPosition( 0, univ.Boolean(self.value, tagSet=getBooleanTagSet(0))) return [128, encoder.encode(seq)]
def setUp(self): self.s1 = univ.Sequence(componentType=namedtype.NamedTypes( namedtype.NamedType('name', univ.OctetString('')), namedtype.OptionalNamedType('nick', univ.OctetString('')), namedtype.DefaultedNamedType('age', univ.Integer(34))))
def getSeqApplicationTagSet(n): return univ.Sequence().getTagSet() + tag.Tag( tagClass=64, tagFormat=32, tagId=n)
class _SubjectPublicKeyInfo(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('algorithm', univ.Sequence()), namedtype.NamedType('subjectPublicKey', univ.BitString()))
def getSequenceTagSet(n): return univ.Sequence().getTagSet() + tag.Tag( tagClass=128, tagFormat=32, tagId=n)
def setUp(self): self.s = univ.Sequence(componentType=namedtype.NamedTypes( namedtype.NamedType('place-holder', univ.Null(null)), namedtype.OptionalNamedType('first-name', univ.OctetString(null)), namedtype.DefaultedNamedType('age', univ.Integer(33)), ))
class SequenceDecoder(AbstractDecoder): protoComponent = univ.Sequence() def _getAsn1SpecByPosition(self, t, idx): if t.getComponentType() is not None: if hasattr(t, 'getComponentTypeMapNearPosition'): return t.getComponentTypeMapNearPosition(idx) # Sequence elif hasattr(t, 'getComponentType'): # XXX return t.getComponentType() # SequenceOf # or no asn1Specs def _getPositionByType(self, t, c, idx): if t.getComponentType() is not None: if hasattr(t, 'getComponentPositionNearType'): effectiveTagSet = getattr( c, 'getEffectiveTagSet', c.getTagSet )() return t.getComponentPositionNearType(effectiveTagSet, idx) # Sequence return idx # SequenceOf or w/o asn1Specs def valueDecoder(self, substrate, asn1Spec, tagSet, length, state, decodeFun): r = self._createComponent(tagSet, asn1Spec) idx = 0 if not decodeFun: return r, substrate while substrate: asn1Spec = self._getAsn1SpecByPosition(r, idx) component, substrate = decodeFun( substrate, asn1Spec ) idx = self._getPositionByType(r, component, idx) r.setComponentByPosition(idx, component) idx = idx + 1 if hasattr(r, 'setDefaultComponents'): r.setDefaultComponents() r.verifySizeSpec() return r, substrate def indefLenValueDecoder(self, substrate, asn1Spec, tagSet, length, state, decodeFun): r = self._createComponent(tagSet, asn1Spec) idx = 0 while substrate: try: asn1Spec = self._getAsn1SpecByPosition(r, idx) except error.PyAsn1Error: asn1Spec = None # XXX if not decodeFun: return r, substrate component, substrate = decodeFun(substrate, asn1Spec) if component == eoo.endOfOctets: break idx = self._getPositionByType(r, component, idx) r.setComponentByPosition(idx, component) idx = idx + 1 else: raise error.SubstrateUnderrunError( 'No EOO seen before substrate ends' ) if hasattr(r, 'setDefaultComponents'): r.setDefaultComponents() r.verifySizeSpec() return r, substrate
class LastReq(univ.SequenceOf): componentType = univ.Sequence(componentType=namedtype.NamedTypes( _sequence_component('lr-type', 0, Int32()), _sequence_component('lr-value', 1, KerberosTime())))
def testKeys(self): s = univ.Sequence() s.setComponentByPosition(0, univ.OctetString('abc')) s.setComponentByPosition(1, univ.Integer(123)) assert list(s.keys()) == ['field-0', 'field-1']
class SequenceDecoder(SequenceOrSequenceOfDecoder): protoComponent = univ.Sequence()
def testUninitializedOptionalOctetStringIsNotEncoded(self): self.s = univ.Sequence(componentType=namedtype.NamedTypes( namedtype.OptionalNamedType('str', univ.OctetString()))) self.s.clear() assert encoder.encode(self.s) == ints2octs((48, 0))