#--------------------------------
# GOOGLE CHROME SECURITY SETTINGS
#--------------------------------
chrome_safe_browsing_options = 2
chrome_HTTPS_Only_Mode_options = 1
chrome_PasswordLeakDetection_options = 1

#--------------------------------
# MICROSOFT EDGE SECURITY SETTINGS
#--------------------------------
TrackingPrevention_options = 3
EnhanceSecurityMode_options = 2
MD_SmartScreen_options = 1
BlockPotentiallyUnwantedApps_options = 1
WebsiteTypoProtection_options = 1
SiteSafetyServices_options = 1
Scareware_Blocker_options = 1   # applies to BOTH Scareware policies
Edge_HTTPS_Only_Mode_options = 1


#--------------------------------
# FIREFOX SECURITY SETTINGS
#--------------------------------
EnableTrackingProtection_options = 1
Https_Only_Mode_options = 1
SafeBrowsing_options = 1
PrivateBrowsing_options = 1

#--------------------------------
# PYTHON SCRIPT STARTS
#--------------------------------
import os
from subprocess import PIPE, Popen
import ctypes

BatchScript = r"""
@echo off
set "user="

for /f "skip=1 tokens=1,* delims=\" %%A in ('
    wmic computersystem get username ^|
    powershell -noprofile -command "$input.trim()"
') do set "user=%%~B"

echo %user%
"""

