Ejemplo n.º 1
0
    def sync_time_w_ntp():
        if not SystemTime.is_time_to_sync():
            p("}}gnNot time to sync w NTP servers yet, skipping.}}xx",
              log_level=4)
            return True

        RegistrySettings.set_reg_value(value_name="last_ntp_sync",
                                       value=time.time())

        smc_url = RegistrySettings.get_reg_value(value_name="smc_url",
                                                 default="https://smc.ed")
        smc_host = smc_url.lower().replace("https://",
                                           "").replace("http://",
                                                       "").replace("/", "")
        if ":" in smc_host:
            # port :8000 - remove it
            pos = smc_host.index(":")
            smc_host = smc_host[:pos]

        # Pull the current time from the SMC server and set it locally.
        # HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers
        # w32tm /stripchart /computer:smc.ed /dataonly /samples:5
        # w32tm /query /peers

        # Add our time servers to the list
        os.system("w32tm /config /update /manualpeerlist:\"" + smc_host +
                  " time.windows.com 202.5.222.1\"")
        # Force the update
        os.system("w32tm /resync /nowait")  # /nowait

        return True
Ejemplo n.º 2
0
    def remove_nic():
        # Get the params for the nic
        nic_name = util.get_param(2)
        nic_network = util.get_param(3)

        if nic_name == "" or nic_network == "":
            p("}}rbError - Invalid paramaters!}}xx")
            return False

        # Get the list of approved nics
        # Load the value from the registry
        try:
            approved_nics_json = RegistrySettings.get_reg_value(
                app="OPEService", value_name="approved_nics", default="[]")
            nic_list = json.loads(approved_nics_json)
            new_nic_list = []
            # Loop through old list and add any that don't match remove parameters
            removed = False
            for item in nic_list:
                #p("checking " + item[0] + " -> " + item[1])
                if item[0] == nic_name and item[1] == nic_network:
                    #p("FOUND!")
                    removed = True
                else:
                    # Not the one to remove, put it in the new_nic_list
                    new_nic_list.append(item)

            if removed:
                # Write this back to the registry
                approved_nics_json = json.dumps(new_nic_list)
                RegistrySettings.set_reg_value(app="OPEService",
                                               value_name="approved_nics",
                                               value=approved_nics_json)
                p("}}gnRemoved " + nic_name + " on netowrk " + nic_network +
                  "}}xx",
                  log_level=1)
            else:
                p("}}rnNOT FOUND - NOT Removed " + nic_name + " on netowrk " +
                  nic_network +
                  " (Can't remove system pre-approved nic entries)}}xx")
        except Exception as ex:
            p("}}rbUnable to write approved nics to the registry!}}xx\n" +
              str(ex),
              log_level=1)
            return False

        # Force device list refresh
        NetworkDevices.init_device_list(refresh=True)

        return True
Ejemplo n.º 3
0
    def init_device_list(refresh=False):
        # Build up the nic list
        if not refresh and len(NetworkDevices.NIC_LIST) > 0:
            # Don't rebuild it has been done
            return True

        n_list = []
        n_list += NetworkDevices.default_microsoft_nics
        n_list += NetworkDevices.default_approved_nics

        # Load the value from the registry
        try:
            approved_nics_json = RegistrySettings.get_reg_value(
                app="OPEService", value_name="approved_nics", default="[]")
            nic_list = json.loads(approved_nics_json)
            for item in nic_list:
                # Add each item to the list
                # p("found nic " + str(item))
                n_list.append(item)

        except Exception as ex:
            p("}}rbUnable to pull approved nics from registry!}}xx")

        # Set the current list
        NetworkDevices.NIC_LIST = n_list
        return True
Ejemplo n.º 4
0
    def list_approved_nics():
        # Show a list of approved nics
        NetworkDevices.init_device_list()

        # Get the specifically approved nics vs the default approved
        manually_approved_nics = []
        # Load the value from the registry
        try:
            approved_nics_json = RegistrySettings.get_reg_value(
                app="OPEService", value_name="approved_nics", default="[]")
            manually_approved_nics = json.loads(approved_nics_json)
        except Exception as ex:
            p("}}rbUnable to pull approved nics from registry!}}xx")

        p("}}yn+ Pre-approved nics (can't remove)}}xx")
        p("}}mb* Nic manually added to approved list by admin}}xx\n")
        col1 = 45
        col2 = 30
        for item in NetworkDevices.NIC_LIST:
            m = "  "
            if item in manually_approved_nics:
                m = "}}mb* }}xx"
            else:
                m = "}}yn+ }}xx"
            ips = str(item[1])
            if ips == "-1":
                ips = "OK only if no IP (-1)"
            if ips == "*":
                ips = "Any IP Allowed (*)"

            p(m + item[0].ljust(col1) + ips.rjust(col2))
Ejemplo n.º 5
0
    def apply_firewall_policy():
        ret = True
        if RegistrySettings.is_debug():
            p("}}rbDEBUG MODE ON - Skipping apply firewall policy}}xx")
            return True

        policy_file_name = util.get_param(2, "firewall_config.wfw")

        # Should be in RC sub folder under the app
        app_folder = util.get_app_folder()
        rc_path = os.path.join(app_folder, "rc")
        policy_file_path = os.path.join(rc_path, policy_file_name)

        # netsh advfirewall import "%~dp0rc\firewall_config.wfw" 2>NUL 1<NUL

        cmd = "%SystemRoot%\\system32\\netsh advfirewall import \"" + policy_file_path + "\""
        returncode, output = ProcessManagement.run_cmd(cmd,
                                                       attempts=5,
                                                       require_return_code=0,
                                                       cmd_timeout=15)
        if returncode == -2:
            # Error running command?
            p("}}rbError - Unable to reset firewall back to defaults?}}xx\n" +
              output)
            ret = False

        return ret
Ejemplo n.º 6
0
    def reset_firewall_policy():
        ret = True
        if RegistrySettings.is_debug():
            p("}}rbDEBUG MODE ON - Skipping reset firewall policy}}xx")
            return True

        cmd = "%SystemRoot%\\system32\\netsh advfirewall reset"
        returncode, output = ProcessManagement.run_cmd(cmd,
                                                       attempts=5,
                                                       require_return_code=0,
                                                       cmd_timeout=15)
        if returncode == -2:
            # Error running command?
            p("}}rbError - Unable to reset firewall back to defaults?}}xx\n" +
              output)
            ret = False

        # rem reset settings to default
        # netsh advfirewall reset
        # rem turn on all profiles
        # rem netsh advfirewall set allprofiles state on
        # rem turn on logging
        # rem netsh advfirewall set currentprofile logging filename "c:\programdata\ope\tmp\log\pfirewall.log"

        return ret
Ejemplo n.º 7
0
    def is_time_to_upgrade():
        # How long has it been since we tried to upgrade?
        last_upgrade_time = RegistrySettings.get_reg_value(value_name="last_upgrade_time", default=0)
        curr_time = time.time()

        # Only check for upgrades every 5 minutes
        if curr_time - last_upgrade_time > 300:
            return True
        
        return False
Ejemplo n.º 8
0
    def is_time_to_sync():
        # How long has it been since we synced our time?
        last_time_sync = RegistrySettings.get_reg_value(
            value_name="last_ntp_sync", default=0)
        curr_time = time.time()

        # Only sync every 5 minutes
        if curr_time - last_time_sync > 300:
            return True

        return False
Ejemplo n.º 9
0
    def is_time_to_ping_smc():
        # How long has it been since we talked to the SMC server?
        last_smc_ping_time = RegistrySettings.get_reg_value(value_name="last_smc_ping_time", default=0)
        curr_time = time.time()

        # Only need a successful ping every ? minutes
        min_time = 30  # TODO - Turn ping time back up 300
        time_diff = curr_time - last_smc_ping_time
        if time_diff > min_time:
            return True
        
        p("}}ynNot time to ping yet - " + str(int(min_time - time_diff)) + " seconds left.}}xx", log_level=4)
        return False
Ejemplo n.º 10
0
    def ping_smc(smc_url=None):
        # See if we can bounce off the SMC server and get a response
        if smc_url is None:
            # Try and get from command line
            smc_url = util.get_param(2, None)
        if smc_url is None:
            # Nothing on command line? Get from registry
            smc_url = RegistrySettings.get_reg_value(value_name="smc_url", default="https://smc.ed")

        force = util.get_param(3, "")
        if force == "-f":
            force = True
        else:
            force = False

        if not force and not CredentialProcess.is_time_to_ping_smc():
            #p("}}gnNot time to ping smc, skipping...}}xx", log_level=4)
            return True
        
        RegistrySettings.set_reg_value(value_name="last_smc_ping_time", value=time.time())
        
        if not RestClient.ping_smc(smc_url):
            p("}}mnNot able to ping SMC " + smc_url + "}}xx", log_level=4)
            # Ok to return true - we just don't do more maintenance
            return True

        # We are connected, do maintenance

        # Check if time to sync time
        SystemTime.sync_time_w_ntp()

        # Check if time to sync stuff (lms app, folders, logs)...
        # TODO 

        # Check if time to auto upgrade
        CredentialProcess.start_upgrade_process()

        return True
