예제 #1
0
def test_mafiles(path, entry=False):
    try:
        manifest_file = open(os.path.join(path, 'manifest.json'))
    except IOError:
        return False
    test_manifest = json.load(manifest_file)
    if entry:
        try:
            with open(
                    os.path.join(path, test_manifest['entries'][entry]
                                 ['filename'])) as maf_file:
                maf = json.loads(maf_file.read())
            sa = guard.SteamAuthenticator(secrets=maf)
            sa.get_code()
        except (IOError, json.decoder.JSONDecodeError,
                guard.SteamAuthenticatorError):
            manifest_file.close()
            return False
        manifest_file.close()
        return True
    else:
        valid_entries = []
        for i in test_manifest['entries']:
            try:
                with open(os.path.join(path, i['filename'])) as maf_file:
                    maf = json.loads(maf_file.read())
                sa = guard.SteamAuthenticator(secrets=maf)
                sa.get_code()
                valid_entries.append(i)
            except (IOError, json.decoder.JSONDecodeError,
                    guard.SteamAuthenticatorError):
                continue
        manifest_file.close()
        return valid_entries
예제 #2
0
def get_2FA():
    acc = get_account_list(False, True)
    req = {"twoFA": {}}

    sa_time = guard.SteamAuthenticator()
    time = 30 - (sa_time.get_time() % 30)
    req["reload_time"] = time * 1000

    for Sid, data in acc.items():
        if ("guard" in data):
            sa = guard.SteamAuthenticator(data["guard"])
            req["twoFA"][Sid] = sa.get_code()

    return req
예제 #3
0
def import_shared_secret(mafile, notest=False):  # mafile
    mafile = json.loads(mafile)
    Sid = str(mafile["Session"]["SteamID"])
    acc = get_account_list(False, True)
    if (Sid not in acc):
        return "acc_not_found"

    user_conf = acc[Sid]

    if (notest == False):
        try:
            user_login = wa.MobileWebAuth(user_conf["name"])
            sa = guard.SteamAuthenticator(mafile)
            code = sa.get_code()
            user_login.login(user_conf["password"], twofactor_code=code)
        except:
            return "login_error"

    user_path = path + "user_config/" + user_conf["name"] + ".json"
    with open(user_path, "r") as file:
        user_conf = json.load(file)

    user_conf["guard"] = mafile

    with open(user_path, "w") as file:
        json.dump(user_conf, file)
    return True
예제 #4
0
 def __init__(self, name: str, oauth: str, steamid: str) -> None:  #創建驗證器
     self.name = name
     self.oauth = oauth
     self.steamid = steamid
     self.wa = wa.MobileWebAuth(name)
     try:
         self.wa.oauth_login(oauth, steamid)
     except:
         return print("oauth_error")
     self.sa = guard.SteamAuthenticator(backend=self.wa)
예제 #5
0
파일: core.py 프로젝트: oczkers/smapi
 def __init__(
         self,
         username: str,
         passwd: str,
         secrets: dict,
         currency: int,  # default to USD?
         country: str,  # default to Germany?
         android_id: str) -> None:
     self.username = username
     self.passwd = passwd
     self.secrets = secrets
     # self.r.headers.encoding = 'utf8'  # temporary
     self.r = httpx.Client(timeout=300, headers=headers)
     self.currency = currency  # 6 PLN, 3 EUR, 18 UAH
     self.country = country  # PL, ?, UA
     self.android_id = android_id
     self.sa = guard.SteamAuthenticator(secrets=self.secrets)
     # load saved cookies/session
     try:
         with open('cookies.json', 'r') as f:
             self.r.cookies.update(json.load(f))
     except json.JSONDecodeError:  # file corupted or empty
         pass
     except FileNotFoundError:
         pass
     # encode password
     rc = self.r.get('https://steamcommunity.com/login/home/')
     self.username = str(
         rc.url).split('/')[-1]  # gonna be false if not logged
     rc = rc.text
     open('smapi.log', 'w').write(rc)
     if 'javascript:Logout();' not in rc:
         print('RELOGIN')
         self.r.cookies = {}  # reset cookies
         self.login(username, passwd)
         # TODO?: detect session_id in login
         rc = self.r.get('https://steamcommunity.com/login/home/').text
         open('smapi.log', 'w').write(rc)
     self.session_id = re.search('g_sessionID = "(.+?)";', rc).group(1)
     # rc = self.r.get('https://steamcommunity.com/id/oczun/').text
     self.steam_id = re.search('g_steamID = "([0-9]+?)";', rc).group(1)
     self.saveSession()
예제 #6
0
def app_load():
    global mafiles_folder_path, mafile_name, manifest_entry_index, manifest

    base_path = os.path.dirname(os.path.abspath(sys.executable)) if getattr(sys, 'frozen', False)\
        else os.path.dirname(os.path.abspath(__file__))
    if test_mafiles(os.path.join(base_path, 'maFiles')):
        mafiles_folder_path = os.path.join(base_path, 'maFiles')
    elif test_mafiles(os.path.expanduser(os.path.join(
            '~', '.maFiles'))) and '--dbg' not in sys.argv:
        mafiles_folder_path = os.path.expanduser(os.path.join('~', '.maFiles'))
    else:
        mafiles_folder_path = os.path.join(base_path, 'maFiles') if os.path.basename(os.path.normpath(base_path)) ==\
                                      'PySteamAuth' else os.path.expanduser(os.path.join('~', '.maFiles'))
    while True:
        try:
            with open(os.path.join(mafiles_folder_path,
                                   'manifest.json')) as manifest_file:
                manifest = json.loads(
                    manifest_file.read())  # TODO add encryption support
            valid_entries = test_mafiles(mafiles_folder_path)
            if len(valid_entries) == 0:
                raise ValueError('No valid Manifest Entries found!')
            manifest_entry_index = 0
            if len(manifest['entries']) > 1:
                if ('selected_account'
                        in manifest) and manifest['selected_account'] < len(
                            manifest['entries']):
                    manifest_entry_index = manifest['selected_account']
                else:
                    ac_dialog = QtWidgets.QDialog()
                    ac_ui = PyUIs.AccountChooserDialog.Ui_Dialog()
                    ac_ui.setupUi(ac_dialog)
                    for i in valid_entries:
                        try:
                            entry = [None, str(i['steamid']), i['filename']]
                            with open(
                                    os.path.join(mafiles_folder_path,
                                                 i['filename'])) as ma_file:
                                entry[0] = json.load(ma_file)['account_name']
                            ac_ui.accountSelectList.addTopLevelItem(
                                QtWidgets.QTreeWidgetItem(entry))
                        except (json.JSONDecodeError, IOError):
                            continue
                    # noinspection PyUnresolvedReferences
                    ac_dialog.rejected.connect(sys.exit)
                    ac_ui.accountSelectList.itemSelectionChanged.connect(
                        lambda: ac_ui.buttonBox.setDisabled(
                            len(ac_ui.accountSelectList.selectedItems()) != 1))
                    ac_dialog.exec_()
                    manifest_entry_index = ac_ui.accountSelectList.selectedIndexes(
                    )[0].row()
                    manifest['selected_account'] = manifest_entry_index
            mafile_name = manifest['entries'][manifest_entry_index]['filename']
            with open(os.path.join(mafiles_folder_path, mafile_name),
                      'r+') as ma_file:
                maf = json.load(ma_file)
                if 'device_id' not in maf:
                    maf['device_id'] = guard.generate_device_id(maf['steamid'])
                    ma_file.seek(0)
                    ma_file.write(json.dumps(maf))
                    ma_file.truncate()
            if not test_mafiles(mafiles_folder_path, manifest_entry_index):
                raise IOError()
            break
        except (IOError, ValueError, TypeError, IndexError, KeyError) as e:
            if os.path.isdir(mafiles_folder_path):
                if any('maFile' in x for x in os.listdir(mafiles_folder_path)) or 'manifest.json'\
                        in os.listdir(mafiles_folder_path):
                    Common.error_popup('Failed to load maFile: ' + str(e))
            setup_dialog = QtWidgets.QDialog()
            setup_ui = PyUIs.SetupDialog.Ui_Dialog()
            setup_ui.setupUi(setup_dialog)
            setup_ui.setupButton.clicked.connect(
                lambda: (setup_dialog.accept(), add_authenticator()))
            setup_ui.importButton.clicked.connect(
                lambda: (copy_mafiles(), setup_dialog.accept()))
            setup_ui.quitButton.clicked.connect(sys.exit)
            setup_dialog.exec_()
    sa = guard.SteamAuthenticator(maf)
    main_window.setWindowTitle('PySteamAuth - ' + sa.secrets['account_name'])
    main_ui.codeBox.setText(sa.get_code())
    main_ui.codeBox.setAlignment(QtCore.Qt.AlignCenter)
    main_ui.copyButton.clicked.connect(
        lambda: (main_ui.codeBox.selectAll(), main_ui.codeBox.copy()))
    main_ui.codeTimeBar.setTextVisible(False)
    main_ui.codeTimeBar.valueChanged.connect(main_ui.codeTimeBar.repaint)
    main_ui.tradeCheckBox.setChecked(manifest['auto_confirm_trades'])
    main_ui.marketCheckBox.setChecked(
        manifest['auto_confirm_market_transactions'])
    main_ui.confAllButton.clicked.connect(lambda: accept_all(sa))
    main_ui.confListButton.clicked.connect(lambda: open_conf_dialog(sa))
    main_ui.removeButton.clicked.connect(lambda: remove_authenticator(sa))
    main_ui.createBCodesButton.clicked.connect(lambda: backup_codes_popup(sa))
    main_ui.removeBCodesButton.clicked.connect(lambda: backup_codes_delete(sa))
    main_ui.actionOpen_Current_maFile.triggered.connect(
        lambda c: open_path(os.path.join(mafiles_folder_path, mafile_name)))
    main_ui.actionSwitch.triggered.connect(lambda c: (manifest.pop(
        'selected_account'), save_mafiles(sa), restart()))

    code_timer = QtCore.QTimer(main_window)
    code_timer.setInterval(1000)
    code_timer.timeout.connect(
        lambda: code_update(sa, main_ui.codeBox, main_ui.codeTimeBar))
    main_ui.codeTimeBar.setValue(30 - (sa.get_time() % 30))
    code_timer.start()

    aa_timer = QtCore.QTimer(main_window)
    aa_timer.setInterval(5000)
    set_autoaccept(aa_timer, sa, main_ui.tradeCheckBox.isChecked(),
                   main_ui.marketCheckBox.isChecked())
    main_ui.tradeCheckBox.stateChanged.connect(
        lambda: set_autoaccept(aa_timer, sa, main_ui.tradeCheckBox.isChecked(),
                               main_ui.marketCheckBox.isChecked()))
    main_ui.marketCheckBox.stateChanged.connect(
        lambda: set_autoaccept(aa_timer, sa, main_ui.tradeCheckBox.isChecked(),
                               main_ui.marketCheckBox.isChecked()))

    main_window.show()
    main_window.raise_()

    save_mafiles(sa)
