Skip to content

Instantly share code, notes, and snippets.

@trueroad
Last active July 11, 2022 15:04
Show Gist options
  • Save trueroad/9d9002150ae871d25806db1ff495e424 to your computer and use it in GitHub Desktop.
Save trueroad/9d9002150ae871d25806db1ff495e424 to your computer and use it in GitHub Desktop.
Experiment native app like that uses get encrypted session CGI.
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Experiment native app like that uses get encrypted session CGI.
https://gist.github.com/trueroad/9d9002150ae871d25806db1ff495e424
Copyright (C) 2022 Masamichi Hosoda.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
"""
import os
import sys
from typing import Any, Dict, Final, List, Tuple
import urllib.parse
import webbrowser
from cryptography.hazmat.primitives.ciphers import (
Cipher, algorithms, modes
)
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import requests
# セッションクッキーの名前
SESSION_COOKIE_NAME: Final[str] = 'mod_auth_openidc_session'
# Get encrypted session CGI の URL
# CGI のソースは
# https://gist.github.com/trueroad/e08efb3a1096c6df7243f6b1deed9d57
URL_GET_ENCRYPTED_SESSION: Final[str] = \
'https://example.com/oidc/cgi-bin/get_encrypted_session.cgi'
# ネイティブアプリ ID とネイティブアプリシークレット
SECRET: Final[Tuple[str, str]] = (
'native_app_id_0001', 'native_app_secret_0001'
)
# 最後に表示するテスト用 URL
URL_FOR_TEST: Final[str] = 'https://example.com/oidc/'
def decrypt(password: str,
salt: bytes, iv: bytes, ciphertext: bytes, tag: bytes
) -> str:
"""
文字列を復号化する.
Args:
password (str): 暗号化パスワード
salt (bytes): ソルト
iv (bytes): 初期化ベクタ
ciphertext (bytes): 暗号本文
tag (bytes): タグ
Returns:
str: 復号化された文字列
"""
password_bytes: bytes = password.encode('utf-8')
# 鍵導出
kdf: PBKDF2HMAC = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=390000,
)
key: bytes = kdf.derive(password_bytes)
# 復号化設定
decryptor = Cipher(
algorithms.AES(key),
modes.GCM(iv, tag),
).decryptor()
# 復号化
plaintext_bytes: bytes = \
decryptor.update(ciphertext) + decryptor.finalize()
return plaintext_bytes.decode('utf-8')
def main() -> None:
"""メイン."""
# ブラウザでネイティブアプリ ID を指定して
# get encrypted session CGI を開く
webbrowser.open(URL_GET_ENCRYPTED_SESSION + '?' +
urllib.parse.urlencode({'app_id': SECRET[0]}))
# ブラウザでログイン操作が終わると表示される
# 暗号化したセッションクッキーの値を入力させる
# (本来はブラウザにネイティブアプリをキックさせるが、
# 今回は省略して手動入力する)
encrypted: str = input('Input encrypted response> ')
# 入力された値をパース
query_in_dict: Dict[str, List[str]] = \
urllib.parse.parse_qs(encrypted)
# 各要素を取り出す
salt: bytes = bytes.fromhex(query_in_dict['salt'][0])
iv: bytes = bytes.fromhex(query_in_dict['iv'][0])
ciphertext: bytes = bytes.fromhex(query_in_dict['ciphertext'][0])
tag: bytes = bytes.fromhex(query_in_dict['tag'][0])
# ネイティブアプリシークレットを使ってセッションクッキーの値を復号化
plaintext: str = decrypt(SECRET[1], salt, iv, ciphertext, tag)
# セッションクッキーを付与してテスト用 URL へリクエストを投げる
resp: requests.models.Response = \
requests.get(URL_FOR_TEST, cookies={SESSION_COOKIE_NAME: plaintext})
# レスポンスを表示する
# ログイン状態の内容が表示されれば成功
resp.encoding = 'utf-8'
print(resp.text)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment