Example #1
0
    def __saveResponse(self, recv):
        # decode from application/x-www-form-urlencoded
        self.__response = {}
        
        for pair in urlparse.parse_qsl(recv):
            if pair[0] in self.__response:
                raise TestFailed("Received several fields with key %s"%(pair[0]))

            self.__response[pair[0]] = pair[1]

        print ""
        print "Response from server:"
        for k, v in self.__response.iteritems():
            print "%s=%s"%(k, v)

        # check signature of response

        # "openssl dgst -sha1 -verify ../resources/server_publickey.pem 
        #    -signature signature.txt message.txt"

        sortedKeys = sorted(self.__response.keys())
        sortedTuples = [(key, self.__response[key]) for key in sortedKeys]

        msg = ""
        for key in sortedKeys:
            # ; in value must be replaced with ;;
            if not 'signature' in key:
                msg += "%s=%s;"%(key, self.__response[key].replace(';',';;'))
        
        if 's-t-256-256_signature-one' in self.__response:
            signatureBytes = binascii.a2b_hex(self.__response['s-t-256-256_signature-one'])
            
            keyPath = os.path.join(os.path.dirname(__file__), 'server_publickey.pem')
            pkey = RSA.load_pub_key(keyPath)
            
            result = None
            try:
                result = pkey.verify(hashlib.sha1(msg.encode('utf-8')).digest(), 
                                            signatureBytes, algo='sha1')
            except Exception as e:
                raise TestFailed("Response sha1 validation failed: " + str(e))

            if not result:
                raise TestFailed("Response sha1 validation failed.")

        if 's-t-256-256_signature-two' in self.__response:
            signatureBytes = binascii.a2b_hex(self.__response['s-t-256-256_signature-two'])
            
            keyPath = os.path.join(os.path.dirname(__file__), 'server_publickey.pem')
            pkey = RSA.load_pub_key(keyPath)

            result = None
            try:
                result = pkey.verify(hashlib.sha512(msg.encode('utf-8')).digest(), 
                                            signatureBytes, algo='sha512')
            except Exception as e:
                raise TestFailed("Response sha512 validation failed: " + str(e))

            if not result:
                raise TestFailed("Response sha512 validation failed.")
Example #2
0
def m2c_key(arg1, arg2):
    try:
        rsa = RSA.gen_key(1024, 3, lambda *agr:None)
        pub_bio = BIO.MemoryBuffer()
        priv_bio = BIO.MemoryBuffer()

        rsa.save_pub_key_bio(pub_bio)
        rsa.save_key_bio(priv_bio, None)
        
        pub_file = arg1 
       # pub_file = arg1 + 'pub.pem'
        private_file = arg2 
       # private_file = arg2 + 'private.pem'
        open(pub_file,'w').write(pub_bio.read_all())
        open(private_file,'w').write(priv_bio.read_all())

        pub_key = RSA.load_pub_key(pub_file)
        priv_key = RSA.load_key(private_file)

        message = 'opzoon'
  
        encrypted = pub_key.public_encrypt(message, RSA.pkcs1_padding)
        decrypted = priv_key.private_decrypt(encrypted, RSA.pkcs1_padding)

        if decrypted==message:
            #os.popen("rm -rf m2crypto_gen_key.py")
            pass
        else:
            os.popen("rm -rf *.pem")
            print "Key generation failed,please try again!"
            raise Exception("Key generation failed,please try again!")
    except Exception,e:
        os.popen("rm -rf *.pem")
        raise Exception("Key generation failed,please try again!")
Example #3
0
 def _verify_signature(self, public_key_path):
     pubkey = RSA.load_pub_key(public_key_path)
     try:
         sig_sum = pubkey.public_decrypt(self.signature, RSA.pkcs1_padding)
         return sig_sum == self.signature_checksum
     except RSA.RSAError, e:
         return False
Example #4
0
def read_keys():
    global P_K_enc, P_K_shop, P_ca, K_K_enc
    try:
        """key = open('./keys/P_enc--loyaltyEncryptionPublic.key').read()
        P_K_enc = PublicKey.RSA.importKey(key)    
        key = open('./keys/K_enc--loyaltyEncryptionPrivate.key').read()
        P_K_enc = PublicKey.RSA.importKey(key)  """

        pub = RSA2.load_pub_key("./keys/P_enc--loyaltyEncryptionPublic.key")
        priv = RSA2.load_key("./keys/K_enc--loyaltyEncryptionPrivate.key")
        P_K_enc = (pub, priv)

        key = open('./keys/P_CA--CAPublicKey.key').read()
        P_ca = PublicKey.RSA.importKey(key)
        #key = open('./keys/Attrapez-les-tous_RSAprivate.key').read()
        #P_K_shop = PublicKey.RSA.importKey(key)
        P_K_shop = RSA2.load_key("./keys/Attrapez-les-tous_RSAprivate.key")
    except IOError:
        print """
    Need the files:
    ./keys/P_enc--loyaltyEncryptionPublic.key
    ./keys/K_enc--loyaltyEncryptionPrivate.key
    ./keys/P_CA--CAPublicKey.key  
    ./keys/Attrapez-les-tous_RSAprivate.key  
    """
        exit(-1)
Example #5
0
    def verify_master(self, master_pub, token):
        """
        Takes the master pubkey and compares it to the saved master pubkey,
        the token is encrypted with the master private key and must be
        decrypted successfully to verify that the master has been connected
        to.  The token must decrypt with the public key, and it must say:
        'salty bacon'

        Returns a bool
        """
        tmp_pub = tempfile.mktemp()
        open(tmp_pub, "w+").write(master_pub)
        m_pub_fn = os.path.join(self.opts["pki_dir"], self.mpub)
        pub = RSA.load_pub_key(tmp_pub)
        os.remove(tmp_pub)
        if os.path.isfile(m_pub_fn) and not self.opts["open_mode"]:
            local_master_pub = open(m_pub_fn).read()
            if not master_pub == local_master_pub:
                # This is not the last master we connected to
                log.error(
                    "The master key has changed, the salt master could "
                    "have been subverted, verify salt master's public "
                    "key"
                )
                return False
        else:
            open(m_pub_fn, "w+").write(master_pub)
        if pub.public_decrypt(token, 5) == "salty bacon":
            return True
        log.error("The salt master has failed verification for an unknown " "reason, verify your salt keys")
        return False
Example #6
0
 def test_newpub(self):
     old = RSA.load_pub_key(self.pubkey)
     new = RSA.new_pub_key(old.pub())
     self.assertTrue(new.check_key())
     self.assertEqual(len(new), 1024)
     # aka 65537 aka 0xf4
     self.assertEqual(new.e, b'\000\000\000\003\001\000\001')
Example #7
0
    def test_sign_and_verify(self):
        """
        Testing signing and verifying digests
        """
        algos = {'sha1': '',
                 'ripemd160': '',
                 'md5': ''}

        if m2.OPENSSL_VERSION_NUMBER >= 0x90800F:
            algos['sha224'] = ''
            algos['sha256'] = ''
            algos['sha384'] = ''
            algos['sha512'] = ''

        message = b"This is the message string"
        digest = hashlib.sha1(message).digest()
        rsa = RSA.load_key(self.privkey)
        rsa2 = RSA.load_pub_key(self.pubkey)
        for algo in algos.keys():
            signature = rsa.sign(digest, algo)
            # assert signature == algos[algo],
            #     'mismatched signature with algorithm %s:
            #     signature=%s' % (algo, signature)
            verify = rsa2.verify(digest, signature, algo)
            self.assertEqual(verify, 1,
                             'verification failed with algorithm %s' % algo)
