Esempio n. 1
0
    def get_message_content(self):
        """
        Given the Slap XML, extract out the author and payload.
        """
        body = self.doc.find(
            ".//{http://salmon-protocol.org/ns/magic-env}data").text
        sig = self.doc.find(
            ".//{http://salmon-protocol.org/ns/magic-env}sig").text

        if not self.skip_author_verification:
            self.verify_signature(self.sender_key, body, sig.encode('ascii'))

        if self.encrypted:
            inner_iv = b64decode(self.header.find(".//iv").text.encode("ascii"))
            inner_key = b64decode(
                self.header.find(".//aes_key").text.encode("ascii"))

            decrypter = AES.new(inner_key, AES.MODE_CBC, inner_iv)
            body = b64decode(urlsafe_b64decode(body.encode("ascii")))
            body = decrypter.decrypt(body)
            body = self.pkcs7_unpad(body)
        else:
            body = urlsafe_b64decode(body.encode("ascii"))

        return body
Esempio n. 2
0
    def _build_protobuf(self):
        """Build a query protobuf.

        Relies on the current state of the iterator.

        :rtype:
            :class:`.query_pb2.Query`
        :returns: The query protobuf object for the current
                  state of the iterator.
        """
        pb = _pb_from_query(self._query)

        start_cursor = self.next_page_token
        if start_cursor is not None:
            pb.start_cursor = base64.urlsafe_b64decode(start_cursor)

        end_cursor = self._end_cursor
        if end_cursor is not None:
            pb.end_cursor = base64.urlsafe_b64decode(end_cursor)

        if self.max_results is not None:
            pb.limit.value = self.max_results - self.num_results

        if start_cursor is None and self._offset is not None:
            # NOTE: We don't need to add an offset to the request protobuf
            #       if we are using an existing cursor, because the offset
            #       is only relative to the start of the result set, not
            #       relative to each page (this method is called per-page)
            pb.offset = self._offset

        return pb
    def get(self, path):
        self.step = self.parseInt(path.replace("/", ""), -1)
        self.state = base64.urlsafe_b64decode(str(self.request.get("d"))).split(",")
        self.param_done = str(self.state[0]).split("|")
        self.param_correct = base64.urlsafe_b64decode(str(self.request.get("c")))
        self.param_choice = self.parseInt(self.request.get("q"), -1)

        if len(self.state) > 1:
            self.param_score = self.parseInt(self.state[1], 0)
        else:
            self.param_score = 0

        # http://wiki.python.org/moin/KeyError
        #person_correct = persons[param_correct]
        self.person_correct = persons.get(self.param_correct, None)
        self.result = None

        # Check the result
        if self.person_correct is not None and self.person_correct.place == self.param_choice:
            self.result = "success"
            self.param_score += 1
        elif self.param_choice != -1:
            self.result = "error"

        # Redirect the page
        if 0 < self.step < 11:
            self.doGame()
        else:
            self.doFinish()
Esempio n. 4
0
def fb_request_decode(signed_request):
    '''
    will get the data from a facebook signed request
    @param signed_request: 
    @return: Object the decoded data 
    '''
    
    fb_app_secret = settings.FACEBOOK_APP_SECRET
    s = [s.encode('ascii') for s in signed_request.split('.')]

    fb_sig = base64.urlsafe_b64decode(s[0] + '=')
    fb_data = json.loads(base64.urlsafe_b64decode(s[1]))
    fb_hash = hmac.new(fb_app_secret, s[1], hashlib.sha256).digest()

    sig_match = False
    if fb_sig == fb_hash:
        sig_match = True

    auth = False
    if 'user_id' in fb_data:
        auth = True

    return {
        'fb_sig' : fb_sig,
        'fb_data' : fb_data,
        'fb_hash' : fb_hash,
        'sig_match' : sig_match,
        'auth' : auth,
    }
Esempio n. 5
0
def decodeAsCookie(cookie):
  """
  Decode data from inside a cookie

  Parameters: cookie- the string of text representing the cookie. This
  will be decoded into data.

  Returns: a string with the hidden data

  Methods: will do take out the key and value, decode them, and
  concatenate them into the original string

  Note: As with the encodeAsCookie function, this function is designed
  to send data from the client to the server and modifications are
  necessary for convincing traffic from server to client
  """
  pattern = 'Cookie: (?P<key>[a-zA-Z0-9+_\-/]+)=(?P<value>[a-zA-Z0-9+_=\-/]*)'
  match = re.match(pattern, cookie)
  key = match.group('key')
  key = key.replace('+', '=')
  value = match.group('value')
  key = urlsafe_b64decode(key)
  value = urlsafe_b64decode(value)
  #In this case, the data needed padding because it was too
  #short. Since this key is longer than 10 chars, it cannot occur
  #naturally and does not need to be escaped
  if key == 'keyForPadding':
    key = ''
  data = key + value
  return data
Esempio n. 6
0
def parse_signed_request(
    signed_request, app_secret
):  # From http://www.rkblog.rk.edu.pl/w/p/facebook-aided-registration-django/
    """Return dictionary with signed request data.
    Code taken from https://github.com/facebook/python-sdk"""
    try:
        l = signed_request.split(".", 2)
        encoded_sig = str(l[0])
        payload = str(l[1])
    except IndexError:
        raise ValueError("'signed_request' malformed")

    sig = base64.urlsafe_b64decode(encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4))
    data = base64.urlsafe_b64decode(payload + "=" * ((4 - len(payload) % 4) % 4))

    data = json.loads(data)

    if data.get("algorithm").upper() != "HMAC-SHA256":
        raise ValueError("'signed_request' is using an unknown algorithm")
    else:
        expected_sig = hmac.new(app_secret, msg=payload, digestmod=hashlib.sha256).digest()

    if sig != expected_sig:
        raise ValueError("'signed_request' signature mismatch")
    else:
        return data
Esempio n. 7
0
    def get_signed_request_data(self, signed_request=None):
        signed_request = signed_request or request.form.get('signed_request')

        if signed_request:
            encoded_sig, payload = signed_request.split('.')
            data = json.loads(
                urlsafe_b64decode(
                    str(payload) + (64 - len(payload) % 64) * '='
                    ))

            if not data['algorithm'] == u'HMAC-SHA256':
                raise TypeError(
                    'Unknown encryption "{0}". Expected "HMAC-SHA256"'.format(
                        data['algorithm']))

            if not 'CANVAS_SECRET' in current_app.config.keys():
                raise ValueError(
                    'CANVAS_SECRET must be set to the Facebook app secret.')

            expected_sig = hmac.new(
                current_app.config['CANVAS_SECRET'],
                str(payload),
                sha256).digest()
            sig = urlsafe_b64decode(
                str(encoded_sig) + ('=' * (4 - (len(encoded_sig) % 4))))

            if not sig == expected_sig:
                raise AssertionError(
                    'Unexpected signature "{0}", expected "{1}"'.format(
                        sig,
                        expected_sig))

            return data
        return None
Esempio n. 8
0
def main():
    if len(sys.argv) < 4:
        #print ("usage: python push-encryption.py <client-pub-key> <server-auth> <message>")
        sys.exit(1)

    # generate ephemerial public key using ecdh
    serverECDH = pyelliptic.ECC(curve="prime256v1")
    serverPubKey = b64e(serverECDH.get_pubkey()[1:])

    http_ece.keys[serverPubKey] = serverECDH
    http_ece.labels[serverPubKey] = "P-256"

    salt = os.urandom(16)

    clientPubKey64 = sys.argv[1]
    clientPubKey = base64.urlsafe_b64decode(clientPubKey64)
   
    clientAuthSecret64 = sys.argv[2]
    clientAuthSecret = base64.urlsafe_b64decode(clientAuthSecret64)

    messageRaw = sys.argv[3]
    messageRaw = messageRaw.encode('utf8')
    messageRaw = buffer(messageRaw)


    messageEncrypted = http_ece.encrypt(messageRaw, salt=salt,
                              keyid=serverPubKey, dh=clientPubKey,
                              authSecret=clientAuthSecret)

    print ("%s,%s,%s" % (base64.urlsafe_b64encode(salt), base64.urlsafe_b64encode(serverECDH.get_pubkey()), base64.b64encode(messageEncrypted)), end="")
Esempio n. 9
0
def parse_signed_request(signed_request, app_secret):
    """ Return dictionary with signed request data.

    We return a dictionary containing the information in the signed_request. This will
    include a user_id if the user has authorised your application, as well as any
    information requested in the scope.

    If the signed_request is malformed or corrupted, False is returned.
    """
    try:
        l = signed_request.split('.', 2)
        encoded_sig = str(l[0])
        payload = str(l[1])
        sig = base64.urlsafe_b64decode(encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4))
        data = base64.urlsafe_b64decode(payload + "=" * ((4 - len(payload) % 4) % 4))
    except IndexError:
        return False # raise ValueError('signed_request malformed')
    except TypeError:
        return False # raise ValueError('signed_request had corrupted payload')

    data = _parse_json(data)
    if data.get('algorithm', '').upper() != 'HMAC-SHA256':
        return False # raise ValueError('signed_request used unknown algorithm')

    expected_sig = hmac.new(app_secret, msg=payload, digestmod=hashlib.sha256).digest()
    if sig != expected_sig:
        return False # raise ValueError('signed_request had signature mismatch')

    return data
Esempio n. 10
0
def parse_signed_request(signed_request, secret):
    """
    Parse signed_request given by Facebook (usually via POST),
    decrypt with app secret.

    Arguments:
    signed_request -- Facebook's signed request given through POST
    secret -- Application's app_secret required to decrpyt signed_request
    """
    try:
        l = signed_request.split('.', 2)
        encoded_sig = str(l[0])
        payload = str(l[1])
    except IndexError:
        raise SignedRequestError("Signed request malformed")

    sig = base64.urlsafe_b64decode(encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4))
    data = base64.urlsafe_b64decode(payload + "=" * ((4 - len(payload) % 4) % 4))

    data = json.loads(data)

    if data.get('algorithm').upper() != 'HMAC-SHA256':
        raise SignedRequestError("Signed request is using an unknown algorithm")
    else:
        expected_sig = hmac.new(secret, msg=payload, digestmod=hashlib.sha256).digest()

    if sig != expected_sig:
        raise SignedRequestError("Signed request signature mismatch")
    else:
        return data
Esempio n. 11
0
def decrypt(ciphertext, secret, inital_vector, checksum=True, lazy=True):
    """Decrypts ciphertext with secret
    ciphertext     - encrypted content to decrypt
    secret         - secret to decrypt ciphertext
    inital_vector  - initial vector
    lazy           - pad secret if less than legal blocksize (default: True)
    checksum       - verify crc32 byte encoded checksum (default: True)
    returns plaintext
    """

    secret = _lazysecret(secret) if lazy else secret
    encobj = AES.new(secret, AES.MODE_CFB, inital_vector)
    plaintext = encobj.decrypt(base64.urlsafe_b64decode(
        ciphertext + ('=' * (len(ciphertext) % 4))))

    if checksum:
        try:
            crc, plaintext = (base64.urlsafe_b64decode(
                plaintext[-8:]), plaintext[:-8])
        except TypeError:
            raise CheckSumError("checksum mismatch")

        if not crc == struct.pack("i", zlib.crc32(plaintext)):
            raise CheckSumError("checksum mismatch")

    return plaintext
Esempio n. 12
0
def home(request):
    instrument_panel = {}
    data_str = request.GET.get('data', '')
    
    signature = base64.urlsafe_b64decode(request.GET.get('sig', '').encode("ascii"))
    signature_check = hmac.new(settings.GEOPOD_CONSUMER_SECRET.encode("ascii"), msg=data_str.encode("ascii"), digestmod=hashlib.sha256).digest()
    
    if signature != signature_check:
        return HttpResponseForbidden()
    
    if data_str:
        data = simplejson.loads(base64.urlsafe_b64decode(data_str.encode("ascii")))
        subdomain = data.get('subdomain', '')
        if subdomain:
            gp = get_object_or_404(Geopod, subdomain=subdomain)
            gc = geopod.GeopodClient(gp.subdomain, gp.access_token, gp.access_token_secret, settings.GEOPOD_CONSUMER_KEY, settings.GEOPOD_CONSUMER_SECRET, "testgeopod.com")
            points = gc.request('/point/', params={'markers[]': 'his'})
    
    now = datetime.datetime.now()
    start = request.GET.get('start', str(datetime.date(year=now.year, month=now.month, day=now.day)))
    end = request.GET.get('end', str(datetime.date(year=now.year, month=now.month, day=now.day)))
    
    context = {
        'geopod': gp,
        'points': [{'id': '149eecb3-4cb9224d'}],
        'start': start,
        'end': end,
    }
    return render_to_response('threshold.html', context, context_instance=RequestContext(request))