예제 #7
0
def add_authenticator():
    endfunc = Empty()
    endfunc.endfunc = False
    mwa = AccountHandler.get_mobilewebauth()
    if not mwa:
        return
    sa = guard.SteamAuthenticator(backend=mwa)
    if not sa.has_phone_number():
        code_dialog = QtWidgets.QDialog()
        code_ui = PyUIs.PhoneDialog.Ui_Dialog()
        code_ui.setupUi(code_dialog)
        code_ui.buttonBox.rejected.connect(
            lambda: setattr(endfunc, 'endfunc', True))
        code_dialog.setWindowTitle('Phone number')
        code_ui.actionBox.setText(
            'This account is missing a phone number. Type yours below to add it.\n'
            'Eg. +1 123-456-7890')
        code_dialog.exec_()
        if endfunc.endfunc:
            return
        if sa.add_phone_number(code_ui.codeBox.text().replace('-', '')):
            code_dialog = QtWidgets.QDialog()
            code_ui = PyUIs.PhoneDialog.Ui_Dialog()
            code_ui.setupUi(code_dialog)
            code_ui.buttonBox.rejected.connect(
                lambda: setattr(endfunc, 'endfunc', True))
            code_dialog.exec_()
            if endfunc.endfunc:
                return
            if not sa.confirm_phone_number(code_ui.codeBox.text()):
                Common.error_popup('Failed to confirm phone number')
                return
        else:
            Common.error_popup('Failed to add phone number.')
            return
    try:
        sa.add()
    except guard.SteamAuthenticatorError as e:
        if 'DuplicateRequest' in str(e):
            code_dialog = QtWidgets.QDialog()
            code_ui = PyUIs.PhoneDialog.Ui_Dialog()
            code_ui.setupUi(code_dialog)
            code_ui.buttonBox.rejected.connect(
                lambda: setattr(endfunc, 'endfunc', True))
            code_dialog.setWindowTitle('Remove old authenticator')
            code_ui.actionBox.setText(
                'There is already an authenticator associated with this account.'
                ' Enter its revocation code to remove it.')
            code_dialog.exec_()
            if endfunc.endfunc:
                return
            sa.secrets = {'revocation_code': code_ui.codeBox.text()}
            sa.revocation_code = code_ui.codeBox.text()
            try:
                sa.remove()
                sa.add()
            except guard.SteamAuthenticatorError as e:
                Common.error_popup(str(e))
                return
        else:
            Common.error_popup(e)
            return
    if os.path.isdir(mafiles_folder_path):
        if any('maFile' in x for x in os.listdir(mafiles_folder_path)) or 'manifest.json'\
                in os.listdir(mafiles_folder_path):
            Common.error_popup(
                'The maFiles folder in the app folder is not empty.\nPlease remove it.'
            )
            return
        else:
            shutil.rmtree(mafiles_folder_path)
    os.mkdir(mafiles_folder_path)
    with open(os.path.join(mafiles_folder_path, mwa.steam_id + '.maFile'),
              'w') as maf:
        maf.write(json.dumps(sa.secrets))
    with open(os.path.join(mafiles_folder_path, 'manifest.json'),
              'w') as manifest_file:
        manifest_file.write(
            json.dumps({
                'periodic_checking':
                False,
                'first_run':
                False,
                'encrypted':
                False,
                'periodic_checking_interval':
                5,
                'periodic_checking_checkall':
                False,
                'auto_confirm_market_transactions':
                False,
                'entries': [{
                    'steamid': mwa.steam_id,
                    'encryption_iv': None,
                    'encryption_salt': None,
                    'filename': mwa.steam_id + '.maFile'
                }],
                'auto_confirm_trades':
                False
            }))
    Common.error_popup(
        'This is your revocation code. Write it down physically and keep it. You will need it in case'
        ' you lose your authenticator.', sa.secrets['revocation_code'])
    code_dialog = QtWidgets.QDialog()
    code_ui = PyUIs.PhoneDialog.Ui_Dialog()
    code_ui.setupUi(code_dialog)
    code_ui.buttonBox.rejected.connect(
        lambda: setattr(endfunc, 'endfunc', True))
    while True:
        code_dialog.exec_()
        if endfunc.endfunc:
            return
        try:
            sa.finalize(code_ui.codeBox.text())
            break
        except guard.SteamAuthenticatorError as e:
            code_ui.msgBox.setText(str(e))