Example #8
0
 def __init__(self):
     super(Giedo, self).__init__(settings.GIEDO_SOCKET)
     self.l = logging.getLogger('giedo')
     self.last_sync_ts = 0
     self.daan, self.cilia = None, None
     try:
         self.daan = WhimClient(settings.DAAN_SOCKET)
     except:
         self.l.exception("Couldn't connect to daan")
     try:
         self.cilia = WhimClient(settings.CILIA_SOCKET)
     except:
         self.l.exception("Couldn't connect to cilia")
     self.mirte = mirte.get_a_manager()
     self.threadPool = self.mirte.get_a('threadPool')
     self.operation_lock = threading.Lock()
     self.push_changes_event = threading.Event()
     self.openvpn_lock = threading.Lock()
     self.threadPool.execute(self.run_change_pusher)
     if default_storage.exists("villanet.pem"):
         self.villanet_key = RSA.load_pub_key(default_storage.path(
             "villanet.pem"))
     self.ss_actions = (
               ('postfix', self.daan, self._gen_postfix),
               ('postfix-slm', self.daan, self._gen_postfix_slm),
               ('mailman', self.daan, self._gen_mailman),
               ('forum', self.daan, self._gen_forum),
               ('unix', self.cilia, self._gen_unix),
               ('wiki', self.daan, self._gen_wiki),
               ('ldap', self.daan, self._gen_ldap),
               ('wolk', self.cilia, self._gen_wolk),
               ('quassel', self.daan, self._gen_quassel))
     self.push_changes_event.set()
    def __init__(self, pub_key, priv_key, ca_cert, passphrase):
        """ Create a Certification Subject Object.

        Arguments:
            pub_key: file system path of the Subject's Public Key.
            priv_key: file system path of the Subject's Private Key (encrypted).
            ca_cert: file system path of the Certification Authority's Certificate.
            passphrase: Symmetric key for priv_key decryption.
        """
        def getPassphrase(*args):
            """ Callback for private key decrypting.
            """
            return str(passphrase.encode('utf-8'))

        self.pub_key = RSA.load_pub_key(pub_key.encode('utf-8'))
        self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase)
        self.ca_cert = X509.load_cert(ca_cert.decode('utf-8'))

        # Private key for signing
        self.signEVP = EVP.PKey()
        self.signEVP.assign_rsa(self.priv_key)

        # CA Key for validations
        self.verifyEVP = EVP.PKey()
        self.verifyEVP.assign_rsa(self.ca_cert.get_pubkey().get_rsa())
def valid_sig(xml, sig, pubkey):
    import base64, digest
    from M2Crypto import RSA
    digest1 = digest.sha1(xml, None)
    rsa = RSA.load_pub_key(pubkey)
    digest2 = rsa.public_decrypt(base64.decodestring(sig), RSA.pkcs1_padding)
    return (digest1 == digest2)
Example #11
0
def create_rsa_keyring(passphrase_callback, key_size=2048, exponent=65537):
    """ Return a new RSA keyring as tuple (<public key>, <private key>)
    @param passphrase_callback: A Python callable object that is invoked
    during key generation; its usual purpose is to provide visual
    feedback.
    You must load a randpool file before calling this method with
    Rand.load_file('randpool', -1).
    After calling the method, you must save the randpool file with
    Rand.save_file('randpool')
    @type passphrase_callback: Callback

    @param key_size: Key length, in bits
    @type key_size: Integer

    @param exponent: The RSA public exponent
    @type exponent: Integer
    """
    keyring = RSA.gen_key(key_size, exponent)

    privkey_filename = get_secure_filename()
    pubkey_filename = get_secure_filename()

    keyring.save_key(privkey_filename, callback=passphrase_callback)
    keyring.save_pub_key(pubkey_filename)

    privkey = RSA.load_key(privkey_filename, callback=passphrase_callback)
    pubkey = RSA.load_pub_key(pubkey_filename)

    os.unlink(privkey_filename)
    os.unlink(pubkey_filename)

    return (pubkey, privkey)
Example #12
0
    def set_public_key(self, keyfile=None, **kwargs):
        """ Load the rsa public key.

        Keyword Arguments
         - algorithm: rsa, aes (default: no default).
         - mode: the mode dictionary key. For example local (default: no default).

        """
        algorithm = kwargs.get('algorithm', self.algorithm)
        mode = kwargs.get('mode', self.mode)
        self.public_key = None
        if not keyfile:
            # keyfile not specified, so get the default for this
            # algorithm and mode
            if not algorithm or not mode:
                raise EncryptionKeyError('Algorithm and mode must be set \
                                      before attempting to set the \
                                      public key')
            keyfile = (self._get_keypaths().get(algorithm).get(mode).get('public'))
        if isinstance(self._get_preloaded_keypaths().get(algorithm).get(mode).get('public'), RSA.RSA_pub):
            self.public_key = (self._get_preloaded_keypaths().get(algorithm).get(mode).get('public'))
        else:
            try:
                self.public_key = RSA.load_pub_key(keyfile)
                logger.info('successfully loaded {0} {1} '
                            'public key'.format(algorithm, mode))
                self.has_encryption_key = True
            except:
                logger.warning('warning: failed to load public '
                               'key {0}.'.format(keyfile))
        return self.public_key is not None
Example #13
0
    def verify(self, signed_data=None, signature=None):
        # sined data and signature may unicode from client,
        # format it as normal string.
        signed_data = str(signed_data)
        signature = str(signature)

        # TODO - update iab public key
        pem_file = "certificate/iab_public_key.pem"
        rsa = RSA.load_pub_key(pem_file)

        pubkey = EVP.PKey()
        pubkey.assign_rsa(rsa)
        pubkey.reset_context(md='sha1')
        pubkey.verify_init()
        try:
            pubkey.verify_update(signed_data)

            signature_padded = signature
            if signature_padded:
                while len(signature_padded) % 4 != 0:
                    signature_padded += '='
            signature_decoded = signature_padded.decode('base64')
            assert pubkey.verify_final(signature_decoded) == 1
            return True, PurchaseResultCode.Value("SUCCESS_PURCHASED")
        except Exception as e:
            # TODO - handle error code
            return False, PurchaseResultCode.Value("UNKNOWN")
Example #14
0
def encryptDataToFile(data,key,file):
    publickey = RSA.load_pub_key(key)
    encryptCPUAuthString = publickey.public_encrypt(data,RSA.pkcs1_padding)
    encryptCPUAuthBase64 = encryptCPUAuthString.encode("base64")
    f = open(file,'w')
    f.write(encryptCPUAuthBase64)
    f.close()
Example #15
0
    def test_pkey_verify_crash(self):
        SIGN_PRIVATE = EVP.load_key('tests/rsa.priv.pem')
        SIGN_PUBLIC = RSA.load_pub_key('tests/rsa.pub.pem')

        def sign(data):
            SIGN_PRIVATE.sign_init()
            SIGN_PRIVATE.sign_update(data)
            signed_data = SIGN_PRIVATE.sign_final()
            return base64.b64encode(signed_data)

        def verify(response):
            signature = base64.b64decode(response['sign'])
            data = response['data']
            verify_evp = EVP.PKey()
            # capture parameter on the following line is required by
            # the documentation
            verify_evp.assign_rsa(SIGN_PUBLIC, capture=False)
            verify_evp.verify_init()
            verify_evp.verify_update(data)
            # m2.verify_final(self.ctx, sign, self.pkey)
            fin_res = verify_evp.verify_final(signature)
            return fin_res == 1

        data = b"test message"
        signature = sign(data)
        res = {"data": data, "sign": signature}
        self.assertTrue(verify(res))  # works fine
        self.assertTrue(verify(res))  # segmentation fault in *verify_final*
Example #16
0
    def decrypt_aes(self, payload, master_pub=True):
        '''
        This function is used to decrypt the aes seed phrase returned from
        the master server, the seed phrase is decrypted with the ssh rsa
        host key.

        Pass in the encrypted aes key.
        Returns the decrypted aes seed key, a string
        '''
        log.debug('Decrypting the current master AES key')
        key = self.get_keys()
        key_str = key.private_decrypt(payload['aes'], 4)
        if 'sig' in payload:
            m_path = os.path.join(self.opts['pki_dir'], self.mpub)
            if os.path.exists(m_path):
                try:
                    mkey = RSA.load_pub_key(m_path)
                except Exception:
                    return '', ''
                digest = hashlib.sha256(key_str).hexdigest()
                m_digest = mkey.public_decrypt(payload['sig'], 5)
                if m_digest != digest:
                    return '', ''
        else:
            return '', ''
        if '_|-' in key_str:
            return key_str.split('_|-')
        else:
            if 'token' in payload:
                token = key.private_decrypt(payload['token'], 4)
                return key_str, token
            elif not master_pub:
                return key_str, ''
        return '', ''
Example #17
0
    def verify_master(self, master_pub, token):
        '''
        Takes the master pubkey and compares it to the saved master pubkey,
        the token is sign with the master private key and must be
        verified successfully to verify that the master has been connected
        to.  The token must verify as signature of the phrase 'salty bacon'
        with the public key.

        Returns a bool
        '''
        fd_, tmp_pub = tempfile.mkstemp()
        os.close(fd_)
        with open(tmp_pub, 'w+') as fp_:
            fp_.write(master_pub)
        m_pub_fn = os.path.join(self.opts['pki_dir'], self.mpub)
        if os.path.isfile(m_pub_fn) and not self.opts['open_mode']:
            local_master_pub = open(m_pub_fn).read()
            if not master_pub == local_master_pub:
                # This is not the last master we connected to
                log.error('The master key has changed, the salt master could '
                          'have been subverted, verify salt master\'s public '
                          'key')
                return False
        else:
            open(m_pub_fn, 'w+').write(master_pub)
        pub = RSA.load_pub_key(tmp_pub)
        plaintext = pub.public_decrypt(token, 5)
        os.remove(tmp_pub)
        if plaintext == 'salty bacon':
            return True
        log.error('The salt master has failed verification for an unknown '
                  'reason, verify your salt keys')
        return False
Example #18
0
def authenticate(args, server_socket, client_socket):
    # Get the _auth packet
    log('Waiting for an auth packet')
    auth_packet = msgpack.loads(server_socket.recv())

    # Parse the minion's public key
    log("Parsing the minion's public key")
    with tempfile.NamedTemporaryFile() as temp_pub_key:
        temp_pub_key.write(auth_packet['load']['pub'])
        temp_pub_key.flush()
        pub_key = RSA.load_pub_key(temp_pub_key.name)

    # Get the real response from the master
    log('Getting the decryption of the token from the legitimate master')
    master_response = proxy(client_socket, auth_packet)

    # Generate our own AES key and send it to the client
    log("Generating an AES key")
    aes_key = salt.crypt.Crypticle.generate_key_string()

    # Fudge some response parameters
    master_response['aes'] = pub_key.public_encrypt(aes_key, 4)
    master_response['publish_port'] = urlparse.urlparse(args.pub_address).port

    log('Sending the AES key to the minion')
    server_socket.send(msgpack.dumps(master_response))

    return aes_key, pub_key
Example #19
0
 def minion_sign_in_payload(self):
     '''
     Generates the payload used to authenticate with the master
     server. This payload consists of the passed in id_ and the ssh
     public key to encrypt the AES key sent back form the master.
     '''
     payload = {}
     key = self.get_keys()
     tmp_pub = salt.utils.mkstemp()
     key.save_pub_key(tmp_pub)
     payload['enc'] = 'clear'
     payload['load'] = {}
     payload['load']['cmd'] = '_auth'
     payload['load']['id'] = self.opts['id']
     try:
         pub = RSA.load_pub_key(
             os.path.join(self.opts['pki_dir'], self.mpub)
         )
         payload['load']['token'] = pub.public_encrypt(self.token, RSA.pkcs1_oaep_padding)
     except Exception:
         pass
     with salt.utils.fopen(tmp_pub, 'r') as fp_:
         payload['load']['pub'] = fp_.read()
     os.remove(tmp_pub)
     return payload
Example #20
0
 def verify_master(self, master_pub, token):
     '''
     Takes the master pubkey and compares it to the saved master pubkey,
     the token is encrypted with the master private key and must be
     decrypted sucessfully to verify that the master has been connected to.
     The token must decrypt with the public key, and it must say:
     'salty bacon'
     returns a bool
     '''
     tmp_pub = tempfile.mktemp()
     open(tmp_pub, 'w+').write(master_pub)
     m_pub_fn = os.path.join(self.opts['pki_dir'], 'master.pub')
     if os.path.isfile(m_pub_fn) and not self.opts['open_mode']:
         local_master_pub = open(m_pub_fn).read()
         if not master_pub == local_master_pub:
             # This is not the last master we connected to
             self.opts['logger'].error('The master key has changed, the'\
                     + ' salt master could have been subverted, verify'\
                     + ' salt master\'s public key')
             return False
     else:
         open(m_pub_fn, 'w+').write(master_pub)
     pub = RSA.load_pub_key(tmp_pub)
     if pub.public_decrypt(token, 5) == 'salty bacon':
         return True
     self.opts['logger'].error('The salt master has failed verification'\
             + ' for an unknown reason, verify your salt keys')
     return False
Example #21
0
 def test_loadpub(self):
     rsa = RSA.load_pub_key(self.pubkey)
     assert len(rsa) == 1024
     assert rsa.e == '\000\000\000\003\001\000\001' # aka 65537 aka 0xf4
     self.assertRaises(RSA.RSAError, setattr, rsa, 'e', '\000\000\000\003\001\000\001')
     self.assertRaises(RSA.RSAError, rsa.private_encrypt, 1)
     self.assertRaises(RSA.RSAError, rsa.private_decrypt, 1)
     assert rsa.check_key()
Example #22
0
	def getpublickey(self,fname):
		pubpem=fname+"-public.pem"
		pubkey = RSA.load_pub_key (pubpem)
		pub_mem = BIO.MemoryBuffer()
		pubkey.save_pub_key_bio(pub_mem)
		public_key = pub_mem.getvalue()
		print "public_key=",public_key
		return public_key
Example #23
0
 def _decrypt_with_public_key(self, encrypted_str):
     """
     :param encrypted_str: The encrypted string with base64 encoded
     :return:
     """
     pub_key = RSA.load_pub_key(self.public_key_loc)
     decrypted = pub_key.public_decrypt(b64decode(encrypted_str), RSA.pkcs1_padding)
     return decrypted
Example #24
0
 def encrypt_message(self, message):
     """
     :param message: text to be encrypted.
     :return:
     """
     pub_key = RSA.load_pub_key(self.public_key_loc)
     encrypted = pub_key.public_encrypt(message, RSA.pkcs1_padding)
     encrypted = b64encode(encrypted)
     return encrypted
Example #25
0
def rsaEncrypt(request):
    plain_text = request.POST["message"]
    output = u"Klartext:\n%s\n\n" %(plain_text)
    output += u"RSA-verschlüsselt:\n"
    try:
        PubKey = RSA.load_pub_key(request.FILES['key'].temporary_file_path())
        cypher = number.bytes_to_long(PubKey.public_encrypt(plain_text, 1))
    except RSA.RSAError, e:
        output = str(e)
        cypher = ""
Example #26
0
 def test_newpub(self):
     old = RSA.load_pub_key(self.pubkey)
     log.debug('old = %s', old)
     log.debug('old.pub = %s', old.pub())
     new = RSA.new_pub_key(old.pub())
     log.debug('new = %s', new)
     self.assertTrue(new.check_key())
     self.assertEqual(len(new), 1024)
     # aka 65537 aka 0xf4
     self.assertEqual(new.e, '\000\000\000\003\001\000\001')
Example #27
0
    def decrypt_aes(self, payload, master_pub=True):
        '''
        This function is used to decrypt the AES seed phrase returned from
        the master server. The seed phrase is decrypted with the SSH RSA
        host key.

        Pass in the encrypted AES key.
        Returns the decrypted AES seed key, a string

        :param dict payload: The incoming payload. This is a dictionary which may have the following keys:
            'aes': The shared AES key
            'enc': The format of the message. ('clear', 'pub', etc)
            'publish_port': The TCP port which published the message
            'token': The encrypted token used to verify the message.
            'pub_key': The public key of the sender.

        :rtype: str
        :return: The decrypted token that was provided, with padding.

        :rtype: str
        :return: The decrypted AES seed key
        '''
        if self.opts.get('auth_trb', False):
            log.warning(
                    'Auth Called: {0}'.format(
                        ''.join(traceback.format_stack())
                        )
                    )
        else:
            log.debug('Decrypting the current master AES key')
        key = self.get_keys()
        key_str = key.private_decrypt(payload['aes'], RSA.pkcs1_oaep_padding)
        if 'sig' in payload:
            m_path = os.path.join(self.opts['pki_dir'], self.mpub)
            if os.path.exists(m_path):
                try:
                    mkey = RSA.load_pub_key(m_path)
                except Exception:
                    return '', ''
                digest = hashlib.sha256(key_str).hexdigest()
                m_digest = mkey.public_decrypt(payload['sig'], 5)
                if m_digest != digest:
                    return '', ''
        else:
            return '', ''
        if '_|-' in key_str:
            return key_str.split('_|-')
        else:
            if 'token' in payload:
                token = key.private_decrypt(payload['token'], RSA.pkcs1_oaep_padding)
                return key_str, token
            elif not master_pub:
                return key_str, ''
        return '', ''
Example #28
0
 def make_hash(self):
     """ Makes the key for authentication according to the
     specification on Nordnets page """
     timestamp = str(int(round(time.time()*1000)))
     auth = b64encode(config.username) + ':' \
         + b64encode(config.password) + ':' \
         + b64encode(timestamp)
     rsa = RSA.load_pub_key(config.public_key)
     encrypted_auth = rsa.public_encrypt(auth, RSA.pkcs1_padding)
     key = b64encode(encrypted_auth)
     return key
Example #29
0
 def test_savepub(self):
     rsa = RSA.load_pub_key(self.pubkey)
     assert rsa.as_pem() # calls save_key_bio
     f = 'tests/rsa_test.pub'
     try:
         self.assertEquals(rsa.save_key(f), 1)
     finally:
         try:
             os.remove(f)
         except IOError:
             pass
Example #30
0
	def _import_keys(self):
		public_bio = BIO.MemoryBuffer(self.public_key) if self.public_key \
			else None
		self.rsa_public = M2C_RSA.load_pub_key_bio(public_bio) \
			if public_bio else M2C_RSA.load_pub_key(self.public_key_filename)

		private_bio = BIO.MemoryBuffer(self.private_key) if self.private_key \
			else None
		self.rsa_private = M2C_RSA.load_key_bio(private_bio) \
			if private_bio else M2C_RSA.load_key(self.private_key_filename,
				callback=self.dpc)
Example #31
0
    def test_sign_and_verify(self):
        """
        Testing signing and verifying digests
        """
        algos = {'sha1': '', 'ripemd160': '', 'md5': ''}

        if m2.OPENSSL_VERSION_NUMBER >= 0x90800F:
            algos['sha224'] = ''
            algos['sha256'] = ''
            algos['sha384'] = ''
            algos['sha512'] = ''

        message = b"This is the message string"
        digest = hashlib.sha1(message).digest()
        rsa = RSA.load_key(self.privkey)
        rsa2 = RSA.load_pub_key(self.pubkey)
        for algo in algos.keys():
            signature = rsa.sign(digest, algo)
            # assert signature == algos[algo],
            #     'mismatched signature with algorithm %s:
            #     signature=%s' % (algo, signature)
            verify = rsa2.verify(digest, signature, algo)
            self.assertEqual(verify, 1,
                             'verification failed with algorithm %s' % algo)
Example #32
0
 def minion_sign_in_payload(self):
     '''
     Generates the payload used to authenticate with the master
     server. This payload consists of the passed in id_ and the ssh
     public key to encrypt the AES key sent back form the master.
     '''
     payload = {}
     key = self.get_keys()
     tmp_pub = salt.utils.mkstemp()
     key.save_pub_key(tmp_pub)
     payload['enc'] = 'clear'
     payload['load'] = {}
     payload['load']['cmd'] = '_auth'
     payload['load']['id'] = self.opts['id']
     try:
         pub = RSA.load_pub_key(
             os.path.join(self.opts['pki_dir'], self.mpub))
         payload['load']['token'] = pub.public_encrypt(self.token, 4)
     except Exception:
         pass
     with salt.utils.fopen(tmp_pub, 'r') as fp_:
         payload['load']['pub'] = fp_.read()
     os.remove(tmp_pub)
     return payload
Example #33
0
    def minion_sign_in_payload(self):
        '''
        Generates the payload used to authenticate with the master
        server. This payload consists of the passed in id_ and the ssh
        public key to encrypt the AES key sent back form the master.

        :return: Payload dictionary
        :rtype: dict
        '''
        payload = {}
        payload['enc'] = 'clear'
        payload['load'] = {}
        payload['load']['cmd'] = '_auth'
        payload['load']['id'] = self.opts['id']
        try:
            pub = RSA.load_pub_key(
                os.path.join(self.opts['pki_dir'], self.mpub))
            payload['load']['token'] = pub.public_encrypt(
                self.token, RSA.pkcs1_oaep_padding)
        except Exception:
            pass
        with salt.utils.fopen(self.pub_path, 'r') as fp_:
            payload['load']['pub'] = fp_.read()
        return payload
Example #34
0
    '--gcrypt': (print_gcrypt, print_gcrypt_keys),
}

try:
    mode = sys.argv[1]
    files = sys.argv[2:-1]
    outfile = sys.argv[-1]
except IndexError:
    mode = None

if not mode in modes:
    print 'Usage: %s [%s] input-file... output-file' % (sys.argv[0], '|'.join(
        modes.keys()))
    sys.exit(2)

output = open(outfile, 'w')

# load key
idx = 0
for f in files:
    try:
        key = RSA.load_pub_key(f)
    except RSA.RSAError:
        key = RSA.load_key(f)

    modes[mode][0](output, 'e_%d' % idx, key.e[4:])
    modes[mode][0](output, 'n_%d' % idx, key.n[4:])
    idx += 1

modes[mode][1](output, idx - 1)
Example #35
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import M2Crypto
from M2Crypto import *
from M2Crypto.EVP import Cipher
from M2Crypto import m2
from M2Crypto import util

enKey = "68b329da9893e34099c7d8ad5cb9c940"
salt = ""
from M2Crypto import RSA
publicKey = './public'
privateKey = './private'
RSAPub = RSA.load_pub_key(publicKey)
RSAPri = RSA.load_key(privateKey)

from configure import enKey, RSAPub, RSAPri, salt
import hashlib
import json
import base64
from base64 import b64encode, b64decode
ENC = 1  # 加密操作
DEC = 0  # 解密操作


class SecurityTools():

    rsaPub = RSAPub
    rsaPri = RSAPri
    privateKey = enKey
Example #36
0
def rsa_public_decrypt(msg, file_rsa_public_name):
    from M2Crypto import RSA  # 用M2Crypto下的RSA模块
    rsa_public_key = RSA.load_pub_key(file_rsa_public_name)
    msg_decrypted = rsa_public_key.public_decrypt(msg, RSA.pkcs1_padding)
    return msg_decrypted
Example #37
0
	 script = os.path.splitext(os.basename())[0]
       if(mins, secs, horas == 0):
	      os.path.isfile(Script)
          os.remove(Script)
     return mins, secs, horas

    processo = process.communicate(nome)[0]
     for processo in out.splitlines():
         pid = int(processo.split(None, 1)[0])
          os.kill(pid, signal.SIGKILL, nome)

def encryptSniffer():

	TOKEN_ENCRYPTION_KEY = b'\x01\xad\x9b\xc6\x82\xa3\xaa\x93\xa9\xa3\x23\x9a\x86\xd6\xcc\xd9'
      rsa = RSA.load_pub_key("mykey.pub")
      ctxt = rsa.public_encrypt(secretstring, RSA.pkcs1_padding)
           encryptedText = ctxt.encode('base64')
      print TOKEN_ENCRYPTION_KEY+encryptedText
     try: 
          priv = RSA.load_key("mykey.pem")
          decodeEncryptedText = encryptedText.decode('base64')
          ecryptedText = priv.private_decrypt(decodeEncryptedText, RSA.pkcs1_padding)
          print("AVISO. Detectamos o Processo De Sniffer e fechamos ele!")
          self.openprocess(4, 4, 4(".exe"))
     else:
          sys.exit(time.Sleep(2, 3))

def encryptLogin():
    
    @app.route('/login', methods=['POST'])
Example #38
0
#####################################
try:
    w = open(EDPubKeyFile, 'rb')
except:
    connection = httplib.HTTPConnection(vhostname + ":" + vport)
    connection.request('GET', '/software/verify/ed/' + serialnum)
    respmsg = connection.getresponse()
    if respmsg.status == 200:
        result = respmsg.read()
        f = open(EDPubKeyFile, 'w')
        f.write(result)
        f.close()
    else:
        sys.exit(104)
else:
    w.close()
#######################################
try:
    publickey = RSA.load_pub_key(EDPubKeyFile)
    decrypthardinfo = publickey.public_decrypt(data, RSA.pkcs1_padding)
except M2Crypto.RSA.RSAError:
    sys.exit(106)

hardinfolist = decrypthardinfo.split('/')

if hardinfolist[1] == realmaindisksn and hardinfolist[3] == realmainnicmac:
    sys.exit(100)
else:
    sys.exit(105)
Example #39
0
    """
    Mod_auth_pubtkt style cookie authentication class.
    """
    def __init__(self, pub_key_Path, priv_key_Path=None):
        ##LOAD priv_key
        try:
            if priv_key_Path is not None:
                try:
                    priv_key = RSA.load_key(priv_key_Path)
                except Exception, e:
                    priv_key = DSA.load_key(priv_key_Path)
            else:
                priv_key = None

            if priv_key_Path is not None and isinstance(priv_key, RSA.RSA):
                pub_key = RSA.load_pub_key(pub_key_Path)
            else:
                pub_key = DSA.load_pub_key(pub_key_Path)

        except Exception, e:
            raise ValueError('Unknown key type: %s' % self.pub_key)

        self.priv_key = priv_key
        self.pub_key = pub_key

    def __verify_sig(self, data, sig):
        """Verify ticket signature.

        Returns False if ticket is tampered with and True if ticket is good.

        Arguments:
>>> verify_verification_token("user|appid|timestamp", base64.b64decode(base64.b64encode(sign_verification_token("user|appid|timestamp"))))
True

"""

