Python hmac.compare_digest() Examples

The following are 30 code examples of hmac.compare_digest(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module hmac , or try the search function .
Example #1
Source File: web.py    From mergify-engine with Apache License 2.0 6 votes vote down vote up
def authentification(request: requests.Request):
    # Only SHA1 is supported
    header_signature = request.headers.get("X-Hub-Signature")
    if header_signature is None:
        LOG.warning("Webhook without signature")
        raise fastapi.HTTPException(status_code=403)

    try:
        sha_name, signature = header_signature.split("=")
    except ValueError:
        sha_name = None

    if sha_name != "sha1":
        LOG.warning("Webhook signature malformed")
        raise fastapi.HTTPException(status_code=403)

    body = await request.body()
    mac = utils.compute_hmac(body)
    if not hmac.compare_digest(mac, str(signature)):
        LOG.warning("Webhook signature invalid")
        raise fastapi.HTTPException(status_code=403) 
Example #2
Source File: keymanager.py    From mini-key-server with MIT License 6 votes vote down vote up
def key_valid_const(app_id: int, token: str, origin: Origin) -> bool:
    """Constant time check to see if `token` exists in the database. Compares
    against all keys even if a match is found. Validates against the app id
    and the hardware id provided."""
    current_app.logger.info(f"key lookup by token {token} from {origin}")
    found = False
    for key in Key.query.all():
        if (compare_digest(token, key.token) and
                key.enabled and key.app_id == app_id
                and compare_digest(origin.hwid, key.hwid)):

            found = True
            key.last_check_ts = datetime.utcnow()
            key.last_check_ip = origin.ip
            key.total_checks += 1
            AuditLog.from_key(key, f"key check from {origin}", Event.KeyAccess)
    return found 
Example #3
Source File: app.py    From github-webhook-lambda with MIT License 6 votes vote down vote up
def validate_signature(request):
    """Validate that the signature in the header matches the payload."""
    if CONFIG["SECRET"] is None:
        return
    try:
        signature = request.headers["X-Hub-Signature"]
        hashname, hashval = signature.split("=")
    except (KeyError, ValueError):
        raise BadRequestError()

    if (hashname in CONFIG["HASHLIB_BLACKLIST"]) or (
        hashname not in hashlib.algorithms_available
    ):
        raise BadRequestError("X-Hub-Signature hash algorithm unavailable")

    digest = hmac.new(
        CONFIG["SECRET"].encode(), request.raw_body.encode(), hashname
    ).hexdigest()
    if not hmac.compare_digest(digest.encode(), hashval.encode("utf-8")):
        raise UnauthorizedError("X-Hub-Signature mismatch") 
Example #4
Source File: test_profile.py    From online-judge with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_generate_api_token(self):
        token = self.profile.generate_api_token()

        self.assertIsInstance(token, str)
        self.assertIsInstance(self.profile.api_token, str)

        user_id, raw_token = struct.unpack('>I32s', base64.urlsafe_b64decode(token))

        self.assertEqual(self.users['normal'].id, user_id)
        self.assertEqual(len(raw_token), 32)

        self.assertTrue(
            hmac.compare_digest(
                hmac.new(force_bytes(settings.SECRET_KEY), msg=force_bytes(raw_token), digestmod='sha256').hexdigest(),
                self.profile.api_token,
            ),
        ) 
Example #5
Source File: pierre.py    From pierre-decheck with MIT License 6 votes vote down vote up
def verify_source_is_github(data, headers):
    if USE_GITHUB_SECRET:
        if data is None:
            return False, {"statusCode": 400, "body": "Request body must contain json"}

        digest = _get_digest(GITHUB_SECRET, data)
        if digest is not None:
            header_signature = headers.get("X-Hub-Signature")
            sig_parts = header_signature.split('=', 1)

            if not isinstance(digest, str):
                digest = str(digest)

            if len(sig_parts) < 2 or sig_parts[0] != 'sha1' or not hmac.compare_digest(sig_parts[1], digest):
                return False, {"statusCode": 400, "body": "Invalid Signature"}

    # Implement ping
    event = headers.get('X-GitHub-Event', 'ping')
    if event == 'ping':
        return False, {"statusCode": 200, "body": {'msg': 'pong'}}

    return True, {} 
Example #6
Source File: base.py    From freight with Apache License 2.0 6 votes vote down vote up
def is_authorized(self):
        current_user = get_current_user()
        if current_user:
            return True

        try:
            auth = request.headers["Authorization"]
        except KeyError:
            return False

        try:
            method, payload = auth.split(" ", 1)
        except ValueError:
            return False

        if method != "Key":
            return False

        if not compare_digest(payload, current_app.config["API_KEY"]):
            return False

        return True 
Example #7
Source File: webhooks.py    From freight with Apache License 2.0 6 votes vote down vote up
def post(self, hook, action, app, env, digest):
        expected = hmac.new(
            current_app.config["API_KEY"].encode("utf8"),
            f"{hook}/{action}/{app}/{env}".encode("utf8"),
            sha256,
        ).hexdigest()
        if not hmac.compare_digest(expected, digest):
            return self.respond(status_code=403)

        try:
            hook = hooks.get(hook)
        except InvalidHook:
            return self.respond("Invalid hook", status_code=404)

        if action != "deploy":
            return self.respond("Unknown action", status_code=404)

        app = App.query.filter(App.name == app).first()
        if app is None:
            return self.respond("Invalid app", status_code=404)

        try:
            return hook.deploy(app, env)
        except NotImplementedError:
            return self.respond(status_code=404) 
Example #8
Source File: __init__.py    From virtkvm with GNU General Public License v3.0 6 votes vote down vote up
def app_switch():
    if switch.config.http.is_secure:
        secret = request.headers.get("X-Secret")
        if secret is None \
           or not hmac.compare_digest(switch.config.http.secret, secret):
            flask.abort(403)

    cases = {
        "host": switch.switch_to_host,
        "guest": switch.switch_to_guest
    }

    if not request.json \
       or not "to" in request.json \
       or not request.json["to"] in cases:
        flask.abort(400)

    error = None
    try:
        cases[request.json["to"]]()
    except:
        error = traceback.format_exc()

    return flask.jsonify({"success": True, "error": error}) 
Example #9
Source File: main.py    From python-docs-samples with Apache License 2.0 6 votes vote down vote up
def verify_signature(request):
    timestamp = request.headers.get('X-Slack-Request-Timestamp', '')
    signature = request.headers.get('X-Slack-Signature', '')

    req = str.encode('v0:{}:'.format(timestamp)) + request.get_data()
    request_digest = hmac.new(
        str.encode(os.environ['SLACK_SECRET']),
        req, hashlib.sha256
    ).hexdigest()
    request_hash = 'v0={}'.format(request_digest)

    if not hmac.compare_digest(request_hash, signature):
        raise ValueError('Invalid request/credentials.')
# [END functions_verify_webhook]


# [START functions_slack_format] 
Example #10
Source File: user.py    From arch-security-tracker with MIT License 6 votes vote down vote up
def validate(self):
        rv = BaseForm.validate(self)
        if not rv:
            return False

        if current_user.name in self.password.data:
            self.password.errors.append(ERROR_PASSWORD_CONTAINS_USERNAME)
            return False

        if self.password.data != self.password_repeat.data:
            self.password_repeat.errors.append(ERROR_PASSWORD_REPEAT_MISMATCHES)
            return False

        if not compare_digest(current_user.password, hash_password(self.password_current.data, current_user.salt)):
            self.password_current.errors.append(ERROR_PASSWORD_INCORRECT)
            return False

        return True 
Example #11
Source File: auth.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def verify_slack_requests(f=None):
    """
    Verify the request signature of the request sent from Slack
    Generate a new hash using the app's signing secret and request data
    """
    @wraps(f)
    def wrapper(*args, **kwargs):
        signature = request.headers['X-Slack-Signature']
        timestamp = request.headers['X-Slack-Request-Timestamp']
        data = request.data.decode('utf-8')
        # data = urllib.parse.urlencode(urllib.parse.unquote(raw_string))

        format_req = str.encode(f"v0:{timestamp}:{data}")
        encoded_secret = str.encode(config.SLACK_SECRET)
        request_hash = hmac.new(encoded_secret, format_req, hashlib.sha256).hexdigest()
        calculated_signature = f"v0={request_hash}"
        if hmac.compare_digest(calculated_signature, signature):
            return f(*args, **kwargs)

        return make_response(jsonify({'message': 'Invalid auth'})), 401
    return wrapper 
Example #12
Source File: utility.py    From razorpay-python with MIT License 6 votes vote down vote up
def verify_signature(self, body, signature, key):
        if sys.version_info[0] == 3:  # pragma: no cover
            key = bytes(key, 'utf-8')
            body = bytes(body, 'utf-8')

        dig = hmac.new(key=key,
                       msg=body,
                       digestmod=hashlib.sha256)

        generated_signature = dig.hexdigest()

        if sys.version_info[0:3] < (2, 7, 7):
            result = self.compare_string(generated_signature, signature)
        else:
            result = hmac.compare_digest(generated_signature, signature)

        if not result:
            raise SignatureVerificationError(
                'Razorpay Signature Verification Failed')
        return result

    # Taken from Django Source Code
    # Used in python version < 2.7.7
    # As hmac.compare_digest is not present in prev versions 
Example #13
Source File: mailgun_api_service.py    From intake with MIT License 6 votes vote down vote up
def is_a_valid_mailgun_post(request):
    """
    Taken from
        http://mailgun-documentation.readthedocs.io/en/latest/
            user_manual.html#webhooks
    :param request: Request object
    :return: True or False if the request was signed by mailgun
    """
    token = request.POST['token']
    timestamp = request.POST['timestamp']
    signature = request.POST['signature']
    key = getattr(settings, 'MAILGUN_PRIVATE_API_KEY', '').encode('utf-8')
    msg = ('{}{}'.format(timestamp, token)).encode('utf-8')
    hmac_digest = hmac.new(key=key, msg=msg, digestmod=hashlib.sha256
                           ).hexdigest()
    return hmac.compare_digest(signature, hmac_digest) 
Example #14
Source File: login.py    From arch-security-tracker with MIT License 6 votes vote down vote up
def validate(self):
        self.user = None
        rv = BaseForm.validate(self)
        if not rv:
            return False

        def fail():
            self.password.errors.append(ERROR_INVALID_USERNAME_PASSWORD)
            return False

        user = User.query.filter(User.name == self.username.data).first()
        if not user:
            compare_digest(dummy_password, hash_password(self.password.data, 'the cake is a lie!'))
            return fail()
        if not compare_digest(user.password, hash_password(self.password.data, user.salt)):
            return fail()
        if not user.active:
            self.username.errors.append(ERROR_ACCOUNT_DISABLED)
            return False
        self.user = user
        return True 
Example #15
Source File: csrf.py    From quay with Apache License 2.0 6 votes vote down vote up
def verify_csrf(
    session_token_name=_QUAY_CSRF_TOKEN_NAME,
    request_token_name=_QUAY_CSRF_TOKEN_NAME,
    check_header=True,
):
    """
    Verifies that the CSRF token with the given name is found in the session and that the matching
    token is found in the request args or values.
    """
    token = str(session.get(session_token_name, ""))
    found_token = str(request.values.get(request_token_name, ""))
    if check_header and not found_token:
        found_token = str(request.headers.get(_QUAY_CSRF_HEADER_NAME, ""))

    if not token or not found_token or not hmac.compare_digest(token, found_token):
        msg = "CSRF Failure. Session token (%s) was %s and request token (%s) was %s"
        logger.error(msg, session_token_name, token, request_token_name, found_token)
        abort(403, message="CSRF token was invalid or missing.") 
Example #16
Source File: middleware.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def __call__(self, request):
        full_token = request.META.get('HTTP_AUTHORIZATION', '')
        if not full_token:
            return self.get_response(request)

        token = self.header_pattern.match(full_token)
        if not token:
            return HttpResponse('Invalid authorization header', status=400)
        if request.path.startswith(reverse('admin:index')):
            return HttpResponse('Admin inaccessible', status=403)

        try:
            id, secret = struct.unpack('>I32s', base64.urlsafe_b64decode(token.group(1)))
            request.user = User.objects.get(id=id)

            # User hasn't generated a token
            if not request.user.profile.api_token:
                raise HTTPError()

            # Token comparison
            digest = hmac.new(force_bytes(settings.SECRET_KEY), msg=secret, digestmod='sha256').hexdigest()
            if not hmac.compare_digest(digest, request.user.profile.api_token):
                raise HTTPError()

            request._cached_user = request.user
            request.csrf_processing_done = True
            request.session['2fa_passed'] = True
        except (User.DoesNotExist, HTTPError):
            response = HttpResponse('Invalid token')
            response['WWW-Authenticate'] = 'Bearer realm="API"'
            response.status_code = 401
            return response
        return self.get_response(request) 
Example #17
Source File: jwk.py    From python-jwt with Apache License 2.0 5 votes vote down vote up
def verify(self, message: bytes, signature: bytes, **options) -> bool:
        signer = self._get_signer(options)
        return hmac.compare_digest(signature, signer(message, self.key)) 
Example #18
Source File: crypto_common.py    From torpy with Apache License 2.0 5 votes vote down vote up
def rsa_verify(pubkey, sig, dig):
    dig_size = len(dig)
    sig_int = int(sig.hex(), 16)
    pn = pubkey.public_numbers()
    decoded = pow(sig_int, pn.e, pn.n)
    buf = '%x' % decoded
    if len(buf) % 2:
        buf = '0' + buf
    buf = '00' + buf
    hash_buf = bytes.fromhex(buf)

    pad_type = b'\0\1'
    pad_len = len(hash_buf) - 2 - 1 - dig_size
    cmp_dig = pad_type + b'\xff' * pad_len + b'\0' + dig
    return compare_digest(hash_buf, cmp_dig) 
Example #19
Source File: crypto.py    From python with Apache License 2.0 5 votes vote down vote up
def constant_time_compare(val1, val2):
        return hmac.compare_digest(force_bytes(val1), force_bytes(val2)) 
Example #20
Source File: webhook.py    From python-github-webhook with Apache License 2.0 5 votes vote down vote up
def _postreceive(self):
        """Callback from Flask"""

        digest = self._get_digest()

        if digest is not None:
            sig_parts = _get_header("X-Hub-Signature").split("=", 1)
            if not isinstance(digest, six.text_type):
                digest = six.text_type(digest)

            if len(sig_parts) < 2 or sig_parts[0] != "sha1" or not hmac.compare_digest(sig_parts[1], digest):
                abort(400, "Invalid signature")

        event_type = _get_header("X-Github-Event")
        content_type = _get_header("content-type")
        data = (
            json.loads(request.form.to_dict(flat=True)["payload"])
            if content_type == "application/x-www-form-urlencoded"
            else request.get_json()
        )

        if data is None:
            abort(400, "Request body must contain json")

        self._logger.info("%s (%s)", _format_event(event_type, data), _get_header("X-Github-Delivery"))

        for hook in self._hooks.get(event_type, []):
            hook(data)

        return "", 204 
Example #21
Source File: auth.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def compare_digest(a, b, _xor_bytes=_xor_bytes):
        left = None
        right = b
        if len(a) == len(b):
            left = a
            result = 0
        if len(a) != len(b):
            left = b
            result = 1

        for x, y in zip(left, right):
            result |= _xor_bytes(x, y)
        return result == 0 
Example #22
Source File: operations.py    From dffml with MIT License 5 votes vote down vote up
def check_secret_match(self, headers, body):
    expected = headers["X-Hub-Signature"].replace("sha1=", "")
    # Getting secret value from file
    secret = await self.sctx.get(name="github_webhook")
    key = secret.encode()
    calculated = hmac.new(key, body, hashlib.sha1).hexdigest()
    match = hmac.compare_digest(expected, calculated)
    if match:
        return {"git_payload": json.loads(body.decode())}
    return 
Example #23
Source File: utils.py    From datasette-auth-github with Apache License 2.0 5 votes vote down vote up
def unsign(self, signed_value):
        if ":" not in signed_value:
            raise BadSignature("No : found")
        value, signature = signed_value.rsplit(":", 1)
        if hmac.compare_digest(signature, self.signature(value)):
            return value
        raise BadSignature("Signature does not match") 
Example #24
Source File: _compat.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def _constant_time_compare(val1, val2):
    """Return ``True`` if the two strings are equal, ``False``
    otherwise.

    The time taken is independent of the number of characters that
    match. Do not use this function for anything else than comparision
    with known length targets.

    This is should be implemented in C in order to get it completely
    right.

    This is an alias of :func:`hmac.compare_digest` on Python>=2.7,3.3.
    """
    len_eq = len(val1) == len(val2)
    if len_eq:
        result = 0
        left = val1
    else:
        result = 1
        left = val2
    for x, y in izip(bytearray(left), bytearray(val2)):
        result |= x ^ y
    return result == 0


# Starting with 2.7/3.3 the standard library has a c-implementation for
# constant time string compares. 
Example #25
Source File: _compat.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def _constant_time_compare(val1, val2):
    """Return ``True`` if the two strings are equal, ``False``
    otherwise.

    The time taken is independent of the number of characters that
    match. Do not use this function for anything else than comparision
    with known length targets.

    This is should be implemented in C in order to get it completely
    right.

    This is an alias of :func:`hmac.compare_digest` on Python>=2.7,3.3.
    """
    len_eq = len(val1) == len(val2)
    if len_eq:
        result = 0
        left = val1
    else:
        result = 1
        left = val2
    for x, y in izip(bytearray(left), bytearray(val2)):
        result |= x ^ y
    return result == 0


# Starting with 2.7/3.3 the standard library has a c-implementation for
# constant time string compares. 
Example #26
Source File: judge_handler.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def _authenticate(self, id, key):
        try:
            judge = Judge.objects.get(name=id, is_blocked=False)
        except Judge.DoesNotExist:
            result = False
        else:
            result = hmac.compare_digest(judge.auth_key, key)

        if not result:
            json_log.warning(self._make_json_log(action='auth', judge=id, info='judge failed authentication'))
        return result 
Example #27
Source File: core.py    From flask-githubapp with MIT License 5 votes vote down vote up
def _verify_webhook(self):
        signature = request.headers['X-Hub-Signature'].split('=')[1]

        mac = hmac.new(self.secret, msg=request.data, digestmod='sha1')

        if not hmac.compare_digest(mac.hexdigest(), signature):
            LOG.warning('GitHub hook signature verification failed.')
            abort(400) 
Example #28
Source File: decorators.py    From Sanic-JWT-Extended with MIT License 5 votes vote down vote up
def _csrf_check(csrf_from_request, csrf_from_jwt):
    if not csrf_from_jwt or not isinstance(csrf_from_jwt, str):
        raise CSRFError('Can not find valid CSRF data from token')
    if not compare_digest(csrf_from_request, csrf_from_jwt):
        raise CSRFError('CSRF double submit tokens do not match') 
Example #29
Source File: decorators.py    From Sanic-JWT-Extended with MIT License 5 votes vote down vote up
def compare_digest(a, b):
        if isinstance(a, str):
            a = a.encode("utf-8")
        if isinstance(b, str):
            b = b.encode("utf-8")

        if len(a) != len(b):
            return False

        r = 0
        for x, y in zip(a, b):
            r |= x ^ y

        return not r 
Example #30
Source File: api_helper.py    From comet-core with Apache License 2.0 5 votes vote down vote up
def assert_valid_token(fingerprint, token):
    """
    Check if the token given in the request is valid by comparing to the calculated API token.

    Args:
        fingerprint (str): the fingerprint to compute the API token with
        token (str): the token to validate

    Raises:
        ValueError: if the token is not valid
    """
    expected_token = fingerprint_hmac(fingerprint, current_app.config["hmac_secret"])
    if not hmac.compare_digest(bytes(expected_token, "utf-8"), bytes(token, "utf-8")):
        raise ValueError("Invalid token for the given fingerprint.")