Esempio n. 13
0
def parse_signed_request(signed_request, app_secret):
    """ Return dictionary with signed request data.

    We return a dictionary containing the information in the
    signed_request. This includes a user_id if the user has authorised
    your application, as well as any information requested.

    If the signed_request is malformed or corrupted, False is returned.
    """
    try:
        l = signed_request.split(".", 2)
        encoded_sig = str(l[0])
        payload = str(l[1])
        sig = base64.urlsafe_b64decode(encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4))
        data = base64.urlsafe_b64decode(payload + "=" * ((4 - len(payload) % 4) % 4))
    except IndexError:
        # Signed request was malformed.
        return False
    except TypeError:
        # Signed request had a corrupted payload.
        return False

    data = _parse_json(data)
    if data.get("algorithm", "").upper() != "HMAC-SHA256":
        return False

    expected_sig = hmac.new(app_secret, msg=payload, digestmod=hashlib.sha256).digest()
    if sig != expected_sig:
        return False

    return data
Esempio n. 14
0
    def __init__(self, subscription_info):
        """Initialize using the info provided by the client PushSubscription
        object (See
        https://developer.mozilla.org/en-US/docs/Web/API/PushManager/subscribe)

        :param subscription_info: a dict containing the subscription_info from
            the client.

        """
        if 'endpoint' not in subscription_info:
            raise WebPushException("subscription_info missing endpoint URL")
        if 'keys' not in subscription_info:
            raise WebPushException("subscription_info missing keys dictionary")
        self.subscription_info = subscription_info
        keys = self.subscription_info['keys']
        for k in ['p256dh', 'auth']:
            if keys.get(k) is None:
                raise WebPushException("Missing keys value: %s", k)
            if isinstance(keys[k], six.string_types):
                keys[k] = bytes(keys[k].encode('utf8'))
        receiver_raw = base64.urlsafe_b64decode(self._repad(keys['p256dh']))
        if len(receiver_raw) != 65 and receiver_raw[0] != "\x04":
            raise WebPushException("Invalid p256dh key specified")
        self.receiver_key = receiver_raw
        self.auth_key = base64.urlsafe_b64decode(self._repad(keys['auth']))
Esempio n. 15
0
def parse_signed_request(signed_request, app_secret):
    # translated to Python from PHP example at:
    # http://developers.facebook.com/docs/authentication/signed_request/
    split_request = signed_request.split(".", 2)
    
    encoded_sig = str(split_request[0])
    payload = str(split_request[1])
    
    # decode
    decoded_sig = base64.urlsafe_b64decode(encoded_sig + "==")
    data = json.loads(base64.urlsafe_b64decode(payload + "=="))
    
    # verify signature
    if data["algorithm"] != "HMAC-SHA256":
        raise ValueError("Unknown algorithm. Expected HMAC-SHA256")
    else:
        expected_sig = hmac.new(
            app_secret, 
            msg=payload, 
            digestmod=hashlib.sha256
        ).digest()
    
    if decoded_sig != expected_sig:
        raise ValueError("Unexpected signature received.")
    
    return data
Esempio n. 16
0
	def filterTracksByPredicate(self, tracks, predicate):
		predicates = re.sub(r"\[(.+)\]", r"\1", predicate).replace('%3A', ':').split('|')
		#print len(tracks)
		#removed = 0
		newTracks = []
		for predicate in predicates:
			prType, cmpMode, data = predicate.split(':', 3)
			#print 'Type: ' + prType + ', data: ' + data
			for track in tracks:
				# Comparisons of format self.compare[cmpMode](data, --property--)
				if prType == 'nam':
					if self.compare[cmpMode](base64.urlsafe_b64decode(data), track['name']): newTracks.append(track)
				elif prType == 'alb':
					if self.compare[cmpMode](base64.urlsafe_b64decode(data), track['album']): newTracks.append(track)
				elif prType == 'art':
					if self.compare[cmpMode](base64.urlsafe_b64decode(data), track['artist']): newTracks.append(track)
				elif prType == 'gen':
					if self.compare[cmpMode](base64.urlsafe_b64decode(data), track['genre']): newTracks.append(track)
				elif prType == 'cmp':
					if self.compare[cmpMode](base64.urlsafe_b64decode(data), track['composer']): newTracks.append(track)
				elif prType == 'plc':
					if self.compare[cmpMode](int(data), track['playCount']): newTracks.append(track)
				elif prType == 'rat':
					if self.compare[cmpMode](int(data), track['rating']): newTracks.append(track)
		#print len(tracks)
		#print 'Removed: ' + str(removed)
		return newTracks
Esempio n. 17
0
def extractRequestFromFileId( fileId ):
  stub = fileId[2:]
  compressType = fileId[0]
  if compressType == 'Z':
    gLogger.info( "Compressed request, uncompressing" )
    try:
      stub = base64.urlsafe_b64decode( stub )
    except Exception as e:
      gLogger.error( "Oops! Plot request is not properly encoded!", str( e ) )
      return S_ERROR( "Oops! Plot request is not properly encoded!: %s" % str( e ) )
    try:
      stub = zlib.decompress( stub )
    except Exception as e:
      gLogger.error( "Oops! Plot request is invalid!", str( e ) )
      return S_ERROR( "Oops! Plot request is invalid!: %s" % str( e ) )
  elif compressType == 'S':
    gLogger.info( "Base64 request, decoding" )
    try:
      stub = base64.urlsafe_b64decode( stub )
    except Exception as e:
      gLogger.error( "Oops! Plot request is not properly encoded!", str( e ) )
      return S_ERROR( "Oops! Plot request is not properly encoded!: %s" % str( e ) )
  elif compressType == 'R':
    #Do nothing, it's already uncompressed
    pass
  else:
    gLogger.error( "Oops! Stub type is unknown", compressType )
    return S_ERROR( "Oops! Stub type '%s' is unknown :P" % compressType )
  plotRequest, stubLength = DEncode.decode( stub )
  if len( stub ) != stubLength:
    gLogger.error( "Oops! The stub is longer than the data :P" )
    return S_ERROR( "Oops! The stub is longer than the data :P" )
  return S_OK( plotRequest )
Esempio n. 18
0
    def _build_protobuf(self):
        """Build a query protobuf.

        Relies on the current state of the iterator.

        :rtype:
            :class:`google.cloud.datastore._generated.query_pb2.Query`
        :returns: The query protobuf object for the current
                  state of the iterator.
        """
        pb = _pb_from_query(self._query)

        start_cursor = self.next_page_token
        if start_cursor is not None:
            pb.start_cursor = base64.urlsafe_b64decode(start_cursor)

        end_cursor = self._end_cursor
        if end_cursor is not None:
            pb.end_cursor = base64.urlsafe_b64decode(end_cursor)

        if self.max_results is not None:
            pb.limit.value = self.max_results - self.num_results

        if self._offset is not None:
            # NOTE: The offset goes down relative to the location
            #       because we are updating the cursor each time.
            pb.offset = self._offset - self._skipped_results

        return pb
def replace_b64_in_dict(item):
  """
  Replace base64 string in python dictionary of inference data. Refer to https://github.com/tensorflow/serving/blob/master/tensorflow_serving/g3doc/api_rest.md#encoding-binary-values .
  
  For example: {'inputs': {'images': {'b64': 'YWJjZGVmZ2hpMTIz'}, 'foo': 'bar'}} to {'inputs': {'images': 'abcdefghi123', 'foo': 'bar'}}.
  """

  if isinstance(item, dict):
    # Use items for Python 3 instead of iteritems
    for key, value in item.items():
      if isinstance(value, dict) and list(value.keys())[0] == "b64":
        # Use list to wrap .keys() and .values() for Python 3
        b64_string = list(value.values())[0]
        # TODO: unicode string to string
        b64_string = str(b64_string)
        bytearray_string = base64.urlsafe_b64decode(b64_string)
        item[key] = bytearray_string
      else:
        replace_b64_in_dict(value)

  elif isinstance(item, list):
    for index, value in enumerate(item):
      if isinstance(value, dict) and list(value.keys())[0] == "b64":
        b64_string = list(value.values())[0]
        b64_string = str(b64_string)
        bytearray_string = base64.urlsafe_b64decode(b64_string)
        item[index] = bytearray_string
      else:
        replace_b64_in_dict(value)
Esempio n. 20
0
def decrypt(ciphertext, secret, inital_vector, checksum=True, lazy=True):
    """Decrypts ciphertext with secret
    ciphertext     - encrypted content to decrypt
    secret         - secret to decrypt ciphertext
    inital_vector  - initial vector
    lazy           - pad secret if less than legal blocksize (default: True)
    checksum       - verify crc32 byte encoded checksum (default: True)
    returns plaintext
    """
    secret = _lazysecret(secret) if lazy else secret
    encobj = AES.new(secret, AES.MODE_CFB, inital_vector)
    try:
        padded = ciphertext + ('=' * (len(ciphertext) % 4))
        decoded = base64.urlsafe_b64decode(str(padded))
        plaintext = encobj.decrypt(decoded)
    except (TypeError, binascii.Error):
        raise InvalidKeyError("invalid key")

    if checksum:
        try:
            crc, plaintext = (base64.urlsafe_b64decode(
                plaintext[-8:]), plaintext[:-8])
        except (TypeError, binascii.Error):
            raise CheckSumError("checksum mismatch")

        if not crc == _pack_crc(plaintext):
            raise CheckSumError("checksum mismatch")

    return plaintext
Esempio n. 21
0
    def get_sources(self, url, hosthdDict, hostDict, locDict):
        try:
            sources = []

            if url == None: return sources

            url = urlparse.urljoin(self.base_link, url)

            result = client.source(url)
            links = re.compile("/watch\.php\?q=(.+?)'").findall(result)

            for i in links:
                try:
                    url = base64.urlsafe_b64decode(i.encode('utf-8'))
                    url = client.replaceHTMLCodes(url)
                    url = url.encode('utf-8')

                    host = base64.urlsafe_b64decode(i.encode('utf-8'))
                    host = urlparse.urlparse(host).netloc
                    host = host.rsplit('.', 1)[0].split('.', 1)[-1]
                    host = host.strip().lower()
                    if not host in hostDict: raise Exception()
                    host = client.replaceHTMLCodes(host)
                    host = host.encode('utf-8')

                    sources.append({'source': host, 'quality': 'SD', 'provider': 'Filmikz', 'url': url})
                except:
                    pass

            return sources
        except:
            return sources
Esempio n. 22
0
def base64_url_decode(inp):
    if sys.version > "3":
        if isinstance(inp, bytes):
            inp = inp.decode()
        return base64.urlsafe_b64decode(inp + '=' * (4 - len(inp) % 4)).decode()
    else:
        return base64.urlsafe_b64decode(str(inp + '=' * (4 - len(inp) % 4)))
Esempio n. 23
0
    def process_salmon_envelope(self, xml, key):
        """
        Given the Slap XML, extract out the author and payload.
        """
        xml = xml.lstrip().encode("utf-8")
        doc = etree.fromstring(xml)
        header = doc.find(".//{" + PROTOCOL_NS + "}header")
        if header is not None:  # Public
            encrypted = False
            sender = header.find(".//{" + PROTOCOL_NS + "}author_id").text
        else:
            header = self.parse_header(doc.find(".//{" + PROTOCOL_NS + "}encrypted_header").text, key)
            encrypted = True
            sender = header.find(".//author_id").text

        sending_contact = self.contact_fetcher(sender).contact
        body = doc.find(".//{http://salmon-protocol.org/ns/magic-env}data").text
        sig = doc.find(".//{http://salmon-protocol.org/ns/magic-env}sig").text
        self.verify_signature(sending_contact, body, sig.encode("ascii"))

        if encrypted:
            inner_iv = b64decode(header.find(".//iv").text.encode("ascii"))
            inner_key = b64decode(header.find(".//aes_key").text.encode("ascii"))

            decrypter = AES.new(inner_key, AES.MODE_CBC, inner_iv)
            body = b64decode(urlsafe_b64decode(body.encode("ascii")))
            body = decrypter.decrypt(body)
            body = self.pkcs7_unpad(body)
        else:
            body = urlsafe_b64decode(body.encode("ascii"))

        return body, sending_contact