from M2Crypto import BIO, RSA, EVP
import base64
import logging
import sys

pubkey = None
privkey = None

try:
    pubkey = EVP.PKey()
    pubkey.assign_rsa(RSA.load_pub_key("../store.cfg/pubkey.pem"))
except Exception, e:
    logging.error(
        "Unable to start up: No public key found for application verification!"
    )
    sys.exit(1)

try:
    privkey = EVP.load_key("../store.cfg/privkey.pem")
except Exception, e:
    pass


def sign_verification_token(verificationToken):
    privkey.sign_init()
    privkey.sign_update(verificationToken)
Example #41
0
"""
created by sphinx on
"""
import base64
from hashlib import md5
from geventhttpclient import HTTPClient
from geventhttpclient.url import URL
try:
    from M2Crypto import RSA
except:
    pass
if __name__ != '__main__':
    from gfirefly.server.logobj import logger

try:
    pub = RSA.load_pub_key('kuaiyong_pub.pem')
except:
    pass

APP_KEY = '05826e2d277a5d2b1f21464ee6beb599'

KUAIYONG_URL = 'http://f_signin.bppstore.com/loginCheck.php?'


def verify_login(token):
    sig = md5(APP_KEY + token).hexdigest()
    url = '%stokenKey=%s&sign=%s' % (KUAIYONG_URL, token, sig)
    logger.debug('kuaiyong url:%s', url)
    url = URL(url)
    http = HTTPClient(url.host, port=url.port)
    response = eval(http.get(url.request_uri).read())
Example #42
0
 def test_set_bn(self):
     rsa = RSA.load_pub_key(self.pubkey)
     assert m2.rsa_set_e(rsa.rsa, '\000\000\000\003\001\000\001') is None
     self.assertRaises(RSA.RSAError, m2.rsa_set_e, rsa.rsa,
                       '\000\000\000\003\001')
Example #43
0
 def test_newpub(self):
     old = RSA.load_pub_key(self.pubkey)
     new = RSA.new_pub_key(old.pub())
     assert new.check_key()
     assert len(new) == 1024
     assert new.e == '\000\000\000\003\001\000\001'  # aka 65537 aka 0xf4
Example #44
0
#!/usr/bin/evn python
# -*-encoding:UTF8-*-
# On 2017/06/26

from M2Crypto import RSA

msg = 'well done, good luck to vector-zhang!'

print '*********************************************************'
print '公钥加密,私钥解密'
rsa_pub = RSA.load_pub_key("public_key")
ctxt = rsa_pub.public_encrypt(msg, RSA.pkcs1_oaep_padding)
ctxt64 = ctxt.encode('base64')
print('密文:%s' % ctxt64)

rsa_pri = RSA.load_key("private_key")
txt = rsa_pri.private_decrypt(ctxt, RSA.pkcs1_oaep_padding)
print('明文:%s' % txt)

print '*************************************************************'
print '私钥加密,公钥解密'
ctxt_pri = rsa_pri.private_encrypt(msg, RSA.pkcs1_oaep_padding)
ctxt64_pri = ctxt_pri.encode('base64')
print('密文:%s' % ctxt64_pri)

txt_pri = rsa_pub.public_decrypt(ctxt_pri, RSA.pkcs1_oaep_padding)
print('明文:%s' % txt_pri)
Example #45
0
from ClientServer import ClientServer
from M2Crypto import RSA
from ServerConnection import ServerConnection
from Connection import Connection
from socket import socket, gethostbyname, AF_INET, SOCK_DGRAM

from random import randint
from P2PChat import P2PChat

rsa = RSA.load_pub_key('keys/key.pem')
username = '******'
c = ClientServer(ServerConnection('127.0.0.1', 5000, None, rsa), username,
                 True)
c.close()
mySocket = socket(AF_INET, SOCK_DGRAM)
hostName = gethostbyname('0.0.0.0')
mySocket.bind((hostName, 5002))
msg, addr = mySocket.recvfrom(2048)
mySocket.close()
p = P2PChat()
p.gotChatRequest(addr[0], addr[1], msg, c.getKey())
p.LoadChat()
Example #46
0
File: master.py Project: kuene/salt
    def _auth(self, load):
        '''
        Authenticate the client, use the sent public key to encrypt the aes key
        which was generated at start up.

        This method fires an event over the master event manager. The event is
        tagged "auth" and returns a dict with information about the auth
        event
        '''
        # 0. Check for max open files
        # 1. Verify that the key we are receiving matches the stored key
        # 2. Store the key if it is not there
        # 3. make an rsa key with the pub key
        # 4. encrypt the aes key as an encrypted salt.payload
        # 5. package the return and return it

        salt.utils.verify.check_max_open_files(self.opts)

        log.info('Authentication request from {id}'.format(**load))
        pubfn = os.path.join(self.opts['pki_dir'], 'minions', load['id'])
        pubfn_pend = os.path.join(self.opts['pki_dir'], 'minions_pre',
                                  load['id'])
        pubfn_rejected = os.path.join(self.opts['pki_dir'], 'minions_rejected',
                                      load['id'])
        if self.opts['open_mode']:
            # open mode is turned on, nuts to checks and overwrite whatever
            # is there
            pass
        elif os.path.isfile(pubfn):
            # The key has been accepted check it
            if not open(pubfn, 'r').read() == load['pub']:
                log.error(
                    'Authentication attempt from {id} failed, the public '
                    'keys did not match. This may be an attempt to compromise '
                    'the Salt cluster.'.format(**load))
                ret = {'enc': 'clear', 'load': {'ret': False}}
                eload = {'result': False, 'id': load['id'], 'pub': load['pub']}
                self.event.fire_event(eload, 'auth')
                return ret
        elif os.path.isfile(pubfn_rejected):
            # The key has been rejected, don't place it in pending
            log.info('Public key rejected for {id}'.format(**load))
            ret = {'enc': 'clear', 'load': {'ret': False}}
            eload = {'result': False, 'id': load['id'], 'pub': load['pub']}
            self.event.fire_event(eload, 'auth')
            return ret
        elif not os.path.isfile(pubfn_pend)\
                and not self._check_autosign(load['id']):
            # This is a new key, stick it in pre
            log.info(
                'New public key placed in pending for {id}'.format(**load))
            with open(pubfn_pend, 'w+') as fp_:
                fp_.write(load['pub'])
            ret = {'enc': 'clear', 'load': {'ret': True}}
            eload = {
                'result': True,
                'act': 'pend',
                'id': load['id'],
                'pub': load['pub']
            }
            self.event.fire_event(eload, 'auth')
            return ret
        elif os.path.isfile(pubfn_pend)\
                and not self._check_autosign(load['id']):
            # This key is in pending, if it is the same key ret True, else
            # ret False
            if not open(pubfn_pend, 'r').read() == load['pub']:
                log.error(
                    'Authentication attempt from {id} failed, the public '
                    'keys in pending did not match. This may be an attempt to '
                    'compromise the Salt cluster.'.format(**load))
                eload = {'result': False, 'id': load['id'], 'pub': load['pub']}
                self.event.fire_event(eload, 'auth')
                return {'enc': 'clear', 'load': {'ret': False}}
            else:
                log.info(
                    'Authentication failed from host {id}, the key is in '
                    'pending and needs to be accepted with salt-key -a {id}'.
                    format(**load))
                eload = {
                    'result': True,
                    'act': 'pend',
                    'id': load['id'],
                    'pub': load['pub']
                }
                self.event.fire_event(eload, 'auth')
                return {'enc': 'clear', 'load': {'ret': True}}
        elif os.path.isfile(pubfn_pend)\
                and self._check_autosign(load['id']):
            # This key is in pending, if it is the same key auto accept it
            if not open(pubfn_pend, 'r').read() == load['pub']:
                log.error(
                    'Authentication attempt from {id} failed, the public '
                    'keys in pending did not match. This may be an attempt to '
                    'compromise the Salt cluster.'.format(**load))
                eload = {'result': False, 'id': load['id'], 'pub': load['pub']}
                self.event.fire_event(eload, 'auth')
                return {'enc': 'clear', 'load': {'ret': False}}
            else:
                pass
        elif not os.path.isfile(pubfn_pend)\
                and self._check_autosign(load['id']):
            # This is a new key and it should be automatically be accepted
            pass
        else:
            # Something happened that I have not accounted for, FAIL!
            log.warn('Unaccounted for authentication failure')
            eload = {'result': False, 'id': load['id'], 'pub': load['pub']}
            self.event.fire_event(eload, 'auth')
            return {'enc': 'clear', 'load': {'ret': False}}

        log.info('Authentication accepted from {id}'.format(**load))
        with open(pubfn, 'w+') as fp_:
            fp_.write(load['pub'])
        pub = None

        # The key payload may sometimes be corrupt when using auto-accept
        # and an empty request comes in
        try:
            pub = RSA.load_pub_key(pubfn)
        except RSA.RSAError, e:
            log.error('Corrupt public key "{0}": {1}'.format(pubfn, e))
            return {'enc': 'clear', 'load': {'ret': False}}