Ejemplo n.º 11
0
    def apply_group_policy():
        ret = True

        if RegistrySettings.is_debug():
            p("}}rbDEBUG MODE ON - Skipping apply group policy}}xx")
            return True

        gpo_name = util.get_param(2, "gpo")

        # LGPO.exe is in the rc sub folder of the mgmt tool
        app_folder = util.get_app_folder()
        lgpo_path = os.path.join(app_folder, "rc")

        cmd = "lgpo.exe /g " + gpo_name

        returncode, output = ProcessManagement.run_cmd(cmd,
                                                       cwd=lgpo_path,
                                                       attempts=5,
                                                       require_return_code=0,
                                                       cmd_timeout=30)
        if returncode == -2:
            # Unable to restore gpo?
            p("}}rnERROR - Unable to set group policy!}}xx\n" + output)
            ret = False
            return ret

        # Force gpupdate
        cmd = "%SystemRoot%\\system32\\gpupdate /force"
        returncode, output = ProcessManagement.run_cmd(cmd,
                                                       attempts=5,
                                                       require_return_code=0,
                                                       cmd_timeout=30)
        if returncode == -2:
            # Error running command?
            p("}}rnERROR - Unable to set force gpupdate!}}xx\n" + output)
            ret = False

        return ret
Ejemplo n.º 12
0
    def trust_ope_certs():
        # Download the CA crt and trust it so we don't get warnings/errors when visiting
        # the sites
        p("}}gnGetting OPE Cert file...}}xx", log_level=3)
        # Get the smc_url - pull the ca.crt file from there
        smc_url = RegistrySettings.get_reg_value(value_name="smc_url", default="https://smc.ed")
        
        app_path = util.get_app_folder()
        rc_path = os.path.join(app_path, "rc")
        wget_path = os.path.join(rc_path, "wget.exe")
        certmgr_path = os.path.join(rc_path, "certmgr.exe")
        tmp_path = os.path.expandvars("%programdata%\\ope\\tmp")
        crt_file = os.path.join(tmp_path, "ca.crt")
        
        crt_url = smc_url + "/static/certs/ca.crt"

        cmd = "\"" + wget_path + "\" --connect-timeout=6 --tries=3 --no-check-certificate -O \"" + crt_file + "\" " + crt_url

        returncode, output = ProcessManagement.run_cmd(cmd, cwd=tmp_path,
            require_return_code=0)
        if returncode == -2:
            # Error running command?
            p("}}rbError - unable to pull ca.crt file!}}xx\n" + output)
            return False
        p("Ret: " + str(returncode) + " - " + output, log_level=5)
        
        # Try to trust the cert
        cmd = "\"" + certmgr_path + "\" -add \"" + crt_file + "\" -c -s -r localMachine root "
        returncode, output = ProcessManagement.run_cmd(cmd, cwd=tmp_path,
            require_return_code=0)
        if returncode == -2:
            # Error running command?
            p("}}rbError - Unable to add ca.crt file into trusted list!}}xx\n" + output)
            return False
        p("Ret: " + str(returncode) + " - " + output, log_level=5)
        
        return True
Ejemplo n.º 13
0
    def lock_machine():
        # Apply secuirty settings and re-enable student account so it can be 
        # handed back to a student
        ret = True

        # Get the current credentialed student
        student_user_name = CredentialProcess.get_credentialed_student()
        if student_user_name is None:
            p("}}rbNot Credentiled! - Unable to find credentialed student - not locking machine!}}xx")
            return False
        
        # Get the current admin user name
        admin_user_name = CredentialProcess.get_credentialed_admin()
        if admin_user_name is None:
            p("}}rbNot Credentiled! - Unable to find credentialed admin account - not locking machine!}}xx")
            return False

        # Log out the student
        if not UserAccounts.log_out_user(student_user_name):
            p("}}rbError - Unable to logout student: " + str(student_user_name) + "}}xx")
            return False

        # Apply firewall rules
        if not GroupPolicy.apply_firewall_policy():
            p("}}rbError - Could Not apply firewall policy!\nStudent Account NOT unlocked!}}xx")
            return False

        # Apply group policy
        if not GroupPolicy.apply_group_policy():
            p("}}rbError - Could Not apply group policy!\nStudent Account NOT unlocked!}}xx")
            return False
        
        # Lock down boot options
        if not FolderPermissions.lock_boot_settings():
            p("}}rbError - Could not lock boot settings!\nStudent Account NOT unlocked!}}xx")
            return False

        # Reset registry permissions
        if not RegistrySettings.set_default_ope_registry_permissions():
            p("}}rbError - Could not reset registry permissions!\nStudent Account NOT unlocked!}}xx")
            return False

        # Reset folder permissions
        if not FolderPermissions.set_default_ope_folder_permissions():
            p("}}rbError - Could not reset ope folder permissions!\nStudent Account NOT unlocked!}}xx")
            return False
        
        # Reset student users group memberships
        if not UserAccounts.set_default_groups_for_student(student_user_name):
            p("}}rbError - Could not reset default groups for student!\nStudent Account NOT unlocked!}}xx")
            return False
        
        # Reset admin users group memberships
        if not UserAccounts.set_default_groups_for_admin(admin_user_name):
            p("}}rbError - Could not reset default groups for the admin account!\nStudent Account NOT unlocked!}}xx")
            return False
        
        # Ensure the OPEService is running
        if not CredentialProcess.ensure_opeservice_running():
            p("}}rbError - Verify OPEService is running!\nStudent Account NOT unlocked!}}xx")
            return False

        # Enable student account
        if not UserAccounts.enable_account(student_user_name):
            p("}}rbError - Failed to enable student account: " + str(student_user_name) + "}}xx")
            return False

        return ret