Esempio n. 24
0
 def test_encode(self):
     for content_encoding in ["aesgcm", "aes128gcm"]:
         recv_key = ec.generate_private_key(
             ec.SECP256R1, default_backend())
         subscription_info = self._gen_subscription_info(recv_key)
         data = "Mary had a little lamb, with some nice mint jelly"
         push = WebPusher(subscription_info)
         encoded = push.encode(data, content_encoding=content_encoding)
         """
         crypto_key = base64.urlsafe_b64encode(
             self._get_pubkey_str(recv_key)
         ).strip(b'=')
         """
         # Convert these b64 strings into their raw, binary form.
         raw_salt = None
         if 'salt' in encoded:
             raw_salt = base64.urlsafe_b64decode(
                 push._repad(encoded['salt']))
         raw_dh = None
         if content_encoding != "aes128gcm":
             raw_dh = base64.urlsafe_b64decode(
                 push._repad(encoded['crypto_key']))
         raw_auth = base64.urlsafe_b64decode(
             push._repad(subscription_info['keys']['auth']))
         decoded = http_ece.decrypt(
             encoded['body'],
             salt=raw_salt,
             dh=raw_dh,
             private_key=recv_key,
             auth_secret=raw_auth,
             version=content_encoding
             )
         eq_(decoded.decode('utf8'), data)
Esempio n. 25
0
    def test_encode(self):
        recv_key = pyelliptic.ECC(curve="prime256v1")
        subscription_info = self._gen_subscription_info(recv_key)
        data = "Mary had a little lamb, with some nice mint jelly"
        push = WebPusher(subscription_info)
        encoded = push.encode(data)

        keyid = base64.urlsafe_b64encode(recv_key.get_pubkey()[1:])

        http_ece.keys[keyid] = recv_key
        http_ece.labels[keyid] = 'P-256'

        # Convert these b64 strings into their raw, binary form.
        raw_salt = base64.urlsafe_b64decode(push._repad(encoded['salt']))
        raw_dh = base64.urlsafe_b64decode(push._repad(encoded['crypto_key']))
        raw_auth = base64.urlsafe_b64decode(
            push._repad(subscription_info['keys']['auth']))

        decoded = http_ece.decrypt(
            buffer=encoded['body'],
            salt=raw_salt,
            dh=raw_dh,
            keyid=keyid,
            authSecret=raw_auth
            )

        eq_(decoded, data)
Esempio n. 26
0
def highlightSmilesFragmentSvg(smarts, smiles):
    """
Converts SMILES to SVG vector graphic with a highlighted fragment described as SMARTS. 
This method accepts urlsafe_base64 encoded string containing SMARTS with a fragment to be highlighted, urlsafe_base64 
encoded string containing single or multiple SMILES optionally containing header line, specific to *.smi format. 
Size is the optional size of image in pixels (default value is 200 px). Legend is optional label in the bottom of image.
cURL examples:

    curl -X GET ${BEAKER_ROOT_URL}highlightSmilesFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat aspirin_no_header.smi | base64 -w 0 | tr "+/" "-_") > aspirin_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightSmilesFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat aspirin_no_header.smi | base64 -w 0 | tr "+/" "-_")?atomMapNumber=1 > aspirin_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightSmilesFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat aspirin_no_header.smi | base64 -w 0 | tr "+/" "-_")?legend=aspirin > aspirin_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightSmilesFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat aspirin_no_header.smi | base64 -w 0 | tr "+/" "-_")?size=400 > aspirin_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightSmilesFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat aspirin_with_header.smi | base64 -w 0 | tr "+/" "-_") > aspirin_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightSmilesFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat aspirin_with_header.smi | base64 -w 0 | tr "+/" "-_")?legend=aspirin > aspirin_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightSmilesFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat aspirin_with_header.smi | base64 -w 0 | tr "+/" "-_")?size=400 > aspirin_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightSmilesFragmentSvg/$(cat aspirin.sma | base64 -w 0 | tr "+/" "-_")/$(cat CHEMBL1999443.smi | base64 -w 0 | tr "+/" "-_")?force=true > aspirin_highlighted_forced.svg
    curl -X GET "${BEAKER_ROOT_URL}highlightSmilesFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/"$(cat mcs.smi | base64 -w 0 | tr "+/" "-_")"?legend=foo|bar|bla" > out_highlighted.svg
    curl -X GET "${BEAKER_ROOT_URL}highlightSmilesFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/"$(cat mcs_no_header.smi | base64 -w 0 | tr "+/" "-_")"?legend=foo|bar|bla" > out_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightSmilesFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat mcs.smi | base64 -w 0 | tr "+/" "-_")?legend=foo > out_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightSmilesFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat mcs_no_header.smi | base64 -w 0 | tr "+/" "-_")?legend=foo > out_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightSmilesFragmentSvg/$(cat aspirin.sma | base64 -w 0 | tr "+/" "-_")/$(cat CHEMBL1999443.smi | base64 -w 0 | tr "+/" "-_")?force=true > out_highlighted_forced.svg    
    """

    data = base64.urlsafe_b64decode(smiles)

    params = request.params
    params['smarts'] = base64.urlsafe_b64decode(smarts)

    return highlightSmilesFragmentSvgView(data, params=params)
Esempio n. 27
0
    def test_next_page_w_cursors_w_more(self):
        from base64 import urlsafe_b64decode
        from base64 import urlsafe_b64encode
        from gcloud.datastore.query import _pb_from_query
        connection = _Connection()
        client = self._makeClient(connection)
        query = _Query(client, self._KIND, self._PROJECT, self._NAMESPACE)
        self._addQueryResults(connection, cursor=self._END, more=True)
        iterator = self._makeOne(query, client)
        iterator._start_cursor = self._START
        iterator._end_cursor = self._END
        entities, more_results, cursor = iterator.next_page()

        self.assertEqual(cursor, urlsafe_b64encode(self._END))
        self.assertTrue(more_results)
        self.assertTrue(iterator._more_results)
        self.assertEqual(iterator._end_cursor, None)
        self.assertEqual(urlsafe_b64decode(iterator._start_cursor), self._END)
        self.assertEqual(len(entities), 1)
        self.assertEqual(entities[0].key.path,
                         [{'kind': self._KIND, 'id': self._ID}])
        self.assertEqual(entities[0]['foo'], u'Foo')
        qpb = _pb_from_query(query)
        qpb.offset = 0
        qpb.start_cursor = urlsafe_b64decode(self._START)
        qpb.end_cursor = urlsafe_b64decode(self._END)
        EXPECTED = {
            'project': self._PROJECT,
            'query_pb': qpb,
            'namespace': self._NAMESPACE,
            'transaction_id': None,
        }
        self.assertEqual(connection._called_with, [EXPECTED])
Esempio n. 28
0
def highlightCtabFragmentSvg(smarts, ctab):
    """
Converts SMILES to SVG vector graphic with a highlighted fragment described as SMARTS. 
SMARTS is urlsafe_base64 encoded string containing fragment ot ge highlighted.
CTAB is urlsafe_base64 encoded string containing single molfile or concatenation of multiple molfiles. 
Size is the optional size of image in pixels (default value is 200 px).
Legend is optional label in the bottom of image.
cURL examples:

    curl -X GET ${BEAKER_ROOT_URL}highlightCtabFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat aspirin.mol | base64 -w 0 | tr "+/" "-_") > aspirin_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightCtabFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat aspirin.mol | base64 -w 0 | tr "+/" "-_")?computeCoords=0 > aspirin_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightCtabFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat aspirin.mol | base64 -w 0 | tr "+/" "-_")?atomMapNumber=1 > aspirin_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightCtabFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat aspirin.mol | base64 -w 0 | tr "+/" "-_")?legend=aspirin > aspirin_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightCtabFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat aspirin.mol | base64 -w 0 | tr "+/" "-_")?size=400 > aspirin_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightCtabFragmentSvg/$(cat aspirin.sma | base64 -w 0 | tr "+/" "-_")/$(cat CHEMBL1999443.mol | base64 -w 0 | tr "+/" "-_")?force=true > out_highlighted_forced.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightCtabFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat mcs.sdf | base64 -w 0 | tr "+/" "-_")"?legend=foo|bar|bla" > out_highlighted.svg
    curl -X GET ${BEAKER_ROOT_URL}highlightCtabFragmentSvg/$(echo c1ccccc1 | base64 -w 0 | tr "+/" "-_")/$(cat mcs.sdf | base64 -w 0 | tr "+/" "-_")"?legend=foo|bar|bla&computeCoords=0" > out_highlighted.svg    
    """

    data = base64.urlsafe_b64decode(ctab)

    params = request.params
    params['smarts'] = base64.urlsafe_b64decode(smarts)

    return highlightCtabFragmentSvgView(data, params)
Esempio n. 29
0
    def get_session(self, request):
        session = None
        value = self.get_cookie(request)
        # FIXME validate remote IP, treat as 'user input',
        remote_ip = self.get_remote_ip(request)

        if value is not None:
            assert isinstance(value, text_type)
            if (len(value) == self.cookie_value_len and
                    self.re_cookie_value.match(value)):
                try:
                    sid, key = value.encode('ascii').split(b':', 1)
                    sid = base64.urlsafe_b64decode(sid)
                    sid = uuid.UUID(bytes=sid)
                    key = base64.urlsafe_b64decode(key)
                except (ValueError, TypeError):
                    logger.debug('Invalid cookie value could not be parsed')
                else:
                    logger.debug('Loading session %s', sid)
                    data = self.store.load(sid)
                    if data:
                        session = self.session_class(handler=self, session_id=sid,
                                key=key, remote_ip=remote_ip, data=data)
                        logger.debug('Session %s loaded', sid)
            else:
                logger.debug('Invalid session cookie value')

        if session is None:
            session = self.session_class(handler=self, remote_ip=remote_ip)

        return session