class BrowserSettings:

    class disable_file_system_redirection:
        _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
        _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
        def __enter__(self):
            self.old_value = ctypes.c_long()
            self.success = self._disable(ctypes.byref(self.old_value))
        def __exit__(self, type, value, traceback):
            if self.success:
                self._revert(self.old_value)

    def ecmd(self, command):
        with self.disable_file_system_redirection():
            return Popen(command, shell=True, stdout=PIPE, stderr=PIPE).communicate()

    #--------------------------------
    # CHROME
    #--------------------------------
    def chrome_settings(self):
        print(self.ecmd(
            'REG ADD HKLM\\Software\\Policies\\Google\\Chrome /v SafeBrowsingProtectionLevel '
            '/t REG_DWORD /d %s /f' % chrome_safe_browsing_options
        ))

        if chrome_HTTPS_Only_Mode_options == 0:
            print(self.ecmd(
                'REG ADD HKLM\\Software\\Policies\\Google\\Chrome /v HttpsOnlyMode '
                '/t REG_SZ /d disallowed /f'
            ))
        else:
            print(self.ecmd(
                'REG ADD HKLM\\Software\\Policies\\Google\\Chrome /v HttpsOnlyMode '
                '/t REG_SZ /d force_enabled /f'
            ))

        print(self.ecmd(
            'REG ADD HKLM\\Software\\Policies\\Google\\Chrome /v PasswordLeakDetectionEnabled '
            '/t REG_DWORD /d %s /f' % chrome_PasswordLeakDetection_options
        ))

    #--------------------------------
    # EDGE
    #--------------------------------
    def Edge_settings(self):

        edge_path = "HKLM\\Software\\Policies\\Microsoft\\Edge"

        print(self.ecmd(
            'REG ADD %s /v TrackingPrevention /t REG_DWORD /d %s /f'
            % (edge_path, TrackingPrevention_options)
        ))

        print(self.ecmd(
            'REG ADD %s /v EnhanceSecurityMode /t REG_DWORD /d %s /f'
            % (edge_path, EnhanceSecurityMode_options)
        ))

        print(self.ecmd(
            'REG ADD %s /v TyposquattingCheckerEnabled /t REG_DWORD /d %s /f'
            % (edge_path, WebsiteTypoProtection_options)
        ))

        print(self.ecmd(
            'REG ADD %s /v SiteSafetyServicesEnabled /t REG_DWORD /d %s /f'
            % (edge_path, SiteSafetyServices_options)
        ))

        # ---------------------------
        # HTTPS-ONLY MODE (Edge UI shows "Always use secure connections")
        # ---------------------------
        if Edge_HTTPS_Only_Mode_options == 0:
            edge_https_value = "disallowed"
        elif Edge_HTTPS_Only_Mode_options == 2:
            edge_https_value = "force_balanced_enabled"
        else:
            edge_https_value = "force_enabled"
        
        print(self.ecmd(
            'REG ADD %s /v HttpsOnlyMode /t REG_SZ /d %s /f'
            % (edge_path, edge_https_value)
        ))

        # ---------------------------
        # SCAREWARE BLOCKER (GLOBAL)
        # ---------------------------
        print(self.ecmd(
            'REG ADD %s /v ScarewareBlockerProtectionEnabled /t REG_DWORD /d %s /f'
            % (edge_path, Scareware_Blocker_options)
        ))

        print(self.ecmd(
            'REG ADD %s /v ScarewareBlockerBlocksDetectedSitesEnabled /t REG_DWORD /d %s /f'
            % (edge_path, Scareware_Blocker_options)
        ))

        #--------------------------------
        # SmartScreen & PUA — Per User
        #--------------------------------
        batch_script_path = os.path.join(os.environ["TEMP"], "currentuser.bat")
        open(batch_script_path, "w").write(BatchScript)

        with self.disable_file_system_redirection():
            curusername = os.popen(batch_script_path).read().strip()

            users = os.popen(
                "wmic UserAccount get Name"
            ).read().strip().splitlines()

            fil_users = [
                u.strip() for u in users
                if u.strip() not in
                ["Administrator", "DefaultAccount", "Guest", "WDAGUtilityAccount"]
                and u.strip() != ""
            ]

            # Current user
            curmatch = [u for u in fil_users if u.lower() == curusername.lower()]
            if curmatch:
                user = curmatch[0]
                try:
                    sid = os.popen(
                        'wmic useraccount where name="%s" get sid' % user
                    ).read().splitlines()[1].strip()

                    print(self.ecmd(
                        'REG ADD "HKEY_USERS\\%s\\Software\\Microsoft\\Edge" '
                        '/v SmartScreenEnabled /t REG_DWORD /d %s /f'
                        % (sid, MD_SmartScreen_options)
                    ))

                    print(self.ecmd(
                        'REG ADD "HKEY_USERS\\%s\\Software\\Microsoft\\Edge" '
                        '/v SmartScreenPuaEnabled /t REG_DWORD /d %s /f'
                        % (sid, BlockPotentiallyUnwantedApps_options)
                    ))

                except:
                    pass

                fil_users.remove(user)

            # Other user profiles
            for u in fil_users:
                ntpath = "C:\\Users\\%s\\ntuser.dat" % u
                if os.path.exists(ntpath):
                    out, _ = self.ecmd(
                        'reg load "HKU\\%s" "%s"' % (u, ntpath)
                    )
                    if out:
                        print(self.ecmd(
                            'REG ADD "HKEY_USERS\\%s\\Software\\Microsoft\\Edge" '
                            '/v SmartScreenEnabled /t REG_DWORD /d %s /f'
                            % (u, MD_SmartScreen_options)
                        ))

                        print(self.ecmd(
                            'REG ADD "HKEY_USERS\\%s\\Software\\Microsoft\\Edge" '
                            '/v SmartScreenPuaEnabled /t REG_DWORD /d %s /f'
                            % (u, BlockPotentiallyUnwantedApps_options)
                        ))

                        os.popen('reg unload "HKU\\%s"' % u)

    #--------------------------------
    # FIREFOX
    #--------------------------------
    def Firefox_settings(self):

        print(self.ecmd(
            'REG ADD HKLM\\Software\\Policies\\Mozilla\\Firefox\\EnableTrackingProtection '
            '/v Value /t REG_DWORD /d %s /f'
            % EnableTrackingProtection_options
        ))

        print(self.ecmd(
            'REG ADD HKLM\\Software\\Policies\\Mozilla\\Firefox\\Preferences '
            '/v dom.security.https_only_mode /t REG_DWORD /d %s /f'
            % Https_Only_Mode_options
        ))

        prefs = [
            "browser.safebrowsing.phishing.enabled",
            "browser.safebrowsing.malware.enabled",
            "browser.safebrowsing.downloads.enabled",
            "browser.safebrowsing.downloads.remote.block_uncommon",
            "browser.safebrowsing.downloads.remote.block_potentially_unwanted"
        ]

        for p in prefs:
            print(self.ecmd(
                'REG ADD HKLM\\Software\\Policies\\Mozilla\\Firefox\\Preferences '
                '/v %s /t REG_DWORD /d %s /f'
                % (p, SafeBrowsing_options)
            ))

        print(self.ecmd(
            'REG ADD HKLM\\Software\\Policies\\Mozilla\\Firefox '
            '/v DisablePrivateBrowsing /t REG_DWORD /d %s /f'
            % PrivateBrowsing_options
        ))


    #--------------------------------
    # RUN EVERYTHING
    #--------------------------------
    def change_settings(self):
        self.chrome_settings()
        self.Edge_settings()
        self.Firefox_settings()


browserOBJ = BrowserSettings()
browserOBJ.change_settings()