Ejemplo n.º 14
0
    def remove_account_profile(user_name=None):
        # Remove the profile/files for the user
        if user_name is None:
            user_name = util.get_param(2, None)
        if user_name is None:
            p("}}enInvalid User name - not removing account profile!}}xx")
            return False

        # Log it out (if it is logged in)
        UserAccounts.log_out_user(user_name)

        # Get the SID for the user in question
        user_sid = ""
        try:
            parts = win32security.LookupAccountName(None, user_name)
            user_sid = win32security.ConvertSidToStringSid(parts[0])
        except Exception as ex:
            # Unable to find this user?
            p("}}rnError - Invalid User - can't remove profile!}}xx " +
              str(user_name))
            return False

        if user_sid == "":
            # User doesn't exist?
            p("}}rnInvalid User - can't remove profile!}}xx " + str(user_name))
            return False

        # We need more privileges to do this next part
        UserAccounts.elevate_process_privilege_to_backup_restore()

        # Make sure the registry hive is unloaded
        #p("Unloading " + user_sid)
        try:
            win32api.RegUnLoadKey(win32con.HKEY_USERS, user_sid)
        except Exception as ex:
            p("}}ynUnable to unload user registry - likely not currently loaded, moving on...}}xx",
              debug_level=4)

        try:
            win32profile.DeleteProfile(user_sid)
        except Exception as ex:
            p("}}ynUnable to remove profile folder - likely it doesn't exist.}}xx",
              debug_level=4)
        return True

        #See if a profile exists
        w = wmi.WMI()
        profiles = w.Win32_UserProfile(SID=user_sid)
        if len(profiles) < 1:
            p("}}ynNo profile found for this user, skipping remove!}}xx")
            return True

        profile_path = ""
        profile_loaded = False
        for profile in profiles:
            profile_path = profile.LocalPath
            profile_loaded = profile.Loaded
        profiles = None

        # We know it exists

        # Remove it from the registry list
        RegistrySettings.remove_key("HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\" + \
            "ProfileList\\" + user_sid)

        # Delete the folder/files
        try:
            shutil.rmtree(profile_path)
        except Exception as ex:
            p("}}rnError - Unable to remove the profile folder at " + profile_path + "}}xx\n" + \
                str(ex))
            return False

        return True
Ejemplo n.º 15
0
    def credential_input_verify_loop():
        # Loop until we quit or get good stuff

        # Return a list of values
        # student_full_name, laptop_admin_user, laptop_admin_password
        ret = []

        mgmt_version = CredentialProcess.get_mgmt_version()

        smc_url = RegistrySettings.get_reg_value(value_name="smc_url", default="https://smc.ed")
        canvas_url = ""
        canvas_access_token = ""
        student_user = RegistrySettings.get_reg_value(value_name="student_user")
        student_full_name = ""
        student_password = ""
        smc_admin_user = RegistrySettings.get_reg_value(app="OPEService", value_name="smc_admin_user", default="admin")
        smc_admin_password = ""

        laptop_admin_user = ""
        laptop_admin_password = ""

        loop_running = True
        while loop_running:
            p("\n}}gb Version: " + mgmt_version + "}}xx")
            
            p("""

}}mn======================================================================
}}mn| }}ybOPE Credential App                                                 }}mn|
}}mn| }}xxThis app will add student credentials to the computer and          }}mn|
}}mn| }}xxsecure the laptop for inmate use.                                  }}mn|
}}mn| }}yn(answer with quit to stop this tool)                               }}mn|
}}mn======================================================================}}xx

            """)

            # 4 - Ask for input (smc server, login, student name, etc...)
            p("}}ynEnter URL for SMC Server }}cn[enter for " + smc_url + "]:}}xx ", False)
            tmp = input()
            tmp = tmp.strip()
            if tmp.lower() == "quit":
                p("}}rnGot QUIT - exiting credential!}}xx")
                return None
            if tmp == "":
                tmp = smc_url
            smc_url = tmp
            # Make sure url has https or http in it
            if "https://" not in smc_url.lower() and "http://" not in smc_url.lower():
                smc_url = "https://" + smc_url

            p("}}ynPlease enter the ADMIN user name }}cn[enter for " + smc_admin_user + "]:}}xx ", False)
            tmp = input()
            tmp = tmp.strip()
            if tmp.lower() == "quit":
                p("}}rnGot QUIT - exiting credential!}}xx")
                return None
            if tmp == "":
                tmp = smc_admin_user
            smc_admin_user = tmp

            p("}}ynPlease enter ADMIN password }}cn[characters will not show]:}}xx", False)
            tmp = getpass.getpass(" ")
            if tmp.lower() == "quit":
                p("}}rnGot QUIT - exiting credential!}}xx")
                return None
            if tmp == "":
                p("}}rbA password is required.}}xx")
                continue
            smc_admin_password = tmp

            tmp = ""
            last_student_user_prompt = ""
            while tmp.strip() == "":
                if student_user != "":
                    last_student_user_prompt = " }}cn[enter for previous student " + student_user + "]"
                    # p("}}mb\t- Found previously credentialed user: }}xx" + str(last_student_user))
                p("}}ynPlease enter the username for the student" + last_student_user_prompt + ":}}xx ", False)
                tmp = input()
                if tmp.lower() == "quit":
                    p("}}rnGot QUIT - exiting credential!}}xx")
                    return None
                if tmp.strip() == "":
                    tmp = student_user
            student_user = tmp.strip()

            # - Bounce off SMC - verify_ope_account_in_smc
            try:
                result = RestClient.verify_ope_account_in_smc(student_user, smc_url, smc_admin_user, smc_admin_password)
                if result is None:
                    # Should show errors during the rest call, so none here
                    #p("}}rbUnable to validate student against SMC!}}xx")
                    # Jump to top of loop and try again
                    continue
                    #return False # sys.exit(-1)
            except Exception as ex:
                p("}}rbError - Unable to verify student in SMC}}xx\n" + str(ex))
                # Jump to top of loop and try again
                continue
            
            # If not None - result will be a tuple of information
            laptop_admin_user, student_full_name, smc_version = result
            
            # Verify that the info is correct
            txt = """
}}mn======================================================================
}}mn| }}gbFound Student - Continue?                                          }}mn|
}}mn| }}ynCredential Version:    }}cn<mgmt_version>}}mn|
}}mn| }}ynSMC URL:               }}cn<smc_url>}}mn|
}}mn| }}ynSMC Version:           }}cn<smc_version>}}mn|
}}mn| }}ynLaptop Admin User:     }}cn<admin_user>}}mn|
}}mn| }}ynStudent Username:      }}cn<student_user>}}mn|
}}mn| }}ynSystem Serial Number:  }}cn<bios_serial_number>}}mn|
}}mn| }}ynDisk Serial Number:    }}cn<disk_serial_number>}}mn|
}}mn======================================================================}}xx
            """
            col_size = 44
            txt = txt.replace("<mgmt_version>", mgmt_version.ljust(col_size))
            txt = txt.replace("<smc_url>", smc_url.ljust(col_size))
            txt = txt.replace("<smc_version>", smc_version.ljust(col_size))
            txt = txt.replace("<admin_user>", laptop_admin_user.ljust(col_size))
            txt = txt.replace("<admin_pass>", "******".ljust(col_size))
            student_text = student_user + " (" + student_full_name + ")"
            txt = txt.replace("<student_user>", student_text.ljust(col_size))
            txt = txt.replace("<bios_serial_number>", 
                CredentialProcess.COMPUTER_INFO['bios_serial_number'].ljust(col_size))
            txt = txt.replace("<disk_serial_number>", 
                CredentialProcess.COMPUTER_INFO['disk_boot_drive_serial_number'].ljust(col_size))

            p(txt)
            p("}}ybPress Y to continue: }}xx", False)
            tmp = input()
            tmp = tmp.strip().lower()
            if tmp != "y":
                p("}}cnCanceled - trying again....}}xx")
                continue

            # Show the warning regarding locking down the boot options
            p("""
}}mn======================================================================
}}mn| }}rb====================       WARNING!!!         ==================== }}mn|
}}mn| }}xxEnsure that the boot from USB or boot from SD card options in      }}mn|
}}mn| }}xxthe bios are disabled and that the admin password is set to a      }}mn|
}}mn| }}xxstrong random password.                                            }}mn|
}}mn======================================================================}}xx
            """)
            p("}}ybHave you locked down the BIOS? Press Y to continue: }}xx", False)
            tmp = input()
            tmp = tmp.strip().lower()
            if tmp != "y":
                p("}}cnCanceled - trying again....}}xx")
                continue

            # - Bounce off SMC - lms/credential_student.json/??
            result = None
            try:
                ex_info = dict()
                ex_info["logged_in_user"] = UserAccounts.get_current_user()
                ex_info["admin_user"] = laptop_admin_user
                ex_info["current_student"] = student_user
                ex_info["mgmt_version"] = mgmt_version
                
                ex_info.update(CredentialProcess.COMPUTER_INFO)

                result = RestClient.credential_student_in_smc(
                    student_user, smc_url, smc_admin_user, smc_admin_password,
                    dict(ex_info=ex_info))
                if result is None:
                    p("}}rbUnable to credential student via SMC!}}xx")
                    # Jump to top of loop and try again
                    continue
                    #return False # sys.exit(-1)
            except Exception as ex:
                p("}}rbError - Unable to credential student via SMC}}xx\n" + str(ex))
                # Jump to top of loop and try again
                continue
            
            (student_full_name, canvas_url, canvas_access_token,
            student_password, laptop_admin_password) = result
            loop_running = False

        ret = (student_user, student_full_name, student_password, laptop_admin_user,
            laptop_admin_password, canvas_access_token, canvas_url, smc_url)

        return ret
Ejemplo n.º 16
0
    def start_upgrade_process(branch=None, force_upgrade=None):
        ret = True

        if not CredentialProcess.is_time_to_upgrade():
            p("}}gnNot time to check for upgrades yet, skipping...}}xx", log_level=3)
            return True

        RegistrySettings.set_reg_value(value_name="last_upgrade_time", value=time.time())

        curr_branch = branch
        if curr_branch is None:
            # See if a parameter was provided
            curr_branch = util.get_param(2, None)
        
        # Force upgrade - even if versions match
        if force_upgrade is None:
            force_upgrade = util.get_param(3, "")
            if force_upgrade.lower() != "-f":
                force_upgrade = False
            else:
                force_upgrade = True
        
        # If branch is still empty, get it from the registry
        if curr_branch is None:
            curr_branch = RegistrySettings.get_reg_value(value_name="install_branch", default="master")

        # Start by grabbing any new stuff from the git server
        ret = ProcessManagement.git_pull_branch(curr_branch)
        if ret is False:
            # Not critical if this fails - apply whatever is present if it is
            # a different version number
            # return False
            p("}}ybWARNING - Unable to pull updates for git server!}}xx")
            pass
        
        # Save the current branch for next time
        RegistrySettings.set_reg_value(value_name="install_branch", value=curr_branch)

        # Check the mgmt.version files to see if we have a new version
        ope_laptop_binaries_path = os.path.expandvars("%programdata%\\ope\\tmp\\ope_laptop_binaries")
        # Get the path to the mgmt.version file
        git_version_path = os.path.join(ope_laptop_binaries_path, "Services", "mgmt", "mgmt.version")

        # Do we have a new version?
        curr_version = CredentialProcess.get_mgmt_version()
        git_version = CredentialProcess.get_mgmt_version(git_version_path)

        if git_version == "NO VERSION":
            # No version file found
            p("}}ynNo version file found in git repo, skipping upgrade!}}xx")
            return False
        
        if not CredentialProcess.is_version_newer(curr_version, git_version) and force_upgrade is not True:
            # Same version - no upgrade needed
            p("}}gnOPE Software up to date: " + str(git_version) + " not newer than " + str(curr_version) + " - (not upgrading)}}xx")
            return True

        # Version is different, prep for update
        forced = ""
        if force_upgrade:
            forced = "}}yb(upgrade forced)}}gn"
        p("}}gnFound new version " + forced + " - starting upgrade process: " + \
            curr_version + " --> " + git_version + "}}xx")
        
        # Lock user accounts
        if not UserAccounts.disable_student_accounts():
            p("}}rbERROR - Unable to disable student accounts prior to upgrade!}}xx")
            return False

        # Make sure students are logged out
        if not UserAccounts.log_out_all_students():
            p("}}rbERROR - Unable to log out student accounts prior to upgrade!}}xx")
            return False
        
        
        p("}}ynLaunching OPE Software Update process...}}xx")
        
        # run the upgrade_ope.cmd from the TMP rc folder!!!
        bat_path = os.path.join(ope_laptop_binaries_path, "Services\\mgmt\\rc\\upgrade_ope.cmd")
        # Add the redirect so we end up with a log file
        if not ProcessManagement.run_detatched_cmd(bat_path + " >> %programdata%\\ope\\tmp\\log\\upgrade.log 2>&1"):
            p("}}rbERROR - Unable to start upgrade process!}}xx")
            return False
        # Make sure to exit this app??
        #sys.exit(0)

        return ret
Ejemplo n.º 17
0
 def get_credentialed_admin():
     # Return the name of the current credentialed student or None if missing
     return RegistrySettings.get_reg_value(app="OPEService", value_name="admin_user", default=None)
Ejemplo n.º 18
0
    def approve_nic():
        # Get the params for the nic
        nic_name = util.get_param(2)
        nic_network = util.get_param(3)

        if nic_name == "" or nic_network == "":
            p("}}rbError - Invalid paramaters! try mgmt.exe help approve_nic for more information}}xx"
              )
            return False

        nic_id = None
        try:
            nic_id = int(nic_name)
        except:
            # Ok if this fails - trying to see if an ID was passed instead of a name
            pass

        if not nic_id is None:
            # Lookup the nic by ID
            iface = NetworkDevices.get_nic_by_interface_index(nic_id)
            if iface is None:
                # Unable to find an interface by this ID
                p("}}rbInvalid Interface ID! " + str(nic_id) + "}}xx")
                return False
            else:
                #nic_name = iface.Name
                # NOTE - Description will give us the driver name w/out the #2 after it
                nic_name = iface.Description

        # Strip off #? at the end of the name
        t_nic = nic_name
        removed_suffix = ""
        for i in range(1, 30):
            suffix = " #" + str(i)
            if suffix in t_nic:
                t_nic = t_nic.replace(suffix, "")
                removed_suffix = suffix
        if removed_suffix != "":
            p("}}ybNOTE - Stripped off " + removed_suffix +
              " from nic name\n - All instances of this nic approved with this network}}xx"
              )
            nic_name = t_nic

        p("}}gnApproving " + nic_name + " on netowrk " + nic_network,
          log_level=1)

        # Get the list of approved nics
        # Load the value from the registry
        try:
            approved_nics_json = RegistrySettings.get_reg_value(
                app="OPEService", value_name="approved_nics", default="[]")
            nic_list = json.loads(approved_nics_json)
            # Add this nic to the list
            nic_list.append((nic_name, nic_network))
            # Write this back to the registry
            approved_nics_json = json.dumps(nic_list)
            RegistrySettings.set_reg_value(app="OPEService",
                                           value_name="approved_nics",
                                           value=approved_nics_json)
        except Exception as ex:
            p("}}rbUnable to write approved nics to the registry!}}xx",
              log_level=1)
            return False

        # Force a reload of the device list
        NetworkDevices.init_device_list(refresh=True)

        return True
Ejemplo n.º 19
0
    def reload_settings():
        p("}}ybRunning reload_settings}}xx")
        # Reload settings for the service from the registry
        if OPEService._svc_instance is None:
            p("}}rbNo OPEService running? - NOT reloading settings!")
            return False

        p("}}mbReloading Settings}}xx", log_level=4)

        #### Grab settings from the registry

        if LOGGER is not None:
            # Grab log level
            value_name = "log_level"
            value = RegistrySettings.get_reg_value(app="OPEService",
                                                   value_name=value_name,
                                                   default=3,
                                                   value_type="REG_DWORD")
            # Set log_level through color/p - it passes things on to the logger
            old_val = get_log_level()
            set_log_level(value)
            if old_val != value:
                p("}}ybNew Setting " + value_name + \
                    ": " + str(value) + "}}xx", log_level=3)

        # Grab how often to run default permissions (registry and ope folder)
        value_name = "set_default_permissions_timer"
        value = RegistrySettings.get_reg_value(app="OPEService",
                                               value_name=value_name,
                                               default=3600,
                                               value_type="REG_DWORD")
        old_val = OPEService._COMMANDS_TO_RUN[
            "set_default_ope_folder_permissions"]["timer"]
        if old_val != value:
            p("}}ybNew Setting " + value_name + ": " + str(value) + "}}xx",
              log_level=3)
        OPEService._COMMANDS_TO_RUN["set_default_ope_folder_permissions"][
            "timer"] = value
        OPEService._COMMANDS_TO_RUN["set_default_ope_registry_permissions"][
            "timer"] = value

        # How often should we run reload_settings function?
        value_name = "reload_settings_timer"
        value = RegistrySettings.get_reg_value(app="OPEService",
                                               value_name=value_name,
                                               default=30,
                                               value_type="REG_DWORD")
        old_val = OPEService._COMMANDS_TO_RUN["reload_settings"]["timer"]
        if old_val != value:
            p("}}ybNew Setting " + value_name + ": " + str(value) + "}}xx",
              log_level=3)
        OPEService._COMMANDS_TO_RUN["reload_settings"]["timer"] = value

        # How often should we run scan_nics
        value_name = "scan_nics_timer"
        value = RegistrySettings.get_reg_value(app="OPEService",
                                               value_name=value_name,
                                               default=60,
                                               value_type="REG_DWORD")
        old_val = OPEService._COMMANDS_TO_RUN["scan_nics"]["timer"]
        if old_val != value:
            p("}}ybNew Setting " + value_name + ": " + str(value) + "}}xx",
              log_level=3)
        OPEService._COMMANDS_TO_RUN["scan_nics"]["timer"] = value

        # How often should we run screen_shot
        value_name = "screen_shot_timer"
        value = RegistrySettings.get_reg_value(app="OPEService",
                                               value_name=value_name,
                                               default="30-300",
                                               value_type="REG_SZ")
        old_val = OPEService._COMMANDS_TO_RUN["screen_shot"]["timer"]
        if old_val != value:
            p("}}ybNew Setting " + value_name + ": " + str(value) + "}}xx",
              log_level=3)
        OPEService._COMMANDS_TO_RUN["screen_shot"]["timer"] = value

        return True
Ejemplo n.º 20
0
    def credential_laptop():
        
        # Are we running as admin w UAC??
        if not UserAccounts.is_uac_admin():
            p("}}rbNot Admin in UAC mode! - UAC Is required for credential process.}}xx")
            return False
        
        # Get computer info
        CredentialProcess.COMPUTER_INFO = Computer.get_machine_info(print_info=False)

        # Are we in a domain?
        if CredentialProcess.COMPUTER_INFO["cs_part_of_domain"] is True:
            p("}}rbSystem is doing to an Active Directory Domain - NOT SUPPORTED!\n" +
                "Please remove this from the domain as it might interfere with security settings.}}xx")
            return False
        
        # Are we using a proper edition win 10? (Home not supported, ed, pro, enterprise ok?)
        # OK - win 10 - pro, ed, enterprise
        # NOT OK - non win 10, win 10 home
        is_win10 = False
        is_win10_home = True
        os_caption = CredentialProcess.COMPUTER_INFO["os_caption"]
        if "Microsoft Windows 10" in os_caption:
            is_win10 = True
        if "Enterprise" in os_caption or "Professional" in os_caption or "Education" in os_caption:
            is_win10_home = False
        
        if is_win10 is not True:
            p("}}rbNOT RUNNING ON WINDOWS 10!!!\nThis software is designed to work win windows 10 ONLY!\n (Enterprise, Professional, or Education OK, Home edition NOT supported)}}xx")
            return False
        if is_win10_home is True:
            p("}}rbWIN10 HOME EDITION DETECTED!\nThis software is designed to work win windows 10 ONLY!\n (Enterprise, Professional, or Education OK, Home edition NOT supported)}}xx")
            return False

        # Disable guest account
        p("}}gnDisabling guest account}}xx", debug_level=2)
        UserAccounts.disable_guest_account()

        # Make sure folder exist and have proper permissions
        if not FolderPermissions.set_default_ope_folder_permissions():
            p("}}rbERROR - Unable to ensure folders are present and permissions are setup properly!}}xx")
            return False

        CredentialProcess.trust_ope_certs()

        # Disable all student accounts
        UserAccounts.disable_student_accounts()

        result = CredentialProcess.credential_input_verify_loop()
        if result is None:
            # Unable to verify?
            return False
        (student_user, student_name, student_password, admin_user, admin_password,
        canvas_access_token, canvas_url, smc_url) = result
        
        # - Create local student account
        p("}}gnCreating local student windows account...}}xx")
        if not UserAccounts.create_local_student_account(student_user, student_name, student_password):
            p("}}rbError setting up OPE Student Account}}xx\n " + str(ex))
            return False

        # - Setup admin user
        p("}}gnCreating local admin windows account...}}xx")
        try:
            UserAccounts.create_local_admin_account(admin_user, "OPE Laptop Admin", admin_password)
        except Exception as ex:
            p("}}rbError setting up OPE Laptop Admin Account}}xx\n " + str(ex))
        admin_password = ""

        # Store the credential information
        if not RegistrySettings.store_credential_info(canvas_access_token, canvas_url, smc_url,
            student_user, student_name, admin_user):
            p("}}rbError saving registry info!}}xx")
            return False
        
        # Create desktop shortcut
        #p("\n}}gnSetting up LMS App...}}xx")
        Computer.create_win_shortcut(
            lnk_path = "c:\\users\\public\\desktop\\OPE LMS.lnk",
            ico_path = "%programdata%\\ope\\Services\\lms\\logo_icon.ico",
            target_path = "%programdata%\\ope\\Services\\lms\\ope_lms.exe",
            description = "Offline LMS app for Open Prison Education project"
        )

        p("}}gnLocking machine - applying security settings...}}xx")
        if not CredentialProcess.lock_machine():
            p("}}rbERROR - Unable to lock machine after credentail!}}xx")
            return False
        
        return True
Ejemplo n.º 21
0
from mgmt_UserAccounts import UserAccounts
from mgmt_FolderPermissions import FolderPermissions
from mgmt_ScreenShot import ScreenShot
from mgmt_RegistrySettings import RegistrySettings
from mgmt_NetworkDevices import NetworkDevices
from mgmt_CredentialProcess import CredentialProcess
from mgmt_SystemTime import SystemTime
from mgmt_GroupPolicy import GroupPolicy
from mgmt_ProcessManagement import ProcessManagement
from mgmt_Computer import Computer
from mgmt_COMPorts import COMPorts

# Get the logging level
value_name = "log_level"
value = RegistrySettings.get_reg_value(app="OPEService",
                                       value_name=value_name,
                                       default=3,
                                       value_type="REG_DWORD")
set_log_level(value)

# Pre-declare - fill out later
global valid_commands
valid_commands = dict()


def RunAsTraceCollector():
    import sys
    try:
        import win32api
        win32api.SetConsoleTitle("Python Trace Collector")
    except:
        pass  # Oh well!
Ejemplo n.º 22
0
 def get_credentialed_student():
     # Return the name of the current credentialed student or None if missing
     return RegistrySettings.get_reg_value(value_name="student_user", default=None)