Esempio n. 30
0
  def xmlrpc_resetpassword_confirm(self, token, mac):
    def badconfirmlinkmsg():
      return self.Fault('Your confirm link was invalid; contact acctserv@hcs '\
          'further assistance.')

    token = (token or '').strip()
    mac = (mac or '').strip()
    cryptor = AES.new(self.secret_cipher, AES.MODE_ECB)

    try:
      plaintext = cryptor.decrypt(base64.urlsafe_b64decode(token))
      mac = base64.urlsafe_b64decode(mac)
    except ValueError: # if the code is a not a multiple of 16 bytes long
      raise badconfirmlinkmsg()
    except TypeError: # invalid padding
      raise badconfirmlinkmsg()
      
    if self.computeMAC(plaintext) != mac:
      raise badconfirmlinkmsg()

    # A proper listvars is of the form
    # [ listname, padding ]
    listvars = plaintext.split("\x00")
    if len(listvars) == 2:
      listname = listvars[0]
    
      # reset password; else return error
      p = subprocess.Popen(('/usr/lib/mailman/bin/change_pw', '-l', listname),
                       stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      retcode = p.wait()

      admins = ', '.join(self.get_admins(listname))
      if retcode is 0:
        # return success message
        output = p.stdout.read()
        mail('*****@*****.**', self.log_password_success_message % {
            'date' : Utils.formatdate(localtime = True),
            'messageid' : Utils.make_msgid(),
            'listname': listname,
            'listadmin': admins})

        return listname

      else:
        # non-standard problem -- e-mail systems/acctserv
        output = p.stdout.read()
        outerr = p.stderr.read()
        mail('*****@*****.**', self.unknown_mailman_password_error % {
            'date' : Utils.formatdate(localtime = True),
            'messageid' : Utils.make_msgid(),
            'listname' : listname,
            'listadmin' : admins,
            'output' : output,
            'outerr' : outerr })
        # return unknown error
        raise self.Fault('Internal error. The systems team has been notified '\
            'and will be getting back to you.')
          
    else: # User submitted bad hash
      raise badconfirmlinkmsg()
Esempio n. 31
0
# Temporary variables
    jwt = sys.argv[1]
    key = ""
    if len(sys.argv) == 3:
        keyList = sys.argv[2]
        with open(keyList, "rb") as f:
            keyLst = f.readlines()
        keyLst = [x.strip() for x in keyLst]
    else:
        keyList = ""

# Rejig token
    try:
        tok1, tok2, sig = jwt.split(".",3)
        sig = base64.urlsafe_b64encode(base64.urlsafe_b64decode(sig + "=" * (-len(sig) % 4))).decode('UTF-8').strip("=")
        contents = tok1+"."+tok2
        contents = contents.encode()
        head = base64.b64decode(tok1 + "=" * (-len(tok1) % 4))
        payl = base64.b64decode(tok2 + "=" * (-len(tok2) % 4))
        headDict = json.loads(head, object_pairs_hook=OrderedDict)
        paylDict = json.loads(payl, object_pairs_hook=OrderedDict)
    except:
        print("Oh noes! Invalid token")
        exit(1)

# Main menu
    print("\n=====================\nDecoded Token Values:\n=====================")
    print("\nToken header values:")
    for i in headDict:
          print("[+] "+i+" = "+str(headDict[i]))
Esempio n. 32
0
def decode_base64(value):
    """Decodes base64url-encoded string"""
    encoded = value.encode('utf-8') # base64 expects binary string as input
    return base64.urlsafe_b64decode(encoded).decode('utf-8')
Esempio n. 33
0
    def do_download(self, request):
        logger.debug(f'Download: args: {request.args}')

        #receber o uuid do client
        req = request.content.read()
        req = json.loads(req.decode())

        signature = base64.b64decode(req["signature"].encode())
        data_signed = json.loads(req["data"])
        uuid = data_signed["uuid"]

        client_cert = self.users[uuid]["client_cert"]
        client_public_key_rsa = client_cert.public_key()

        #Verificar a assinatura
        if self.users[uuid]["digest"] == "SHA256":
            client_public_key_rsa.verify(
                signature, req["data"].encode(),
                paddingAsymetric.PSS(
                    mgf=paddingAsymetric.MGF1(hashes.SHA256()),
                    salt_length=paddingAsymetric.PSS.MAX_LENGTH),
                hashes.SHA256())
        elif self.users[uuid]["digest"] == "SHA512":
            client_public_key_rsa.verify(
                signature, req["data"].encode(),
                paddingAsymetric.PSS(
                    mgf=paddingAsymetric.MGF1(hashes.SHA512()),
                    salt_length=paddingAsymetric.PSS.MAX_LENGTH),
                hashes.SHA512())
        else:
            print("Erro")
            sys.exit(0)

        if self.users[uuid]["Autenticado"]:
            pass
        else:
            return "Erro, user nao autenticado"

        media_id = request.args.get(b'id', [None])[0]
        logger.debug(f'Download: id: {media_id}')
        media_id = base64.urlsafe_b64decode(media_id)

        chunk_id = request.args.get(b'chunk', [b'0'])[0]
        chunk_id = base64.urlsafe_b64decode(chunk_id)

        #decript media_id e chunk
        if self.users[uuid]["algorithm"] == "AES256":
            iv = data_signed["iv"].encode()
            iv = base64.b64decode(iv)
            iv2 = data_signed["iv2"].encode()
            iv2 = base64.b64decode(iv2)

            key = self.users[uuid]["shared_key"]

            if self.users[uuid]["mode"] == "CBC":
                media_id = self.decrypt_AES(key, iv, media_id, "CBC")
                chunk_id = self.decrypt_AES(key, iv2, chunk_id, "CBC")
            elif self.users[uuid]["mode"] == "GCM":
                tag1 = data_signed["tag1"].encode()
                tag1 = base64.b64decode(tag1)
                tag2 = data_signed["tag2"].encode()
                tag2 = base64.b64decode(tag2)
                media_id = self.decrypt_AES(key, iv, media_id, "GCM", tag1)
                chunk_id = self.decrypt_AES(key, iv2, chunk_id, "GCM", tag2)

        elif self.users[uuid]["algorithm"] == "ChaCha20":
            nonce = data_signed["nonce"].encode()
            nonce = base64.b64decode(nonce)
            nonce2 = data_signed["nonce_chunk"].encode()
            nonce2 = base64.b64decode(nonce2)

            key = self.users[uuid]["shared_key"]
            media_id = self.decrypt_ChaCha20(key, nonce, media_id)
            chunk_id = self.decrypt_ChaCha20(key, nonce2, chunk_id)

        else:
            print("Erro1")
            sys.exit(0)

        # Check if the media_id is not None as it is required
        if media_id is None:
            request.setResponseCode(400)
            request.responseHeaders.addRawHeader(b"content-type",
                                                 b"application/json")
            return json.dumps({'error': 'invalid media id'}).encode('latin')

        # Convert bytes to str
        media_id = media_id.decode('latin')

        # Search media_id in the catalog
        if media_id not in CATALOG:
            request.setResponseCode(404)
            request.responseHeaders.addRawHeader(b"content-type",
                                                 b"application/json")
            return json.dumps({
                'error': 'media file not found'
            }).encode('latin')

        # Get the media item
        media_item = CATALOG[media_id]

        valid_chunk = False
        try:
            chunk_id = int(chunk_id.decode('latin'))
            if chunk_id >= 0 and chunk_id < math.ceil(
                    media_item['file_size'] / CHUNK_SIZE):
                valid_chunk = True
        except:
            logger.warn("Chunk format is invalid")

        if not valid_chunk:
            request.setResponseCode(400)
            request.responseHeaders.addRawHeader(b"content-type",
                                                 b"application/json")
            return json.dumps({'error': 'invalid chunk id'}).encode('latin')

        licenca = self.users[uuid]["licenca"]
        cipher_l = Cipher(algorithms.ChaCha20(key_to_files,
                                              self.nonce_for_licence),
                          mode=None)
        decryptor_l = cipher_l.decryptor()
        licenca_d = decryptor_l.update(licenca) + decryptor_l.finalize()
        licenca = json.loads(licenca_d.decode())

        if licenca[uuid]["usos"] == 0:
            print("Client nao tem licenca para ouvir a musica")

            data = {'error': 'Nao tem licenca para ouvir a musica'}
            data = json.dumps(data)
            signature = self.sign(data, self.users[uuid]["digest"])

            request.responseHeaders.addRawHeader(b"content-type",
                                                 b"application/json")
            return json.dumps({
                "data":
                data,
                "signature":
                base64.b64encode(signature).decode('latin')
            }).encode('latin')
        else:
            licenca[uuid]["usos"] -= 1
            licenca = json.dumps(licenca).encode()
            cipher_l = Cipher(algorithms.ChaCha20(key_to_files,
                                                  self.nonce_for_licence),
                              mode=None)
            encryptor_l = cipher_l.encryptor()
            licenca_e = encryptor_l.update(licenca) + encryptor_l.finalize()
            self.users[uuid]["licenca"] = licenca_e

        logger.debug(f'Download: chunk: {chunk_id}')

        offset = chunk_id * CHUNK_SIZE

        # Open file, seek to correct position and return the chunk
        with open(os.path.join(CATALOG_BASE, media_item['file_name']),
                  'rb') as f:

            f.seek(offset)
            data = f.read(CHUNK_SIZE)

            decryptor_filess = self.users[uuid]["decriptor"]
            data = decryptor_filess.update(data)

            info = json.dumps(
                {
                    'media_id': media_id,
                    'chunk': chunk_id,
                    'data': binascii.b2a_base64(data).decode('latin').strip()
                },
                indent=4).encode('latin')

            if self.users[uuid]["algorithm"] == "ChaCha20":
                salt = os.urandom(16)

                #Encript then MAC
                if self.users[uuid]["digest"] == "SHA256":
                    #Derivar chave
                    kdf = PBKDF2HMAC(
                        algorithm=hashes.SHA256(),
                        length=32,
                        salt=salt,
                        iterations=100000,
                    )
                    key = kdf.derive(self.users[uuid]["shared_key"])

                    data_encrypted, nonce = self.encrypt_ChaCha20(key, info)

                    h = hmac.HMAC(key, hashes.SHA256())
                    h.update(data_encrypted)
                    MAC = h.finalize()

                elif self.users[uuid]["digest"] == "SHA512":
                    #Derivar chave
                    kdf = PBKDF2HMAC(
                        algorithm=hashes.SHA512(),
                        length=32,
                        salt=salt,
                        iterations=100000,
                    )
                    key = kdf.derive(self.users[uuid]["shared_key"])

                    data_encrypted, nonce = self.encrypt_ChaCha20(key, info)
                    h = hmac.HMAC(key, hashes.SHA512())
                    h.update(data_encrypted)
                    MAC = h.finalize()

                else:
                    print("Erro")
                    sys.exit(0)

                nonce = base64.b64encode(nonce).decode('latin')
                data_encrypted = base64.b64encode(data_encrypted).decode(
                    'latin')
                MAC = base64.b64encode(MAC).decode('latin')
                salt = base64.b64encode(salt).decode('latin')

                data = {
                    "data": data_encrypted,
                    "nonce": nonce,
                    "MAC": MAC,
                    "salt": salt
                }
                data = json.dumps(data)

                signature = self.sign(data, self.users[uuid]["digest"])
                payload = {
                    "data": data,
                    "signature": base64.b64encode(signature).decode('latin')
                }

                request.setResponseCode(200)
                request.responseHeaders.addRawHeader(b"content-type",
                                                     b"application/json")
                return json.dumps(payload).encode('latin')

            elif self.users[uuid]["algorithm"] == "AES256":
                salt = os.urandom(16)

                if self.users[uuid]["digest"] == "SHA256":
                    #Derivar chave
                    kdf = PBKDF2HMAC(
                        algorithm=hashes.SHA256(),
                        length=32,
                        salt=salt,
                        iterations=100000,
                    )
                    key = kdf.derive(self.users[uuid]["shared_key"])

                elif self.users[uuid]["digest"] == "SHA512":
                    #Derivar chave
                    kdf = PBKDF2HMAC(
                        algorithm=hashes.SHA512(),
                        length=32,
                        salt=salt,
                        iterations=100000,
                    )
                    key = kdf.derive(self.users[uuid]["shared_key"])

                else:
                    print("Erro3")
                    sys.exit(0)

                if self.users[uuid]["mode"] == "CBC":
                    data_encrypted, iv = self.encrypt_AES(key, info, "CBC")
                    tag = None
                elif self.users[uuid]["mode"] == "GCM":
                    data_encrypted, iv, tag = self.encrypt_AES(
                        key, info, "GCM")

                #Encript then MAC
                c = cmac.CMAC(algorithms.AES(key))
                c.update(data_encrypted)
                MAC = c.finalize()

                iv = base64.b64encode(iv).decode('latin')
                data_encrypted = base64.b64encode(data_encrypted).decode(
                    'latin')
                MAC = base64.b64encode(MAC).decode('latin')

                salt = base64.b64encode(salt).decode('latin')

                if tag:
                    tag = base64.b64encode(tag).decode('latin')
                    data = {
                        "data": data_encrypted,
                        "iv": iv,
                        "MAC": MAC,
                        "salt": salt,
                        "tag": tag
                    }
                else:
                    data = {
                        "data": data_encrypted,
                        "iv": iv,
                        "MAC": MAC,
                        "salt": salt
                    }

                data = json.dumps(data)
                signature = self.sign(data, self.users[uuid]["digest"])
                payload = {
                    "data": data,
                    "signature": base64.b64encode(signature).decode('latin')
                }

                request.setResponseCode(200)
                request.responseHeaders.addRawHeader(b"content-type",
                                                     b"application/json")
                return json.dumps(payload).encode('latin')

            else:
                print("erro")

        # File was not open?
        request.responseHeaders.addRawHeader(b"content-type",
                                             b"application/json")
        return json.dumps({'error': 'unknown'}, indent=4).encode('latin')
Esempio n. 34
0
def decrypt(encoded):
    try:
        return unpad(cipher.decrypt(base64.urlsafe_b64decode(encoded)))
    except:
        return False
Esempio n. 35
0
def decode_value(val):
    decoded = base64.urlsafe_b64decode(ensure_bytes(val) + b'==')
    return int.from_bytes(decoded, 'big')
Esempio n. 36
0
def Checking_Exploiting_KID():

    url = raw_input('Please Enter URL(with http | https): ')
    session = requests.Session()
    session.headers[u'User-Agent'] = \
        u'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
    html = session.get(url).content
    soup = bs(html, u'html.parser')
    files = []
    script_files = []

    for script in soup.find_all(u'script'):
        if script.attrs.get(u'src'):

            script_url = urljoin(url, script.attrs.get(u'src'))
            script_files.append(script_url)

    css_files = []

    for css in soup.find_all(u'link'):
        if css.attrs.get(u'href'):

            css_url = urljoin(url, css.attrs.get(u'href'))
            css_files.append(css_url)

    print u'Total script files in the page:', len(script_files)
    print u'Total CSS files in the page:', len(css_files)

    i = 1
    for js_file in script_files:
        print t.green('[' + str(i) + '] ' + js_file)
        i = i + 1
        files.insert(i, str(js_file))

    for css_file in css_files:
        print t.green('[' + str(i) + '] ' + css_file)
        i = i + 1
        files.insert(i, str(css_file))

    fid = \
        raw_input('Which one of these files do you want to set as a  key(1,2,..): '
                  )
    os.system('rm -rf key.txt')
    os.system('wget -O key.txt ' + files[int(fid) - 1])
    file = open('key.txt', 'r')
    key = file.read()

    jwt = raw_input('Please Enter Your JWT: ')
    jwt = jwt.split('.')
    header = base64.urlsafe_b64decode(jwt[0] + '==')
    payload = base64.urlsafe_b64decode(jwt[1] + '==')

    print 'Header: ' + header
    print 'Payload: ' + payload
    header = raw_input('Please Enter New Header(Change KID): ')
    payload = raw_input('Please Enter New Payload: ')
    print 'Header: ' + header
    print 'Payload: ' + payload
    strr = base64.b64encode(header) + '.' + base64.b64encode(payload)
    strr = strr.replace('=', '')
    sig = base64.urlsafe_b64encode(
        hmac.new(key, strr,
                 hashlib.sha256).digest()).decode('UTF-8').rstrip('=')
    print t.green(strr + '.' + sig)
Esempio n. 37
0
 def decode64(self, b64):
     return json.loads(base64.urlsafe_b64decode(b64 + '==='))
Esempio n. 38
0
print "Processing - Removing known domain name...."
message = message[0:-len(domainname)]

print "Processing - Making remaining string base64 complient..."
chunkNumber, chunkData = message.split('.', 1)
chunkNumber = int(chunkNumber)  # We have only one chunk with index 0
dataChunks = []
dataChunks.append(chunkData.replace(".", ""))
filedata = ''.join(dataChunks)
filedata = filedata.replace("_", "/").replace("-", "+")
filedata += "=" * ((4 - len(filedata) % 4) % 4)
filedata = bytearray(filedata, 'utf-8')

print "Processing - Undertaking base64 decode..."
filedata = base64.urlsafe_b64decode(filedata)

print "Processing - Undertaking RC4 decode..."
arc4 = ARC4(password)
filedata = arc4.decrypt(filedata)

print "Processing - Saving data to zipfile..."
with open("./secret.zip", 'w') as fileHandle:
    fileHandle.write(filedata)
fileHandle.close()

print "Processing - Opening zip file and reading data..."
os.system("unzip secret.zip > F1.txt")
readline = open(filename).readline().rstrip()

print "Processing - Tidying up system files...\n"
Esempio n. 39
0
def decode_id(encoded_id):
    padding = "=" * (len(encoded_id) % 3)
    return struct.unpack("!Q",
                         base64.urlsafe_b64decode(encoded_id + padding))[0]
Esempio n. 40
0
    def getwsmtraneventszipfromtrankeys(self, keystr):
        """
        keys strings are space delimited and in format: collection:request_message_id:response_message_id:be_request_message_id:be_response_message_id

"20160902.TestSplunk:57c9e0084c9ff841320dd2c2::: 20160902.TestSplunk:57c9e0084c9ff841320dd2be:57c9e0084c9ff841320dd2bf:57c9e0084c9ff841320dd2c0:57c9e0084c9ff841320dd2c1 20160902.TestSplunk:57c9dff94c9ff841320dd2ba:57c9dff94c9ff841320dd2bb:57c9dff94c9ff841320dd2bc:57c9dff94c9ff841320dd2bd 20160902.TestSplunk:57c9df804c9ff841320dd2b6:57c9df804c9ff841320dd2b7:57c9df804c9ff841320dd2b8:57c9df814c9ff841320dd2b9 20160902.TestSplunk:57c9df084c9ff841320dd2b2:57c9df084c9ff841320dd2b3:57c9df084c9ff841320dd2b4:57c9df084c9ff841320dd2b5"

created with search like:
index=esb*_syslog wsm_evt | getdpwsm | fields * | fillnull value="" collection,request_message_id,response_message_id,be_request_message_id,be_response_message_id| eval tran_key=collection.":".request_message_id.":".response_message_id.":".be_request_message_id.":".be_response_message_id    | stats list(tran_key) as tk | nomv tk

        """
        run_start_time = time.time()

        try:
            #print keystr
            decode_tks = base64.urlsafe_b64decode(keystr)
            #print "Decoded:", len(decode_tks), decode_tks
            decomped_tks = gzip.zlib.decompress(decode_tks)
            #print decomped_tks
            #tran_key_list = keystr.split(" ")
            tran_key_list = decomped_tks.split(" ")

            col_dict = {}
            for tk in tran_key_list:
                (tk_col, tk_req_id, tk_res_id, tk_be_req_id,
                 tk_be_res_id) = tk.split(":")

                if tk_col != "":
                    if not col_dict.has_key(tk_col):
                        col_dict[tk_col] = []

                    if tk_req_id != "":
                        col_dict[tk_col].append(
                            bson.objectid.ObjectId(tk_req_id))

                    if tk_res_id != "":
                        col_dict[tk_col].append(
                            bson.objectid.ObjectId(tk_res_id))

                    if tk_be_req_id != "":
                        col_dict[tk_col].append(
                            bson.objectid.ObjectId(tk_be_req_id))

                    if tk_be_res_id != "":
                        col_dict[tk_col].append(
                            bson.objectid.ObjectId(tk_be_res_id))

            if len(col_dict) == 0:
                return "No collections and keys found."

            z_name = "%s.zip" % uuid.uuid4()

            file = zipfile.ZipFile("%s" % z_name, "w", allowZip64=True)
            now = time.localtime(time.time())[:6]

            f_count = 0
            for collection, ids in col_dict.items():
                where_clause = {"_id": {"$in": ids}}
                #                print str(where_clause)
                for msg_doc in mongodb_db[collection].find(where_clause):
                    #print "here"
                    f_count = f_count + 1
                    dte = datetime.datetime.fromtimestamp(
                        msg_doc[u"starttimeutc"]).strftime("%Y%m%d%H%M%S")
                    info = zipfile.ZipInfo(
                        "%s_%s_%s_%s.xml" %
                        (dte, msg_doc[u"service"], msg_doc[u"tranid"],
                         msg_doc[u"payload_type"]))
                    info.date_time = now
                    info.compress_type = zipfile.ZIP_DEFLATED
                    file.writestr(
                        info,
                        zlib.decompress(
                            base64.decodestring(msg_doc[u"payload"]), -15))

            file.close()
            file = open("%s" % z_name, "rb")
            uncomp_msg_data = file.read()
            file.close()
            os.remove(z_name)

            if f_count == 0:
                cherrypy.response.headers['Content-type'] = "text/plain"
                return "No rows returned."

            cherrypy.response.headers[
                "Content-Disposition"] = "attachment; filename=Payloads_%s_%i.zip" % (
                    datetime.datetime.now().strftime("%Y%m%d_%H%M"), f_count)
            cherrypy.response.headers['Content-type'] = "application/zip"

            return uncomp_msg_data

        except Exception, ex:
            cherrypy.response.headers['Content-type'] = "text/plain"
            return "Error: %s" % str(ex)
Esempio n. 41
0
    def __init__(self, panodoc):
        self.PanoDoc = panodoc
        panoDocCtx = self.PanoDoc.xpathNewContext()

        self.PanoId = panoDocCtx.xpathEval(
            "/panorama/data_properties/@pano_id")[0].content
        self.ImageWidth = panoDocCtx.xpathEval(
            "/panorama/data_properties/@image_width")[0].content
        self.ImageHeight = panoDocCtx.xpathEval(
            "/panorama/data_properties/@image_height")[0].content
        self.TileWidth = panoDocCtx.xpathEval(
            "/panorama/data_properties/@tile_width")[0].content
        self.TileHeight = panoDocCtx.xpathEval(
            "/panorama/data_properties/@tile_height")[0].content
        self.NumZoomLevels = panoDocCtx.xpathEval(
            "/panorama/data_properties/@num_zoom_levels")[0].content
        self.Lat = panoDocCtx.xpathEval(
            "/panorama/data_properties/@lat")[0].content
        self.Lon = panoDocCtx.xpathEval(
            "/panorama/data_properties/@lng")[0].content
        self.OriginalLat = panoDocCtx.xpathEval(
            "/panorama/data_properties/@original_lat")[0].content
        self.OriginalLon = panoDocCtx.xpathEval(
            "/panorama/data_properties/@original_lng")[0].content
        # self.Copyright = panoDocCtx.xpathEval("/panorama/data_properties/copyright/text()")[0].content
        # self.Text = panoDocCtx.xpathEval("/panorama/data_properties/text/text()")[0].content
        # self.Region = panoDocCtx.xpathEval("/panorama/data_properties/region/text()")[0].content
        # self.Country = panoDocCtx.xpathEval("/panorama/data_properties/country/text()")[0].content

        self.ProjectionType = panoDocCtx.xpathEval(
            "/panorama/projection_properties/@projection_type")[0].content
        self.ProjectionPanoYawDeg = panoDocCtx.xpathEval(
            "/panorama/projection_properties/@pano_yaw_deg")[0].content
        self.ProjectionTiltYawDeg = panoDocCtx.xpathEval(
            "/panorama/projection_properties/@tilt_yaw_deg")[0].content
        self.ProjectionTiltPitchDeg = panoDocCtx.xpathEval(
            "/panorama/projection_properties/@tilt_pitch_deg")[0].content

        self.AnnotationLinks = []
        for cur in panoDocCtx.xpathEval(
                "/panorama/annotation_properties/link"):
            self.AnnotationLinks.append({
                'YawDeg':
                cur.xpathEval("@yaw_deg")[0].content,
                'PanoId':
                cur.xpathEval("@pano_id")[0].content,
                'RoadARGB':
                cur.xpathEval("@road_argb")[0].content,
                # 'Text': cur.xpathEval("link_text/text()")[0].content,
            })

        tmp = panoDocCtx.xpathEval("/panorama/model/pano_map/text()")
        if len(tmp) > 0:
            tmp = tmp[0].content
            tmp = zlib.decompress(
                base64.urlsafe_b64decode(tmp + self.MakePadding(tmp)))
            self.DecodePanoMap(tmp)

        tmp = panoDocCtx.xpathEval("/panorama/model/depth_map/text()")
        if len(tmp) > 0:
            tmp = tmp[0].content
            tmp = zlib.decompress(
                base64.urlsafe_b64decode(tmp + self.MakePadding(tmp)))
            self.DecodeDepthMap(tmp)
Esempio n. 42
0
fanart = os.path.join(addonFolder, 'fanart.jpg')
skin = 'v2'
alerta = xbmcgui.Dialog().ok
select = xbmcgui.Dialog().select
simNao = xbmcgui.Dialog().yesno
mensagemprogresso = xbmcgui.DialogProgress()
teclado = xbmc.Keyboard
pastaDados = Addon(addonInfo("id")).get_profile().decode("utf-8")
headers = {
    'User-Agent':
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:43.0) Gecko/20100101 Firefox/43.0',
    'Accept-Charset': 'utf-8;q=0.7,*;q=0.7',
    'Content-Type': 'application/json'
}
dataHoras = datetime.now()
API = base64.urlsafe_b64decode('aHR0cDovL21yYXBpLnh5ei8=')
API_SITE = base64.urlsafe_b64decode('aHR0cDovL21yYXBpLnh5ei9hcGluZXcv')
SITE = base64.urlsafe_b64decode('aHR0cDovL21ycGlyYWN5LmdxLw==')