예제 #8
0
    def steam_start(self, bot):
        print('Steam is now logging on')
        bot.log.info('Steam is now logging on')
        bot.client = SteamClient()
        bot.client.set_credential_location('Login_details')  # where to store sentry files and other stuff



        @bot.client.on('error')
        def handle_error(result):
            bot.log.error(f'Logon result: {repr(result)}')

        @bot.client.on('connected')
        def handle_connected():
            bot.log.info(f'Connected to: {bot.client.current_server_addr}')

        @bot.client.on('reconnect')
        def handle_reconnect(delay):
            if bot.client is None:
                raise SystemExit
            bot.log.info(f'Reconnect in {delay}...')

        @bot.client.on('disconnected')
        def handle_disconnect():
            bot.log.warning('Disconnected.')
            if bot.client is None:
                raise SystemExit
            if bot.client.relogin_available:
                bot.log.info('Reconnecting...')
                bot.client.reconnect(maxdelay=30)

        @bot.client.on('logged_on')
        def handle_after_logon():
            bot.s_bot = bot.client.get_user(bot.bot64id)
            bot.logged_on = True
            bot.log.info(f'Logged on as: {bot.client.user.name}')

        @bot.client.on('chat_message')
        def handle_message(user, message_text):
            if user.steam_id == bot.bot64id:
                if message_text.startswith('Message from'):
                    bot.user_message = message_text
                elif bot.current_time.split()[1] == '23:59' \
                        and message_text.startswith("You've made") \
                        or message_text.startswith("Trades today"):
                    bot.daily = message_text

                else:
                    bot.sbotresp = message_text

        if preferences.cli_login:
            bot.log.info('Logging in using cli_login')
            result = bot.client.cli_login(username=sensitive_details.username, password=sensitive_details.password)
        else:
            bot.log.info('Logging in using automatic')
            SA = guard.SteamAuthenticator(sensitive_details.secrets).get_code()
            result = bot.client.login(username=sensitive_details.username, password=sensitive_details.password,
                                      two_factor_code=SA)
            if result == EResult.TwoFactorCodeMismatch:
                sleep(2)
                result = bot.client.login(username=sensitive_details.username, password=sensitive_details.password,
                                          two_factor_code=SA)

        if result != EResult.OK:
            bot.log.fatal(f'Failed to login: {repr(result)}')
            raise SystemExit
        bot.client.run_forever()