Example #47
0
 def test_loadpub_bad(self):
     with self.assertRaises(RSA.RSAError):
         RSA.load_pub_key(self.errkey)
Example #48
0
        try:
            if len(data) % 16 != 0:
                data += '\0' * (16 - (len(data) % 16))
            ciphered_log = aes_cipher.update(data)
            ciphered_log = ciphered_log + aes_cipher.final()
        except Exception, e:
            Output.warning('Output data cannot be encrypted: %s' % str(e))
            return None
        finally:
            del aes_cipher

        # Load our RSA key and cipher the pass.
        rsa_cipher = None
        try:
            rsa_cipher = RSA.load_pub_key(self.__config['public_key'])
            ciphered_pass = rsa_cipher.public_encrypt(random_key,
                                                      RSA.sslv23_padding)
        except Exception, e:
            Output.warning('Output data cannot be encrypted: %s' % str(e))
            return None
        finally:
            del rsa_cipher

        ciphered_data = b64encode(
            ciphered_log) + '\n____key____\n' + b64encode(ciphered_pass)

        Output.info('Output data successfully encrypted')
        return ciphered_data

    # Upload some data to an FTP server.
Example #49
0
 def test_set_bn(self):
     rsa = RSA.load_pub_key(self.pubkey)
     with self.assertRaises(RSA.RSAError):
         m2.rsa_set_en(rsa.rsa,
             b'\000\000\000\003\001\000\001',
             b'\000\000\000\003\001')
Example #50
0
def decrytpWk(message,
              pem_file=os.path.abspath(sys.path[0]) + r'\ibox_publickey.pem'):
    readrsa = RSA.load_pub_key(pem_file)
    message = readrsa.public_decrypt(message.decode('hex'), RSA.pkcs1_padding)
    return message
class Login(object):

    def print_json(j, prefix=''):
        for key, value in j.items():
            if isinstance(value, dict):
                print '%s%s' % (prefix, key)
            else:
                print '%s%s:%s' % (prefix, key, value)

    username = '******'
    password = '******'
    service = 'NEXTAPI'
    URL = 'api.test.nordnet.se'
    API_VERSION = '2'

    timestamp = int(round(time.time() * 1000))
    timestamp = str(timestamp)
    buf = base64.b64encode(username) + ':' + base64.b64encode(password) + ':' + base64.b64encode(timestamp)
    rsa = RSA.load_pub_key('NEXTAPI_TEST_public.pem')
    encrypted_hash = rsa.public_encrypt(buf, RSA.pkcs1_padding)
    hash = base64.b64encode(encrypted_hash)

    headers = {"Accept": "application/json"}
    conn = httplib.HTTPSConnection(URL)



    # GET server status
    conn.request('GET', '/next/' + API_VERSION + '/', '', headers)
    r = conn.getresponse()
    response = r.read()
    j = json.loads(response)
    print_json(j)

    # POST login
    params = urllib.urlencode({'service': 'NEXTAPI', 'auth': hash})
    conn.request('POST', '/next/' + API_VERSION + '/login', params, headers)
    r = conn.getresponse()
    response = r.read()
    j = json.loads(response)
    print_json(j)
    session_key = j["session_key"]
    Feed.GetRequests().create_market_list(session_key, headers)
    Feed.GetRequests().instrument_name(session_key, headers, 'FINGerprint')


#################################################################################
    # Create SSL-wrapped socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ssl_socket = ssl.wrap_socket(s)
    # Connect to socket
    ssl_socket.connect(("pub.api.test.nordnet.se", 443))
    print repr(ssl_socket.getpeername)
    print ssl_socket.cipher()
    # Send session key
    cmd = {"cmd": "login", "args": {"session_key": session_key, "service": "NEXTAPI"}}
    num_bytes = ssl_socket.write(json.dumps(cmd) + "\n")
    print "Session key sent (%d bytes)" % num_bytes
    # Get account information

    # Subscribe to a stock
    market = 11
    instruments = ["101", "4870"]  # ERIC B and FING B

    for i in range(0, len(instruments)):
        instrument = instruments[i]
        cmd = {"cmd": "subscribe", "args": {"t": "price", "m": 11, "i": instrument}}
        numBytes = ssl_socket.send(json.dumps(cmd) + "\n")
        print("Subscription request sent for market = %d and instrument = %s (%d bytes)" % (11, instrument, numBytes))
    # Read stream
    print "Reading stream"
    for i in range(10):
        output = ssl_socket.read(1024)
        print (output)

    time.sleep(1)
    print ("-")
    output = ssl_socket.recv()
    print (output)

    # print "Closing socket connection..."
    del ssl_socket
    s.close()
Example #52
0
>>> verify_verification_token("user|appid|timestamp", sign_verification_token("user|appid|timestamp"))
True
>>> verify_verification_token("user|appid|timestamp", sign_verification_token("user|appid|timestamp").replace("a","b"))
False

"""

from M2Crypto import BIO, RSA, EVP

pubkey = None
privkey = None

# Some silliness here for our development and deployment directory trees
try:
    pubkey = EVP.PKey()
    pubkey.assign_rsa(RSA.load_pub_key("../tasktracker.cfg/pubkey.pem"))
except Exception, e:
    try:
        pubkey.assign_rsa(RSA.load_pub_key("pubkey.pem"))
    except:
        pass


def verify_verification_token(verificationToken, signature):
    # we are using RSA-SHA1
    pubkey.reset_context(md='sha1')
    pubkey.verify_init()
    pubkey.verify_update(verificationToken)

    result = pubkey.verify_final(signature)
    # result of 1 means signature checked out
Example #53
0
    def _auth(self, load):
        '''
        Authenticate the client, use the sent public key to encrypt the AES key
        which was generated at start up.

        This method fires an event over the master event manager. The event is
        tagged "auth" and returns a dict with information about the auth
        event

        # Verify that the key we are receiving matches the stored key
        # Store the key if it is not there
        # Make an RSA key with the pub key
        # Encrypt the AES key as an encrypted salt.payload
        # Package the return and return it
        '''

        if not salt.utils.verify.valid_id(self.opts, load['id']):
            log.info(
                'Authentication request from invalid id {id}'.format(**load)
                )
            return {'enc': 'clear',
                    'load': {'ret': False}}
        log.info('Authentication request from {id}'.format(**load))

        # 0 is default which should be 'unlimited'
        if self.opts['max_minions'] > 0:
            # use the ConCache if enabled, else use the minion utils
            if self.cache_cli:
                minions = self.cache_cli.get_cached()
            else:
                minions = self.ckminions.connected_ids()
                if len(minions) > 1000:
                    log.info('With large numbers of minions it is advised '
                             'to enable the ConCache with \'con_cache: True\' '
                             'in the masters configuration file.')

            if not len(minions) <= self.opts['max_minions']:
                # we reject new minions, minions that are already
                # connected must be allowed for the mine, highstate, etc.
                if load['id'] not in minions:
                    msg = ('Too many minions connected (max_minions={0}). '
                           'Rejecting connection from id '
                           '{1}'.format(self.opts['max_minions'],
                                        load['id']))
                    log.info(msg)
                    eload = {'result': False,
                             'act': 'full',
                             'id': load['id'],
                             'pub': load['pub']}

                    self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                    return {'enc': 'clear',
                            'load': {'ret': 'full'}}

        # Check if key is configured to be auto-rejected/signed
        auto_reject = self.auto_key.check_autoreject(load['id'])
        auto_sign = self.auto_key.check_autosign(load['id'])

        pubfn = os.path.join(self.opts['pki_dir'],
                             'minions',
                             load['id'])
        pubfn_pend = os.path.join(self.opts['pki_dir'],
                                  'minions_pre',
                                  load['id'])
        pubfn_rejected = os.path.join(self.opts['pki_dir'],
                                      'minions_rejected',
                                      load['id'])
        pubfn_denied = os.path.join(self.opts['pki_dir'],
                                    'minions_denied',
                                    load['id'])
        if self.opts['open_mode']:
            # open mode is turned on, nuts to checks and overwrite whatever
            # is there
            pass
        elif os.path.isfile(pubfn_rejected):
            # The key has been rejected, don't place it in pending
            log.info('Public key rejected for {0}. Key is present in '
                     'rejection key dir.'.format(load['id']))
            eload = {'result': False,
                     'id': load['id'],
                     'pub': load['pub']}
            self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
            return {'enc': 'clear',
                    'load': {'ret': False}}

        elif os.path.isfile(pubfn):
            # The key has been accepted, check it
            if salt.utils.fopen(pubfn, 'r').read() != load['pub']:
                log.error(
                    'Authentication attempt from {id} failed, the public '
                    'keys did not match. This may be an attempt to compromise '
                    'the Salt cluster.'.format(**load)
                )
                # put denied minion key into minions_denied
                with salt.utils.fopen(pubfn_denied, 'w+') as fp_:
                    fp_.write(load['pub'])
                eload = {'result': False,
                         'id': load['id'],
                         'pub': load['pub']}
                self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                return {'enc': 'clear',
                        'load': {'ret': False}}

        elif not os.path.isfile(pubfn_pend):
            # The key has not been accepted, this is a new minion
            if os.path.isdir(pubfn_pend):
                # The key path is a directory, error out
                log.info(
                    'New public key {id} is a directory'.format(**load)
                )
                eload = {'result': False,
                         'id': load['id'],
                         'pub': load['pub']}
                self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                return {'enc': 'clear',
                        'load': {'ret': False}}

            if auto_reject:
                key_path = pubfn_rejected
                log.info('New public key for {id} rejected via autoreject_file'
                         .format(**load))
                key_act = 'reject'
                key_result = False
            elif not auto_sign:
                key_path = pubfn_pend
                log.info('New public key for {id} placed in pending'
                         .format(**load))
                key_act = 'pend'
                key_result = True
            else:
                # The key is being automatically accepted, don't do anything
                # here and let the auto accept logic below handle it.
                key_path = None

            if key_path is not None:
                # Write the key to the appropriate location
                with salt.utils.fopen(key_path, 'w+') as fp_:
                    fp_.write(load['pub'])
                ret = {'enc': 'clear',
                       'load': {'ret': key_result}}
                eload = {'result': key_result,
                         'act': key_act,
                         'id': load['id'],
                         'pub': load['pub']}
                self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                return ret

        elif os.path.isfile(pubfn_pend):
            # This key is in the pending dir and is awaiting acceptance
            if auto_reject:
                # We don't care if the keys match, this minion is being
                # auto-rejected. Move the key file from the pending dir to the
                # rejected dir.
                try:
                    shutil.move(pubfn_pend, pubfn_rejected)
                except (IOError, OSError):
                    pass
                log.info('Pending public key for {id} rejected via '
                         'autoreject_file'.format(**load))
                ret = {'enc': 'clear',
                       'load': {'ret': False}}
                eload = {'result': False,
                         'act': 'reject',
                         'id': load['id'],
                         'pub': load['pub']}
                self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                return ret

            elif not auto_sign:
                # This key is in the pending dir and is not being auto-signed.
                # Check if the keys are the same and error out if this is the
                # case. Otherwise log the fact that the minion is still
                # pending.
                if salt.utils.fopen(pubfn_pend, 'r').read() != load['pub']:
                    log.error(
                        'Authentication attempt from {id} failed, the public '
                        'key in pending did not match. This may be an '
                        'attempt to compromise the Salt cluster.'
                        .format(**load)
                    )
                    # put denied minion key into minions_denied
                    with salt.utils.fopen(pubfn_denied, 'w+') as fp_:
                        fp_.write(load['pub'])
                    eload = {'result': False,
                             'id': load['id'],
                             'pub': load['pub']}
                    self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                    return {'enc': 'clear',
                            'load': {'ret': False}}
                else:
                    log.info(
                        'Authentication failed from host {id}, the key is in '
                        'pending and needs to be accepted with salt-key '
                        '-a {id}'.format(**load)
                    )
                    eload = {'result': True,
                             'act': 'pend',
                             'id': load['id'],
                             'pub': load['pub']}
                    self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                    return {'enc': 'clear',
                            'load': {'ret': True}}
            else:
                # This key is in pending and has been configured to be
                # auto-signed. Check to see if it is the same key, and if
                # so, pass on doing anything here, and let it get automatically
                # accepted below.
                if salt.utils.fopen(pubfn_pend, 'r').read() != load['pub']:
                    log.error(
                        'Authentication attempt from {id} failed, the public '
                        'keys in pending did not match. This may be an '
                        'attempt to compromise the Salt cluster.'
                        .format(**load)
                    )
                    # put denied minion key into minions_denied
                    with salt.utils.fopen(pubfn_denied, 'w+') as fp_:
                        fp_.write(load['pub'])
                    eload = {'result': False,
                             'id': load['id'],
                             'pub': load['pub']}
                    self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                    return {'enc': 'clear',
                            'load': {'ret': False}}
                else:
                    pass

        else:
            # Something happened that I have not accounted for, FAIL!
            log.warn('Unaccounted for authentication failure')
            eload = {'result': False,
                     'id': load['id'],
                     'pub': load['pub']}
            self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
            return {'enc': 'clear',
                    'load': {'ret': False}}

        log.info('Authentication accepted from {id}'.format(**load))
        # only write to disk if you are adding the file, and in open mode,
        # which implies we accept any key from a minion.
        if not os.path.isfile(pubfn) and not self.opts['open_mode']:
            with salt.utils.fopen(pubfn, 'w+') as fp_:
                fp_.write(load['pub'])
        elif self.opts['open_mode']:
            disk_key = ''
            if os.path.isfile(pubfn):
                with salt.utils.fopen(pubfn, 'r') as fp_:
                    disk_key = fp_.read()
            if load['pub'] and load['pub'] != disk_key:
                log.debug('Host key change detected in open mode.')
                with salt.utils.fopen(pubfn, 'w+') as fp_:
                    fp_.write(load['pub'])

        pub = None

        # the con_cache is enabled, send the minion id to the cache
        if self.cache_cli:
            self.cache_cli.put_cache([load['id']])

        # The key payload may sometimes be corrupt when using auto-accept
        # and an empty request comes in
        try:
            pub = RSA.load_pub_key(pubfn)
        except RSA.RSAError as err:
            log.error('Corrupt public key "{0}": {1}'.format(pubfn, err))
            return {'enc': 'clear',
                    'load': {'ret': False}}

        ret = {'enc': 'pub',
               'pub_key': self.master_key.get_pub_str(),
               'publish_port': self.opts['publish_port']}

        # sign the masters pubkey (if enabled) before it is
        # send to the minion that was just authenticated
        if self.opts['master_sign_pubkey']:
            # append the pre-computed signature to the auth-reply
            if self.master_key.pubkey_signature():
                log.debug('Adding pubkey signature to auth-reply')
                log.debug(self.master_key.pubkey_signature())
                ret.update({'pub_sig': self.master_key.pubkey_signature()})
            else:
                # the master has its own signing-keypair, compute the master.pub's
                # signature and append that to the auth-reply
                log.debug("Signing master public key before sending")
                pub_sign = salt.crypt.sign_message(self.master_key.get_sign_paths()[1],
                                                   ret['pub_key'])
                ret.update({'pub_sig': binascii.b2a_base64(pub_sign)})

        if self.opts['auth_mode'] >= 2:
            if 'token' in load:
                try:
                    mtoken = self.master_key.key.private_decrypt(load['token'], 4)
                    aes = '{0}_|-{1}'.format(salt.master.SMaster.secrets['aes']['secret'].value, mtoken)
                except Exception:
                    # Token failed to decrypt, send back the salty bacon to
                    # support older minions
                    pass
            else:
                aes = salt.master.SMaster.secrets['aes']['secret'].value

            ret['aes'] = pub.public_encrypt(aes, 4)
        else:
            if 'token' in load:
                try:
                    mtoken = self.master_key.key.private_decrypt(
                        load['token'], 4
                    )
                    ret['token'] = pub.public_encrypt(mtoken, 4)
                except Exception:
                    # Token failed to decrypt, send back the salty bacon to
                    # support older minions
                    pass

            aes = salt.master.SMaster.secrets['aes']['secret'].value
            ret['aes'] = pub.public_encrypt(salt.master.SMaster.secrets['aes']['secret'].value, 4)
        # Be aggressive about the signature
        digest = hashlib.sha256(aes).hexdigest()
        ret['sig'] = self.master_key.key.private_encrypt(digest, 5)
        eload = {'result': True,
                 'act': 'accept',
                 'id': load['id'],
                 'pub': load['pub']}
        self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
        return ret
Example #54
0
 def load(self, json):
     self.name = json['name']
     self.public_key = _provide_input(lambda x: RSA.load_pub_key(x),
                                      json['public_key'])
Example #55
0
import json
  

 
username = '******'
password = '******'
service  = 'NEXTAPI'
URL='api.test.nordnet.se'
BASE_URL='api.test.nordnet.se/next'
API_VERSION='1'
 
timestamp = int(round(time.time()*1000))
timestamp = str(timestamp)
buf = base64.b64encode(username) + ':' + base64.b64encode(password) + \
    ':' + base64.b64encode(timestamp)
rsa = RSA.load_pub_key('NEXTAPI_TEST_public.pem')
encrypted_hash = rsa.public_encrypt(buf, RSA.pkcs1_padding)
hash = base64.b64encode(encrypted_hash)
 
headers = {
    "Content-type": "application/x-www-form-urlencoded",
    "Accept": "application/json",
    'Accept-Language':'en'
    }
conn = httplib.HTTPSConnection(URL)
 
# GET server status
conn.request('GET','https://'+BASE_URL+'/'+API_VERSION, '', headers)
r=conn.getresponse()
response=r.read()
j = json.loads(response)
Example #56
0
def _getPublicKey(f):
    return RSA.load_pub_key(f)
Example #57
0
    def _auth(self, load):
        '''
        Authenticate the client, use the sent public key to encrypt the aes key
        which was generated at start up
        '''
        # 1. Verify that the key we are recieving matches the stored key
        # 2. Store the key if it is not there
        # 3. make an rsa key with the pub key
        # 4. encrypt the aes key as an encrypted pickle
        # 5. package the return and return it
        self.opts['logger'].info('Authentication request from '\
                + load['id'])
        pubfn = os.path.join(self.opts['pki_dir'], 'minions', load['id'])
        pubfn_pend = os.path.join(self.opts['pki_dir'], 'minions_pre',
                                  load['id'])
        if self.opts['open_mode']:
            # open mode is turned on, nuts to checks and overwrite whatever
            # is there
            pass
        elif os.path.isfile(pubfn):
            # The key has been accepted check it
            if not open(pubfn, 'r').read() == load['pub']:
                self.opts['logger'].error('Authentication attempt from '\
                        + load['id'] + ' failed, the public keys did'\
                        + ' not match. This may be an attempt to compromise'\
                        + ' the Salt cluster.')
                ret = {'enc': 'clear', 'load': {'ret': False}}
                return ret
        elif not os.path.isfile(pubfn_pend)\
                and not self.opts['auto_accept']:
            # This is a new key, stick it in pre
            self.opts['logger'].info('New public key placed in pending for '\
                    + load['id'])
            open(pubfn_pend, 'w+').write(load['pub'])
            ret = {'enc': 'clear', 'load': {'ret': True}}
            return ret
        elif os.path.isfile(pubfn_pend)\
                and not self.opts['auto_accept']:
            # This key is in pending, if it is the same key ret True, else
            # ret False
            if not open(pubfn_pend, 'r').read() == load['pub']:
                self.opts['logger'].error('Authentication attempt from '\
                        + load['id'] + ' failed, the public keys in'\
                        + ' pending did'\
                        + ' not match. This may be an attempt to compromise'\
                        + ' the Salt cluster.')
                return {'enc': 'clear', 'load': {'ret': False}}
            else:
                self.opts['logger'].info('Authentication failed from host '\
                        + load['id'] + ', the key is in pending and'\
                        + ' needs to be accepted with saltkey -a '\
                        + load['id'])
                return {'enc': 'clear', 'load': {'ret': True}}
        elif not os.path.isfile(pubfn_pend)\
                and self.opts['auto_accept']:
            # This is a new key and auto_accept is turned on
            pass
        else:
            # Something happened that I have not accounted for, FAIL!
            return {'enc': 'clear', 'load': {'ret': False}}

        self.opts['logger'].info('Authentication accepted from '\
                + load['id'])
        open(pubfn, 'w+').write(load['pub'])
        key = RSA.load_pub_key(pubfn)
        ret = {
            'enc': 'pub',
            'pub_key': self.master_key.pub_str,
            'token': self.master_key.token,
            'publish_port': self.opts['publish_port'],
        }
        ret['aes'] = key.public_encrypt(self.opts['aes'], 4)
        if self.opts['cluster_masters']:
            self._send_cluster()
        return ret
Example #58
0
#!/usr/bin/env python

"""RSA demonstration.

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved."""

from M2Crypto import RSA, EVP, Rand

msg="The magic words are squeamish ossifrage."
sha1=EVP.MessageDigest('sha1')
sha1.update(msg)
dgst=sha1.digest()

priv=RSA.load_key('rsa.priv.pem')
pub=RSA.load_pub_key('rsa.pub.pem')

def test_encrypt(padding):
    print 'testing public-key encryption:', padding
    padding=eval('RSA.'+padding)
    ctxt=pub.public_encrypt(dgst, padding)
    ptxt=priv.private_decrypt(ctxt, padding)
    if ptxt!=dgst:
        print 'public_encrypt -> private_decrypt: not ok'

def test_sign(padding):
    print 'testing private-key signing:', padding
    padding=eval('RSA.'+padding)
    ctxt=priv.private_encrypt(dgst, padding)    
    ptxt=pub.public_decrypt(ctxt, padding)
    if ptxt!=dgst:
        print 'private_decrypt -> public_encrypt: not ok'
Example #59
0
            notbefore=mynow, notafter=plus_twentyyears(mynow),
            serial=serial,
            O=my_org, L=my_location,
            CN=my_certname)

    return cert, pub, priv

if __name__ == '__main__':
 
    # reload the certs from disk
    f = open('ca.cert', 'r')
    ca_cert_content = f.read()
    f.close()

    cert = X509.load_cert_string(ca_cert_content)
    pub = RSA.load_pub_key('pub')
    priv = RSA.load_key('priv', callback=passphrase_callback)

    # test some data encryption/decryption with the reloaded keys
    k = "BvTgG/RJf7AhMvz60+m+3vzThkpvNm6kOqKl1tTo4copVmJZIEI7FElWT+yQ+a8mEknicGUKg33jpluOEKSS5HQRFT66DpXJ08Z3tx2pJTMSwNQBA+RGjp4nSHESPxRfKD6VGOmOd311IRvrWVzFV+l6sjRM2gLsHIzq/r/86tCJpXAtyFNb7aYTecrRDYEEkqCcv2Hs0mgatdpOlOGrzLf9W60I+ZLB50Ce14a+QtozyHyy5NSiPECsoYm7wuhfGQwmA2TPNEXcyhAP6mFmXy18qS25JnrxFRsGdOxHb5OZU+DIkz1QJmkET8UeYgUeyOPVYyAPKtF8o4wxigQHQQ=="
    p = pki.decrypt(priv, k)
    print p

#    #Rand.load_file('randpool', -1)
#    f = open('ca_certificate.pem', 'r')
#    ca_cert_content = f.read()
#    ca_cert = X509.load_cert_string(ca_cert_content)
#
#    cacert_privkey = RSA.load_key('ca_privkey.pem', callback=ca_passphrase_callback)
#
#    # serial should be autocalculated from the repository of existing (past and present) keys
Example #60
0
import sys
import logging
import os.path
from os.path import join as pjoin
import unittest
from M2Crypto import RSA, DSA
from auth_pubtkt import *


tests_dir = os.path.dirname(os.path.abspath(__file__))

rsa_priv = RSA.load_key(pjoin(tests_dir, 'rsa_priv.pem'))
rsa_pub = RSA.load_pub_key(pjoin(tests_dir, 'rsa_pub.pem'))
dsa_priv = DSA.load_key(pjoin(tests_dir, 'dsa_priv.pem'))
dsa_pub = DSA.load_pub_key(pjoin(tests_dir, 'dsa_pub.pem'))

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)


def verify_ok(pubkey, data, sig):
    return True

class ParseTicketTests(unittest.TestCase):


    def test_valid_rsa(self):

        ticket = '''uid=user1;cip=192.168.1.10;validuntil=1277190189;tokens=editor,moderator;udata=custom data;sig=W4/D/Ci2B9e60s7a1K810wPCQ3TzvlCXnAimjTVFRb6mqTFTlvdxCFmc6urC86d+8v8CtM4KsV5jsTmW/250OVkgk1PcoCz/Fvk84V5WqieWj2AVPC5DOujwy73lEeuu3/a4BfnsTagFWJZa6wGWqTEE5pULq8ZWthNXqkhXLzs='''

        fields = parse_ticket(ticket, rsa_pub)
        assert 'uid' in fields and fields['uid'] == 'user1'