try:
    import ssl
    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
except:
    pass


def addDir(name,
           url,
           modo,
           iconimage,
           pagina=False,
Esempio n. 43
0
# coding:utf-8
import base64

# 如果要編碼的二進制數據不是3的倍數,最後會剩下1個或2個字節怎麼辦?
# Base64用\x00字節在末尾補足後,再在編碼的末尾加上1個或2個=號,表示補了多少字節,
# 解碼的時候,會自動去掉。
print base64.b64encode('binary\x00string')
print base64.b64decode('YmluYXJ5AHN0cmluZw==')

# 由於標準的Base64編碼後可能出現字符+和/,在URL中就不能直接作為參數,
# 所以又有一種"url safe"的base64編碼,其實就是把字符+和/分別變成-和_:
print base64.b64encode('i\xb7\x1d\xfb\xef\xff')
# abcd++//
print base64.urlsafe_b64encode('i\xb7\x1d\xfb\xef\xff')
# abcd--__
print base64.urlsafe_b64decode('abcd--__')
# i\xb7\x1d\xfb\xef\xff

# 由於=字符也可能出現在Base64編碼中,但=用在URL、Cookie裡面會造成歧義,
# 所以,很多Base64編碼後會把=去掉:
# 標準Base64:
#'abcd' -> 'YWJjZA=='
# 自動去掉=:
#'abcd' -> 'YWJjZA'

# 因為Base64是把3個字節變為4個字節,所以,Base64編碼的長度永遠是4的倍數
# 因此,需要加上=把Base64字符串的長度變為4的倍數,就可以正常解碼了。
Esempio n. 44
0
def create_jwt(payload, secret):
    dsecret = base64.urlsafe_b64decode(secret)
    token = jwt.encode(payload, dsecret, algorithm='HS256')
    return token
Esempio n. 45
0
 def test_generate_password(self):
     password = self.rpcauth.generate_password()
     expected_password = base64.urlsafe_b64encode(
         base64.urlsafe_b64decode(password)).decode('utf-8')
     self.assertEqual(expected_password, password)
Esempio n. 46
0
def decode_base64(value):
    """Decodes base64url-encoded string"""
    encoded = value.encode('utf-8')
    return base64.urlsafe_b64decode(encoded).decode('utf-8')
Esempio n. 47
0
    async def api(self, parse):
        '''
        path: supported command
        /api/localrule: GET POST DELETE
        '''
        self.logger.debug('api %s %s', self.command, self.path)
        # read request body
        content_length = int(self.headers.get('Content-Length', 0))
        if content_length > 102400:
            return
        body = io.BytesIO()
        while content_length:
            data = await self.client_reader_readexactly(min(self.bufsize, content_length))
            if not data:
                return
            content_length -= len(data)
            body.write(data)
        body = body.getvalue()

        # check password
        if self.conf.remotepass:
            if 'Authorization' not in self.headers:
                self.send_response(401)
                self.send_header("WWW-Authenticate", 'Basic')
                self.end_headers()
                return

            auth = self.headers['Authorization'].split()[1]
            _password = base64.b64decode(auth).decode().split(':', 1)[1]
            if _password != self.conf.remotepass:
                self.send_response(401)
                self.send_header("WWW-Authenticate", 'Basic')
                self.end_headers()
                return

        if parse.path == '/api/localrule' and self.command == 'GET':
            data = json.dumps(self.conf.list_localrule(), indent=4)
            self.write(code=200, data=data, ctype='application/json')
            return
        if parse.path == '/api/localrule' and self.command == 'POST':
            # accept a json encoded tuple: (str rule, int exp)
            rule, exp = json.loads(body)
            self.conf.add_localrule(rule, exp)
            self.write(200)
            return
        if parse.path.startswith('/api/localrule/') and self.command == 'DELETE':
            try:
                rule = base64.urlsafe_b64decode(parse.path[15:].encode('latin1')).decode()
                self.conf.del_localrule(rule)
                self.write(200)
                return
            except Exception as err:
                self.logger.error(traceback.format_exc())
                self.send_error(404, repr(err))
                return
        if parse.path == '/api/isgfwed':
            uri = body.decode('utf8')
            if '//' in uri:
                host = urlparse.urlparse(uri).netloc
                host = parse_hostport(host, 80)[0]
            else:
                host = uri
                uri = None
            result = self.conf.GET_PROXY.isgfwed_resolver(host, uri)
            self.write(200, data=repr(result), ctype='text/plain')
            return
        if parse.path == '/api/redirector' and self.command == 'GET':
            data = json.dumps(self.conf.list_redir(), indent=4)
            self.write(200, data=data, ctype='application/json')
            return
        if parse.path == '/api/redirector' and self.command == 'POST':
            # accept a json encoded tuple: (str rule, str dest)
            rule, dest = json.loads(body)
            self.conf.add_redir(rule, dest)
            self.write(200)
            return
        if parse.path.startswith('/api/redirector/') and self.command == 'DELETE':
            try:
                rule = urlparse.parse_qs(parse.query).get('rule', [''])[0]
                rule = base64.urlsafe_b64decode(rule).decode()
                self.conf.del_redir(rule)
                self.write(200)
                return
            except Exception as err:
                self.send_error(404, repr(err))
                return
        if parse.path == '/api/proxy' and self.command == 'GET':
            data = self.conf.list_proxy()
            data = json.dumps(data, indent=4)
            self.write(200, data=data, ctype='application/json')
            return
        if parse.path == '/api/proxy' and self.command == 'POST':
            # accept a json encoded tuple: (str name, str proxy)
            name, proxy = json.loads(body)
            if 'FWLITE:' in name:
                self.send_error(401)
                return
            if name == '_L0C4L_':
                self.send_error(401)
                return
            try:
                self.conf.add_proxy(name, proxy)
                self.write(200)
            except ValueError:
                self.write(401)
            return
        if parse.path.startswith('/api/proxy/') and self.command == 'DELETE':
            try:
                proxy_name = parse.path[11:]
                proxy_name = base64.urlsafe_b64decode(proxy_name).decode()
                self.conf.del_proxy(proxy_name)
                self.write(200)
                return
            except Exception as err:
                self.send_error(404, repr(err))
                return
        if parse.path.startswith('/api/proxy/') and self.command == 'GET':
            try:
                proxy_name = parse.path[11:]
                proxy_name = base64.urlsafe_b64decode(proxy_name).decode()
                proxy = self.conf.get_proxy(proxy_name)
                self.write(200, data=proxy, ctype='text/plain')
                return
            except Exception as err:
                self.send_error(404, repr(err))
                return
        if parse.path == '/api/forward' and self.command == 'GET':
            data = self.conf.list_forward()
            data = json.dumps(data, indent=4)
            self.write(200, data=data, ctype='application/json')
            return
        if parse.path == '/api/forward' and self.command == 'POST':
            # accept a json encoded tuple: (str target, str proxy, int port)
            target, proxy, port = json.loads(body)
            self.conf.add_forward(target, proxy, port)
            self.write(200, data=data, ctype='application/json')
            return
        if parse.path.startswith('/api/forward/') and self.command == 'DELETE':
            data = parse.path[13:]
            port = int(data)
            self.conf.del_forward(port)
            self.write(200)
            return
        if parse.path == '/api/gfwlist' and self.command == 'GET':
            self.write(200, data=json.dumps(self.conf.gfwlist_enable), ctype='application/json')
            return
        if parse.path == '/api/gfwlist' and self.command == 'POST':
            self.conf.gfwlist_enable = json.loads(body)
            self.write(200, data=data, ctype='application/json')
            return
        if parse.path == '/api/adblock' and self.command == 'GET':
            self.write(200, data=json.dumps(self.conf.adblock_enable), ctype='application/json')
            return
        if parse.path == '/api/adblock' and self.command == 'POST':
            self.conf.adblock_enable = json.loads(body)
            self.write(200, data=data, ctype='application/json')
            return
        if parse.path == '/api/exit' and self.command == 'GET':
            self.conf.stop()
            self.write(200, data='Done!', ctype='text/html')
            return
        if parse.path == '/api/log' and self.command == 'GET':
            self.write(200, data=self.conf.get_log(), ctype='text/plain; charset=utf-8')
            return
        self.logger.error('api %s not exist.' % parse.path)
        self.send_error(404)
Esempio n. 48
0
File: auth.py Progetto: fnzv/alerta
def google():
    access_token_url = 'https://accounts.google.com/o/oauth2/token'
    people_api_url = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect'

    payload = {
        'client_id': request.json['clientId'],
        'client_secret': app.config['OAUTH2_CLIENT_SECRET'],
        'redirect_uri': request.json['redirectUri'],
        'grant_type': 'authorization_code',
        'code': request.json['code'],
    }

    try:
        r = requests.post(access_token_url, data=payload)
    except Exception:
        return jsonify(status="error",
                       message="Failed to call Google API over HTTPS")
    token = r.json()

    if 'id_token' not in token:
        return jsonify(status="error",
                       message=token.get('error', "Invalid token"))

    id_token = token['id_token'].split('.')[1].encode('ascii', 'ignore')
    id_token += '=' * (4 - (len(id_token) % 4))
    claims = json.loads(urlsafe_b64decode(id_token))

    if claims.get('aud') != app.config['OAUTH2_CLIENT_ID']:
        return jsonify(status="error",
                       message="Token client audience is invalid"), 400

    email = claims.get('email')
    if app.config['AUTH_REQUIRED'] and not (
            '*' in app.config['ALLOWED_EMAIL_DOMAINS']
            or email.split('@')[1] in app.config['ALLOWED_EMAIL_DOMAINS']):
        return jsonify(status="error",
                       message="User %s is not authorized" % email), 403

    headers = {'Authorization': 'Bearer ' + token['access_token']}
    r = requests.get(people_api_url, headers=headers)
    profile = r.json()

    if app.config['CUSTOMER_VIEWS']:
        try:
            customer = customer_match(email, groups=[email.split('@')[1]])
        except NoCustomerMatch:
            return jsonify(status="error",
                           message="No customer lookup defined for user %s" %
                           email), 403
    else:
        customer = None

    try:
        token = create_token(profile['sub'],
                             profile['name'],
                             email,
                             provider='google',
                             customer=customer,
                             role=role(email))
    except KeyError:
        return jsonify(status="error",
                       message="Google+ API is not enabled for this Client ID")

    return jsonify(token=token)
Esempio n. 49
0
def main():
    argument_spec = get_default_argspec()
    argument_spec.update(
        dict(terms_agreed=dict(type='bool', default=False),
             state=dict(type='str',
                        required=True,
                        choices=['absent', 'present', 'changed_key']),
             allow_creation=dict(type='bool', default=True),
             contact=dict(type='list', elements='str', default=[]),
             new_account_key_src=dict(type='path'),
             new_account_key_content=dict(type='str', no_log=True),
             external_account_binding=dict(
                 type='dict',
                 options=dict(
                     kid=dict(type='str', required=True),
                     alg=dict(type='str',
                              required=True,
                              choices=['HS256', 'HS384', 'HS512']),
                     key=dict(type='str', required=True, no_log=True),
                 ))))
    module = AnsibleModule(
        argument_spec=argument_spec,
        required_one_of=(['account_key_src', 'account_key_content'], ),
        mutually_exclusive=(
            ['account_key_src', 'account_key_content'],
            ['new_account_key_src', 'new_account_key_content'],
        ),
        required_if=(
            # Make sure that for state == changed_key, one of
            # new_account_key_src and new_account_key_content are specified
            [
                'state', 'changed_key',
                ['new_account_key_src', 'new_account_key_content'], True
            ], ),
        supports_check_mode=True,
    )
    handle_standard_module_arguments(module, needs_acme_v2=True)

    if module.params['external_account_binding']:
        # Make sure padding is there
        key = module.params['external_account_binding']['key']
        if len(key) % 4 != 0:
            key = key + ('=' * (4 - (len(key) % 4)))
        # Make sure key is Base64 encoded
        try:
            base64.urlsafe_b64decode(key)
        except Exception as e:
            module.fail_json(
                msg=
                'Key for external_account_binding must be Base64 URL encoded (%s)'
                % e)
        module.params['external_account_binding']['key'] = key

    try:
        account = ACMEAccount(module)
        changed = False
        state = module.params.get('state')
        diff_before = {}
        diff_after = {}
        if state == 'absent':
            created, account_data = account.setup_account(allow_creation=False)
            if account_data:
                diff_before = dict(account_data)
                diff_before['public_account_key'] = account.key_data['jwk']
            if created:
                raise AssertionError('Unwanted account creation')
            if account_data is not None:
                # Account is not yet deactivated
                if not module.check_mode:
                    # Deactivate it
                    payload = {'status': 'deactivated'}
                    result, info = account.send_signed_request(
                        account.uri, payload)
                    if info['status'] != 200:
                        raise ModuleFailException(
                            'Error deactivating account: {0} {1}'.format(
                                info['status'], result))
                changed = True
        elif state == 'present':
            allow_creation = module.params.get('allow_creation')
            contact = [str(v) for v in module.params.get('contact')]
            terms_agreed = module.params.get('terms_agreed')
            external_account_binding = module.params.get(
                'external_account_binding')
            created, account_data = account.setup_account(
                contact,
                terms_agreed=terms_agreed,
                allow_creation=allow_creation,
                external_account_binding=external_account_binding,
            )
            if account_data is None:
                raise ModuleFailException(
                    msg='Account does not exist or is deactivated.')
            if created:
                diff_before = {}
            else:
                diff_before = dict(account_data)
                diff_before['public_account_key'] = account.key_data['jwk']
            updated = False
            if not created:
                updated, account_data = account.update_account(
                    account_data, contact)
            changed = created or updated
            diff_after = dict(account_data)
            diff_after['public_account_key'] = account.key_data['jwk']
        elif state == 'changed_key':
            # Parse new account key
            error, new_key_data = account.parse_key(
                module.params.get('new_account_key_src'),
                module.params.get('new_account_key_content'))
            if error:
                raise ModuleFailException(
                    "error while parsing account key: %s" % error)
            # Verify that the account exists and has not been deactivated
            created, account_data = account.setup_account(allow_creation=False)
            if created:
                raise AssertionError('Unwanted account creation')
            if account_data is None:
                raise ModuleFailException(
                    msg='Account does not exist or is deactivated.')
            diff_before = dict(account_data)
            diff_before['public_account_key'] = account.key_data['jwk']
            # Now we can start the account key rollover
            if not module.check_mode:
                # Compose inner signed message
                # https://tools.ietf.org/html/rfc8555#section-7.3.5
                url = account.directory['keyChange']
                protected = {
                    "alg": new_key_data['alg'],
                    "jwk": new_key_data['jwk'],
                    "url": url,
                }
                payload = {
                    "account": account.uri,
                    "newKey":
                    new_key_data['jwk'],  # specified in draft 12 and older
                    "oldKey": account.jwk,  # specified in draft 13 and newer
                }
                data = account.sign_request(protected, payload, new_key_data)
                # Send request and verify result
                result, info = account.send_signed_request(url, data)
                if info['status'] != 200:
                    raise ModuleFailException(
                        'Error account key rollover: {0} {1}'.format(
                            info['status'], result))
                if module._diff:
                    account.key_data = new_key_data
                    account.jws_header['alg'] = new_key_data['alg']
                    diff_after = account.get_account_data()
            elif module._diff:
                # Kind of fake diff_after
                diff_after = dict(diff_before)
            diff_after['public_account_key'] = new_key_data['jwk']
            changed = True
        result = {
            'changed': changed,
            'account_uri': account.uri,
        }
        if module._diff:
            result['diff'] = {
                'before': diff_before,
                'after': diff_after,
            }
        module.exit_json(**result)
    except ModuleFailException as e:
        e.do_fail(module)
Esempio n. 50
0
 def decode_hash(hash_bytes):
     return binascii.hexlify(
         base64.urlsafe_b64decode(hash_bytes)).decode('utf-8')
Esempio n. 51
0
    def _do_token(self, requesting_user, params):
        code = params.get("code", None)
        grant_type = params.get("grant_type", None)
        redirect_uri = params.get("redirect_uri", None)
        resource = params.get("resource", None)
        state = params.get("state", None)
        client_id = params.get("client_id", None)
        client_secret = params.get("client_secret", None)
        refresh_token = params.get("refresh_token", None)
        tid = params.get("tenant_id", None)
        token_type = "bearer"

        # if grant_type == code then code must not be empty
        # if grant_type == refresh_token then refresh_token must not be empty
        if grant_type == "code":
            if not code:
                raise OAuth2RequestException(
                    "Code must not be empty when grant_type is code")
        elif grant_type == "refresh_token":
            if not refresh_token:
                raise OAuth2RequestException(
                    "Code must not be empty when grant_type is refresh_token")
        else:
            raise OAuth2RequestException(
                "Value of grant_type must be either code or refresh_token")

        request_host = params.get("request_host")

        oauth2_settings = self.settings['oauth2_settings']
        oauth2_token_issuer = oauth2_settings.get("oauth2_token_issuer",
                                                  request_host)
        oauth2_token_expiry_seconds = oauth2_settings.get(
            "oauth2_token_expiry_seconds")

        exp = datetime.timedelta(seconds=oauth2_token_expiry_seconds)

        enc_code = base64.urlsafe_b64decode(code.encode())

        oauth2_private_key_handler = self.get_private_key_handler()

        code_json_bytes = oauth2_private_key_handler.decrypt(enc_code)
        code_json = code_json_bytes.decode()
        code_dict = json.loads(code_json)

        user_id = code_dict.get("user_id")
        code_iat = code_dict.get("iat")

        if not user_id or not code_iat:
            raise OAuth2RequestException("Invalid code")

        user = yield self.load_user(user_id)
        if not user:
            raise OAuth2RequestException("Invalid code")

        #TODO: allow use of secret - otherwise its not secure

        #Make sure the code was not used earlier - otherwise its not secure
        code_status_id = code_dict.get("code_status_id")
        if not code_status_id:
            raise OAuth2RequestException("Invalid code")

        code_status = yield self.load_code_status(code_status_id)
        if not code_status:
            raise OAuth2RequestException(
                "Invalid code. Possibly server error.")

        if code_status.get("used_at"):
            code_status["duplicate_attempt"] = True
            yield self.update_code_status(code_status)
            raise OAuth2RequestException("Code already used")

        current_utc_time = self.get_current_utc_time()

        code_status["used_at"] = current_utc_time
        saved = yield self.update_code_status(code_status)
        if not saved:
            logging.error(
                "Could not save code status Id={}".format(code_status_id))

        resource = code_dict.get("resource")
        oauth2_private_key_pem = self.get_private_key_pem()

        response = get_token(aud=client_id,
                             exp=exp,
                             family_name=user.get("family_name"),
                             given_name=user.get("given_name"),
                             iat=str(current_utc_time),
                             iss=oauth2_token_issuer,
                             nbf=str(current_utc_time),
                             oid=str(user.get("_id")),
                             sub=str(user.get("_id")),
                             tid=tid,
                             unique_name=user.get("username"),
                             upn=user.get("username"),
                             service_private_pem=oauth2_private_key_pem)
        url = redirect_uri
        session_state = user.get("session_id", str(uuid.uuid4()))
        response_type = "access_token"
        params = {
            response_type: response,
            "session_state": session_state,
            "token_type": token_type,
            "resource": resource
        }

        if state:
            params["state"] = state

        parts = list(urlparse.urlparse(url))
        query = dict(urlparse.parse_qsl(parts[4]))
        query.update(params)
        parts[4] = urlencode(query)

        redirect_url = urlparse.urlunparse(parts)

        self.redirect(redirect_url)
Esempio n. 52
0
    def _validate_proxy_url(self):
        original_uri = request.headers.get("X-Original-URI", None)
        if not original_uri:
            logger.error("Missing original URI: %s", request.headers)
            abort(401)

        if not original_uri.startswith("/_storage_proxy/"):
            logger.error("Unknown storage proxy path: %s", original_uri)
            abort(401)

        # The proxy path is of the form:
        # /_storage_proxy/{token}/{scheme}/{hostname}/rest/of/path/here
        without_prefix = original_uri[len("/_storage_proxy/"):]
        parts = without_prefix.split("/", 3)
        if len(parts) != 4:
            logger.error("Invalid storage proxy path (found %s parts): %s",
                         len(parts), without_prefix)
            abort(401)

        encoded_token, scheme, host, uri = parts

        try:
            token = base64.urlsafe_b64decode(encoded_token)
        except ValueError:
            logger.exception("Could not decode proxy token")
            abort(401)
        except TypeError:
            logger.exception("Could not decode proxy token")
            abort(401)

        logger.debug(
            "Got token %s for storage proxy auth request %s with parts %s",
            token,
            original_uri,
            parts,
        )

        # Decode the bearer token.
        try:
            decoded = decode_bearer_token(token, self.instance_keys,
                                          self.app.config)
        except InvalidBearerTokenException:
            logger.exception("Invalid token for storage proxy")
            abort(401)

        # Ensure it is for the proxy.
        if decoded["sub"] != STORAGE_PROXY_SUBJECT:
            logger.exception("Invalid subject %s for storage proxy auth",
                             decoded["subject"])
            abort(401)

        # Validate that the access matches the token format.
        access = decoded.get("access", {})
        try:
            validate(access, ACCESS_SCHEMA)
        except ValidationError:
            logger.exception(
                "We should not be minting invalid credentials: %s", access)
            abort(401)

        # For now, we only expect a single access credential.
        if len(access) != 1:
            logger.exception(
                "We should not be minting invalid credentials: %s", access)
            abort(401)

        # Ensure the signed access matches the requested URL's pieces.
        granted_access = access[0]
        if granted_access["scheme"] != scheme:
            logger.exception("Mismatch in scheme. %s expected, %s found",
                             granted_access["scheme"], scheme)
            abort(401)

        if granted_access["host"] != host:
            logger.exception("Mismatch in host. %s expected, %s found",
                             granted_access["host"], host)
            abort(401)

        if granted_access["uri"] != uri:
            logger.exception("Mismatch in uri. %s expected, %s found",
                             granted_access["uri"], uri)
            abort(401)

        return "OK"
Esempio n. 53
0
    def upload():
        try:
            data = urlsafe_b64decode(request.args.get("data"))
            sig = urlsafe_b64decode(request.args.get("sig"))
        except ValueError:
            abort(400, "Invalid data or signature")

        if not verify_hash_signature(data, media_server_secret_key, sig):
            abort(400, "Invalid data or signature")

        req = media_pb2.UploadRequest.FromString(data)

        # proto timestamps are in UTC
        now = datetime.utcnow()

        if req.created.ToDatetime() > now:
            logger.warning(
                "Got request from the future. Are the clocks out of sync?")

        if req.expiry.ToDatetime() < now:
            abort(400, "Request expired")

        if req.key != secure_filename(req.key):
            # just a sanity check
            abort(500, "Invalid key")

        filename = req.key + ".jpg"
        path = get_path(filename)

        if os.path.isfile(path):
            abort(400, "Invalid request")

        request_file = request.files.get("file", None)

        if not request_file:
            abort(400, "No file provided")

        if req.type != media_pb2.UploadRequest.UploadType.IMAGE:
            abort(500, "Unsupported upload type")

        # handle image uploads
        try:
            img = pyvips.Image.new_from_buffer(request_file.read(),
                                               options="",
                                               access="sequential")
        except pyvips.Error:
            abort(400, "Invalid image")

        width = img.get("width")
        height = img.get("height")

        # if it's larger than allowed max values, resize it
        scale = min(req.max_width / width, req.max_height / height)
        if scale < 1:
            img = img.resize(scale)

        # strip removes EXIF (e.g. GPS location) and other metadata
        img.write_to_file(path, strip=True)

        # let the main server know the upload succeeded, or delete the file
        try:
            send_confirmation_to_main_server(req.key, filename)
            return {"ok": True}
        except Exception as e:
            os.remove(path)
            raise e
Esempio n. 54
0
def base64_urldecode(s):
    ascii_string = str(s)
    ascii_string += '=' * (4 - (len(ascii_string) % 4))
    return base64.urlsafe_b64decode(ascii_string)
Esempio n. 55
0
def decode_url(url):
    s = url.replace('_', '=')[5:]
    return base64.urlsafe_b64decode(str(s)).decode('utf-8')
Esempio n. 56
0
def base64url_decode(input_str):
    return base64.urlsafe_b64decode(input_str)
Esempio n. 57
0
def safe_decode(s):
    num = len(s) % 4
    if num:
        s += '=' * (4 - num)
    return base64.urlsafe_b64decode(s)
Esempio n. 58
0
import requests
import json
import os
import base64

from cryptography.exceptions import AlreadyFinalized
from cryptography.exceptions import InvalidTag
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

import azure.functions as func

key = base64.urlsafe_b64decode(os.environ["AesKey"])
nonce = base64.urlsafe_b64decode(os.environ["AesIV"])
passwordvaultid = os.environ["VaultSpnId"]
clientid = os.environ["Clientid"]
secret = os.environ["SpnSecret"]
login_url = os.environ["LoginUrl"]
app_url = os.environ["AppUrl"]
code = os.environ["FunctionCode"]


def getLoginToken():
    body = {
        "resource": passwordvaultid,
        "scope": "openid",
        "grant_type": "client_credentials",
        "client_id": clientid,
from core import scrapertools
from core.item import Item
from core.tmdb import infoSod

__channel__ = "hdstreamingit"
__category__ = "F"
__type__ = "generic"
__title__ = "hd-streaming.it (IT)"
__language__ = "IT"

DEBUG = config.get_setting("debug")

host = "http://www.hd-streaming.it"

key = base64.urlsafe_b64decode(
    'ZTViNTA5OGJhMWU1NDNlNGFiMGNjNThiNWYzYjE5NTg4MzE3YmQ3NjczMjliZGNiODk0ZDg5YjU2MGU1NTJjMDY4ZjFmOWI5NTc5Zjc0NjQ4MmU2YzEyNGViNzQzYmFlY2MyZmVkZTIyNDk5YzA2NGNiMjZjYTQ1ZDlmM2Y1ODFkMmRjZWM4YjdmNmY0ZmI5YmJhMTgyZmQ4Nzc2NzQyYg=='
)

importio_url = "https://api.import.io/store/connector/_magic?format=JSON&js=false&_apikey=%s&url=" % key

dec_fly = "http://skizzerz.net/scripts/adfly.php?url="


def isGeneric():
    return True


def mainlist(item):
    logger.info("streamondemand.hdstreamingit mainlist")
    itemlist = [
        Item(
Esempio n. 60
0
            default_backend()).public_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PublicFormat.SubjectPublicKeyInfo)


token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImppYk5ia0ZTU2JteFBZck45Q0ZxUms0SzRndyJ9.eyJhdWQiOiI5MzQ4YTQ4YS05Zjk3LTRlOWUtYmNlMi00MGQyMzk4NDA3MzMiLCJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vNzJmOTg4YmYtODZmMS00MWFmLTkxYWItMmQ3Y2QwMTFkYjQ3L3YyLjAiLCJpYXQiOjE2MDAzNzUyMDcsIm5iZiI6MTYwMDM3NTIwNywiZXhwIjoxNjAwMzc5MTA3LCJhaW8iOiJBVlFBcS84UUFBQUFaL1Z4dFl6ZWRPcGtBKzFwVFZMdjNkNnhzOUdjY3hHVVdiYjc0cHl5SVpwYVlNUGhUbVhsUUJXTDlEajNMSlVtR0FrbmdvelNHbFgzN1NVdFVWZnM1YXhtU0I0Qms5dXAyQUZuR0xNclpnST0iLCJuYW1lIjoiQ2hhZCBBZGFtcyIsIm5vbmNlIjoiODFjMmZmNTctNjNmZS00MTlmLWFiODMtMTVlOThjZjk5MDMxIiwib2lkIjoiNmQyN2U2MTItNTcyOS00MjJhLTgyNTctOTljZGE3ZmExMzJmIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiY2hhZGFkYUBtaWNyb3NvZnQuY29tIiwicmgiOiIwLkFSb0F2NGo1Y3ZHR3IwR1JxeTE4MEJIYlI0cWtTSk9YbjU1T3ZPSkEwam1FQnpNYUFQUS4iLCJzdWIiOiJ0ZVhpdHFqdG9vaGZkUFA2czQ1bFBlZS1HWU5RdWtsbTdnNXZrZXo5V0pjIiwidGlkIjoiNzJmOTg4YmYtODZmMS00MWFmLTkxYWItMmQ3Y2QwMTFkYjQ3IiwidXRpIjoiUnlUYXhBLXVIMGlzX2ZmVEh2Y0RBQSIsInZlciI6IjIuMCJ9.AE4rAtZCcPyK6axQWTuJDrk56u-epxbFfWzUFod266-DswbR8558HAKiOLJls7KvV7_ssYeipM7U0ZU6pmN7fFiLjmNHNyCXWE8Dqixn6hJno1_Ik1DAn5k-imF2CrBYrmb9ZkSSIZzy6fYcK5FPVDXvVd4KS2zfEiel8eoVUzEK31wudkImZacy6qafkNIeLcno28VH2Jt9ESoTD3fJ8-nFOorMmOWOeXk1YuXktvAZiTQfatAUAxhwvQg5RxkZuAMHr9sHJqb23Rylh489pQQ7FZKGBqhY-zpp7G1rytguz8wpmhctgJRHu6kmQsVNfih2AfCE3d-mt27vEOueNA"
#token = "eyJ0eXAiOiJKV1QiLCJub25jZSI6IlhzekE5SUNlR2RadFUtMXFjRk9LVHVwWW8zR0NYa1FEaVY1QlJGMlk2SWMiLCJhbGciOiJSUzI1NiIsIng1dCI6ImppYk5ia0ZTU2JteFBZck45Q0ZxUms0SzRndyIsImtpZCI6ImppYk5ia0ZTU2JteFBZck45Q0ZxUms0SzRndyJ9.eyJhdWQiOiIwMDAwMDAwMy0wMDAwLTAwMDAtYzAwMC0wMDAwMDAwMDAwMDAiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDcvIiwiaWF0IjoxNjAwMzc0NzYyLCJuYmYiOjE2MDAzNzQ3NjIsImV4cCI6MTYwMDM3ODY2MiwiYWNjdCI6MCwiYWNyIjoiMSIsImFpbyI6IkFWUUFxLzhRQUFBQW9UK2NkZDduZWtyWlE2aDc3OG00b3g4RDFsSnhJelhuVUpGZzdEQVFUR0FZU1Q4eHRFSVMrUEU4aE43RTY5bHBnamgwT0p0TUZybE5HcVdvSndOY2h1T3I2ZTVvVGZmK1JYQUtUc2tKTlhVPSIsImFtciI6WyJ3aWEiLCJtZmEiXSwiYXBwX2Rpc3BsYXluYW1lIjoibHVuYS1zYSIsImFwcGlkIjoiOTM0OGE0OGEtOWY5Ny00ZTllLWJjZTItNDBkMjM5ODQwNzMzIiwiYXBwaWRhY3IiOiIwIiwiZmFtaWx5X25hbWUiOiJBZGFtcyIsImdpdmVuX25hbWUiOiJDaGFkIiwiaWR0eXAiOiJ1c2VyIiwiaW5fY29ycCI6InRydWUiLCJpcGFkZHIiOiIxMzYuMzUuMTgyLjE4NiIsIm5hbWUiOiJDaGFkIEFkYW1zIiwib2lkIjoiNmQyN2U2MTItNTcyOS00MjJhLTgyNTctOTljZGE3ZmExMzJmIiwib25wcmVtX3NpZCI6IlMtMS01LTIxLTEyNDUyNTA5NS03MDgyNTk2MzctMTU0MzExOTAyMS0xNTQyMzgwIiwicGxhdGYiOiIzIiwicHVpZCI6IjEwMDNCRkZEOTE1NDg3MjAiLCJyaCI6IjAuQVJvQXY0ajVjdkdHcjBHUnF5MTgwQkhiUjRxa1NKT1huNTVPdk9KQTBqbUVCek1hQVBRLiIsInNjcCI6Im9wZW5pZCBwcm9maWxlIFVzZXIuUmVhZCBVc2VyLlJlYWRCYXNpYy5BbGwgZW1haWwiLCJzaWduaW5fc3RhdGUiOlsia21zaSJdLCJzdWIiOiJOMWVwVFF2Y24zX2ZjelNPalJhRVZsVXU1WlBEM19sYVU2V3FmendHNmZrIiwidGVuYW50X3JlZ2lvbl9zY29wZSI6IldXIiwidGlkIjoiNzJmOTg4YmYtODZmMS00MWFmLTkxYWItMmQ3Y2QwMTFkYjQ3IiwidW5pcXVlX25hbWUiOiJjaGFkYWRhQG1pY3Jvc29mdC5jb20iLCJ1cG4iOiJjaGFkYWRhQG1pY3Jvc29mdC5jb20iLCJ1dGkiOiJua0VBbWlDTlhFZVRHS0RYbENJTEFBIiwidmVyIjoiMS4wIiwieG1zX3N0Ijp7InN1YiI6InRlWGl0cWp0b29oZmRQUDZzNDVsUGVlLUdZTlF1a2xtN2c1dmtlejlXSmMifSwieG1zX3RjZHQiOjEyODkyNDE1NDd9.TFl8zLuGlljFZxvKRwsJOzpB5y2Lzk4ddxPTt-Ywx-eL9no6GeHljac_isJqrmu2SUWUEKKo4ZnnGFfUE4_vy4id-pP3PMHoVfGUu6R5Yos5WKviUTvoKHNMc0D1YNigMZQTm0jjewDce4HecKk0FXhMwSPOUSSXAtpLV7LF7vPWNT9Fp4MpIXOLPs6m5rWBcBLnMMv770rhw-6R2wPgMqdDVDHU8eX8pN4JUiCLGLkItqpm68DsInkD5FVJ2hskP2aKmh77i3Ps6b0s5_3C78HaiJy9Yv4ilkE6reqvpUrZkRzB6s_EaP8LXm14412sX3AprURUuL1EN-DFsDDT1Q"
sections = token.split(".")

print(sections[0])
print("==================================")
print(sections[1])
print("==================================")
print(sections[2])

print(base64.urlsafe_b64decode(sections[0].encode('utf-8') + b'=='))
print(base64.urlsafe_b64decode(sections[1].encode('utf-8') + b'=='))

jwts = {
    "keys": [{
        "kty":
        "RSA",
        "use":
        "sig",
        "kid":
        "jibNbkFSSbmxPYrN9CFqRk4K4gw",
        "x5t":
        "jibNbkFSSbmxPYrN9CFqRk4K4gw",
        "n":
        "2YX-YDuuTzPiaiZKt04IuUzAjCjPLLmBCVA6npKuZyIouMuaSEuM7BP8QctfCprUY16Rq2-KDrAEvaaKJvsD5ZONddt79yFdCs1E8wKlYIPO74fSpePdVDizflr5W-QCFH9tokbZrHBBuluFojgtbvPMXAhHfZTGC4ItZ0i_Lc9eXwtENHJQC4e4m7olweK1ExM-OzsKGzDlOsOUOU5pN2sHY74nXPqQRH1dQKfB0NT0YrfkbnR8fiq8z-soixfECUXkF8FzWnMnqL6X90wngnuIi8OtH2mvDcnsvUVh3K2JgvSgjRWZbsDx6G-mVQL2vEuHXMXoIoe8hd1ZpV16pQ",
        "e":