예제 #9
0
import gevent.monkey
gevent.monkey.patch_socket()
gevent.monkey.patch_ssl()
from steam import guard
from steam.client import SteamClient
from steam.enums import EResult

print("\nSteam Bot")
print("-" * 20)

config = open("config.txt", "r+").read().splitlines()

secrets = {'shared_secret': config[5], 'identity_secret': config[7]}

SA = guard.SteamAuthenticator(secrets)

client = SteamClient()


@client.on("error")
def handle_error(result):
    print("\nError", result)


@client.on("connected")
def handle_connected():
    print("Logged on as", user)
    print("Auto accept friend requests is enabled.")
    print("Auto message is enabled.")
    print("-" * 20)
    print("Press Ctrl + C to exit")
예제 #10
0
def login(steamid, lock=False, _app=False, force=False):
    eel.info("使用模擬登入",
             "steamid:" + steamid + "\n強制模式:" + ("是" if force else "否"),
             "console")
    acc = call_info(steamid)

    if (force == False and (steamid in get_client_users())):
        eel.info("模式切換", "偵測到快取模式\n轉為快取模式", "console")
        auto_login(steamid, acc["name"], lock)
        return

    if (acc == False):
        eel.info("無帳號", "", "error")
        if (lock != False):
            lock.release()
        return "no_account"

    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "SOFTWARE\Valve\Steam", 0,
                         winreg.KEY_QUERY_VALUE)
    exe, t = winreg.QueryValueEx(key, "SteamExe")
    winreg.CloseKey(key)

    si = subprocess.STARTUPINFO()
    si.dwFlags |= subprocess.STARTF_USESHOWWINDOW

    if (_app == False):  #如果沒有到拾取app
        eel.info("關閉steam", "", "console")
        close_steam(exe, si)

    # str replace
    password = str.replace(acc["password"], "{", "{{}")
    password = str.replace(password, " ", "{SPACE}")
    password = str.replace(password, "+", "{+}")
    password = str.replace(password, "^", "{^}")
    password = str.replace(password, "%", "{%}")
    # set RememberPassword
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "SOFTWARE\Valve\Steam", 0,
                         winreg.KEY_SET_VALUE)
    winreg.SetValueEx(key, "RememberPassword", 0, winreg.REG_DWORD, 0x00000001)
    winreg.SetValueEx(key, "AutoLoginUser", 0, winreg.REG_SZ, "")
    winreg.CloseKey(key)
    # auto login
    if (_app == False):
        app = APP().start(exe)
    else:
        app = _app
    login_gui = app.window(title_re='Steam [^Guard].*',
                           class_name='vguiPopupWindow')
    try:
        login_gui.wait("ready", 30)
    except timings.TimeoutError:
        eel.info("等待超時", "", "console")
        del app
        if (lock != False):
            lock.release()
        return "error"

    eel.info("自動登入", "登入頁面 已就緒\n開始自動輸入", "console")
    login_gui.set_focus()
    sleep(.1)
    if (_app == False):
        eel.info("自動輸入名稱 [未輸入名稱]", "", "console")
        keyboard.send_keys(acc["name"] + """{TAB}""")
    eel.info("自動輸入密碼", "", "console")
    keyboard.send_keys(password)
    keyboard.send_keys("""{TAB}{ENTER}""")

    if (acc["se"] == False):  #guard
        eel.info("無guard", "跳過guard登入頁面", "console")
    else:
        eel.info("等待guard", "已添加guard\n自動輸入guard", "console")
        sa = guard.SteamAuthenticator(acc["se"])
        guard_gui = app.window(title_re='Steam Guard - .*',
                               class_name='vguiPopupWindow')

        guard_gui.wait("ready")
        guard_gui.set_focus()
        sleep(.1)

        code = sa.get_code()
        keyboard.send_keys(code + """{ENTER}""")
    eel.info("等待登入頁面被關閉", "", "console")
    login_gui.wait_not("visible", 60000)
    eel.info("登入完成", "", "console")
    del app
    if (lock != False):
        lock.release()
예제 #11
0
def shared_secret_to_2FA(req: str):
    se = json.loads(req)
    sa = guard.SteamAuthenticator(se)
    return sa.get_code()