def set_registry_permissions(student_user): reg = registry.registry(r"HKLM\Software\OPE") with reg.security() as s: # Break inheritance causes things to reapply properly s.break_inheritance(copy_first=True) if student_user is not None: s.dacl.append( (student_user, registry.Registry.ACCESS["Q"], "ALLOW")) s.dacl.append((accounts.me(), registry.Registry.ACCESS["F"], "ALLOW")) # s.dacl.dump() reg = registry.registry(r"HKLM\Software\OPE\OPELMS") with reg.security() as s: # Break inheritance causes things to reapply properly s.break_inheritance(copy_first=True) if student_user is not None: s.dacl.append( (student_user, registry.Registry.ACCESS["Q"], "ALLOW")) s.dacl.append((accounts.me(), registry.Registry.ACCESS["F"], "ALLOW")) # s.dacl.dump() reg = registry.registry(r"HKLM\Software\OPE\OPELMS\student") with reg.security() as s: # Break inheritance causes things to reapply properly s.break_inheritance(copy_first=True) if student_user is not None: s.dacl.append( (student_user, registry.Registry.ACCESS["W"], "ALLOW")) s.dacl.append((accounts.me(), registry.Registry.ACCESS["F"], "ALLOW"))
def log_event(source, type="error", message=None, data=None, id=0, category=0, principal=core.UNSET): """Convenience function to log an event against an existing source. :param source: anything accepted by :func:`event_source` :param type: an :data:`EVENTLOG_TYPE` :param message: a string or list of strings :param data: a bytestring :param id: a number corresponding to the event message :param category: a number relevant to the event source :param principal: anything which :func:`accounts.principal` accepts [logged-on user] """ type = EVENTLOG_TYPE.constant(type) principal = accounts.me( ) if principal is core.UNSET else accounts.principal(principal) if isinstance(message, basestring): message = [message] message = message or [] with event_source(source) as hLog: wrapped(win32evtlog.ReportEvent, hLog, type, category, id, principal.pyobject(), message, data)
def log_event(source, type="error", message=None, data=None, id=0, category=0, principal=core.UNSET): """Convenience function to log an event against an existing source. :param source: anything accepted by :func:`event_source` :param type: an :data:`EVENTLOG_TYPE` :param message: a string or list of strings :param data: a bytestring :param id: a number corresponding to the event message :param category: a number relevant to the event source :param principal: anything which :func:`accounts.principal` accepts [logged-on user] """ type = EVENTLOG_TYPE.constant(type) principal = accounts.me() if principal is core.UNSET else accounts.principal(principal) if isinstance(message, basestring): message = [message] message = message or [] with event_source(source) as hLog: wrapped( win32evtlog.ReportEvent, hLog, type, category, id, principal.pyobject(), message, data )
def get_reg_key(key_str, user_name=None): reg = registry.registry(key_str) with reg.security() as s: # Break inheritance causes things to reapply properly s.break_inheritance(copy_first=True) if user_name is not None: s.dacl.append((user_name, "Q", "ALLOW")) s.dacl.append((accounts.me(), "F", "ALLOW")) # s.dacl.dump() return reg
def create_reg_key(key_str, user_name=None): reg = registry.create(key_str) # Add the user to the key with permissions if user_name is not None: with reg.security() as s: # Break inheritance causes things to reapply properly s.break_inheritance(copy_first=True) s.dacl.append((user_name, "W", "ALLOW")) s.dacl.append((accounts.me(), "F", "ALLOW")) # s.dacl.dump() return reg
from __future__ import with_statement from winsys import registry, accounts new_key = registry.copy (r"HKLM\Software\Python", r"HKLM\Software\WinsysPython") try: with new_key.security () as sec: sec.break_inheritance (copy_first=False) sec.dacl += [ ("Users", "R", "ALLOW"), (accounts.me (), "F", "ALLOW"), ] sec.dump () finally: print "***" new_key.security ().dump ()
import os, sys import functools import operator import win32security import ntsecuritycon import tempfile from winsys._compat import unittest from winsys.tests import utils as testutils from winsys import core, accounts from winsys._security import _aces everyone, _, _ = win32security.LookupAccountName(None, "Everyone") me = accounts.me() administrators = accounts.principal("Administrators") @unittest.skipUnless(testutils.i_am_admin(), "These tests must be run as Administrator") class TestAces(unittest.TestCase): def setUp(self): testutils.change_priv(win32security.SE_SECURITY_NAME, True) self.filehandle, self.filename = tempfile.mkstemp() dacl = win32security.ACL() dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, 0, ntsecuritycon.FILE_READ_DATA, everyone) sacl = win32security.ACL() sacl.AddAuditAccessAce(win32security.ACL_REVISION_DS, ntsecuritycon.FILE_READ_DATA, everyone, 1, 1)
import os, sys import operator from nose.tools import * import utils from winsys import core, accounts from winsys._security import _aces import win32security import ntsecuritycon import tempfile everyone, _, _ = win32security.LookupAccountName (None, "Everyone") me = accounts.me () administrators = accounts.principal ("Administrators") filehandle = filename = None def setup (): utils.change_priv (win32security.SE_SECURITY_NAME, True) global filehandle, filename filehandle, filename = tempfile.mkstemp () print filename dacl = win32security.ACL () dacl.AddAccessAllowedAceEx (win32security.ACL_REVISION_DS, 0, ntsecuritycon.FILE_READ_DATA, everyone) sacl = win32security.ACL () sacl.AddAuditAccessAce (win32security.ACL_REVISION_DS, ntsecuritycon.FILE_READ_DATA, everyone, 1, 1) win32security.SetNamedSecurityInfo ( filename, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION | win32security.SACL_SECURITY_INFORMATION, None, None, dacl, sacl )
def main(): global APP_FOLDER if win_util.is_admin() is not True: p("}}rbApp must be run as Admin user with elevated (UAC) privileges!!!}}xx" ) return False global admin_user, admin_pass, smc_url, student_user, server_name, home_root canvas_access_token = "" canvas_url = "https://canvas.ed" win_util.disable_guest_account() # win_util.test_reg() # See if we already have a user credentialed. last_student_user = win_util.get_credentialed_student_name( default_value="") last_smc_url = win_util.get_last_smc_url(default_value="https://smc.ed") last_admin_user = win_util.get_last_admin_user(default_value="admin") # p("LAST STUDENT USER: "******"}}ynEnter URL for SMC Server }}cn[enter for " + last_smc_url + "]:}}xx ", False) tmp = input() tmp = tmp.strip() if tmp == "": tmp = last_smc_url smc_url = tmp p( "}}ynPlease enter the ADMIN user name }}cn[enter for " + last_admin_user + "]:}}xx ", False) tmp = input() tmp = tmp.strip() if tmp == "": tmp = last_admin_user admin_user = tmp p("}}ynPlease enter ADMIN password }}cn[characters will not show]:}}xx", False) tmp = getpass.getpass(" ") if tmp == "": p("}}rbA password is required.}}xx") return False admin_pass = tmp tmp = "" last_student_user_prompt = "" while tmp.strip() == "": if last_student_user != "": last_student_user_prompt = " }}cn[enter for previous student " + last_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.strip() == "": tmp = last_student_user student_user = tmp.strip() result = verify_ope_account_in_smc(student_user, smc_url, admin_user, admin_pass) if result is None: p("}}rbERR - User doesn't exist in smc??}}xx") sys.exit(-1) laptop_admin_user, laptop_admin_password, student_full_name = result if laptop_admin_user == "" or laptop_admin_password == "": p("}}rbERR - Please set the laptop admin credentials in the SMC before continuing (Admin -> Configure App -> Laptop Admin Credentials) }}xx" ) sys.exit(-1) if student_full_name == "": p("}}rbERR - Unable to find student user in the SMC? Make sure it is imported.}}xx" ) sys.exit(-1) # Show confirm info txt = """ }}mn====================================================================== }}mn| }}ybConfirm Credential Parameters }}mn| }}mn| }}ynSMC URL: }}cn<smc_url>}}mn| }}mn| }}ynAdmin User: }}cn<admin_user>}}mn| }}mn| }}ynAdmin Password: }}cn<admin_pass>}}mn| }}mn| }}ynStudent Username: }}cn<student_user>}}mn| }}mn======================================================================}}xx """ txt = txt.replace("<smc_url>", smc_url.ljust(47)) txt = txt.replace("<admin_user>", admin_user.ljust(47)) txt = txt.replace("<admin_pass>", "******".ljust(47)) student_text = student_user + " (" + student_full_name + ")" txt = txt.replace("<student_user>", student_text.ljust(47)) p(txt) p("}}ybPress Y to continue: }}xx", False) tmp = input() tmp = tmp.strip().lower() if tmp != "y": p("}}cnCanceled / Not credentialing....}}xx") return False api_url = smc_url if not api_url.endswith("/"): api_url += "/" key = base64.b64encode(str(admin_user + ':' + admin_pass).encode()).decode() headers = {'Authorization': 'Basic ' + key} # password_manager = urllib3.HTTPPasswordMgrWithDefaultRealm() # password_manager.add_password(None, api_url, admin_user, admin_pass) # handler = urllib3.HTTPBasicAuthHandler(password_manager) # opener = urllib3.build_opener(handler) # ssl_context = ssl._create_unverified_context() p("\n}}gnStarting Credential Process...}}xx\n") url = api_url + "lms/credential_student.json/" + student_user try: resp = requests.get( url, headers=headers, verify=False) # urllib3.Request(url, None, headers) except requests.ConnectionError as error_message: p("}}rbConnection error trying to connect to SMC server}}xx") p("}}yn" + str(error_message) + "}}xx") return False if resp is None: # Unable to get a response? p("}}rbInvalid response from SMC server!}}xx") return False if resp.status_code == requests.codes.forbidden: p("}}rbError authenticating with SMC server - check password and try again.}}xx" ) return False try: resp.raise_for_status() except Exception as error_message: p("}}rbGeneral error trying to connect to SMC server}}xx") p("}}yn" + str(error_message) + "}}xx") return False smc_response = None try: smc_response = resp.json() except ValueError as error_message: p("}}rbInvalid JSON response from SMC}}xx") p("}}yn" + str(error_message) + "}}xx") return False except Exception as error_message: p("}}rbUNKNOWN ERROR}}xx") p("}}yn" + str(error_message) + "}}xx") return False # Interpret response from SMC try: # p("RESP: " + str(smc_response)) msg = smc_response["msg"] if msg == "Invalid User!": p("\n}}rbInvalid User!}}xx") p("}}mnUser doesn't exit in system, please import this student in the SMC first!}}xx" ) return False if msg == "No username specified!": p("\n}}rbInvalid User!}}xx") p("}}mnNo user with this name exists, please import this student in the SMC first!}}xx" ) return False if "unable to connect to canvas db" in msg: p("\n}}rbSMC Unable to connect to Canvas DB - make sure canvas app is running and\n" + "the SMC tool is configured to talk to Canvas}}xx") p("}}yn" + str(msg) + "}}xx") return False if "Unable to find user in canvas:" in msg: p("\n}}rbInvalid User!}}xx") p("}}mnUser exists in SMC but not in Canvas, please rerun import this student in the SMC to correct the issue!}}xx" ) full_name = smc_response["full_name"] canvas_access_token = smc_response["key"] hash = smc_response["hash"] student_full_name = str(smc_response["full_name"]) canvas_url = str(smc_response['canvas_url']) except Exception as error_message: p("}}rbUnable to interpret response from SMC - no msg parameter returned}}xx" ) p("}}mn" + str(ex) + "}}xx") return False #print(json.dumps(smc_response)) #p("Response: " + canvas_access_token + " ---- " + str(hash)) #print(canvas_access_token) #print(hash) pw = win_util.decrypt(hash, canvas_access_token) p("}}gnCreating local student windows account...") win_util.create_local_student_account(student_user, student_full_name, pw) p("}}gnCreating local admin windows account...") try: win_util.create_local_admin_account(laptop_admin_user, "OPE Laptop Admin", laptop_admin_password) except Exception as ex: p("}}rbError setting up OPE Laptop Admin Account " + str(ex)) laptop_admin_password = "" # Store the access token in the registry where the LMS app can pick it up p("}}gn\nSaving canvas credentials for student...") # key = win_util.create_reg_key(r"HKLM\Software\OPE\OPELMS", student_user) # key = win_util.create_reg_key(r"HKLM\Software\OPE\OPELMS\student") # key.canvas_access_token = canvas_access_token # key.user_name = student_user win_util.set_registry_value('canvas_access_token', canvas_access_token) win_util.set_registry_value('user_name', student_user) win_util.set_registry_value('canvas_url', canvas_url) win_util.set_registry_value('smc_url', smc_url) win_util.set_registry_value('admin_user', admin_user) win_util.set_registry_permissions(student_user) # p("}}gnCanvas access granted for student.}}xx") p("\n}}gnSetting up LMS App...}}xx") # Create shortcut lnk_path = "c:\\users\\public\\desktop\\OPE LMS.lnk" # Modify so that desktop shortcut point to where the app really is, not the hard coded dir # exe_path = "c:\\programdata\\ope\\ope_laptop_binaries\\lms\\ope_lms.exe" LMS_FOLDER = os.path.join(os.path.dirname(APP_FOLDER), "lms") exe_path = os.path.join(LMS_FOLDER, "ope_lms.exe") # ico_path = "c:\\programdata\\ope\\ope_laptop_binaries\\lms\\logo_icon.ico" ico_path = os.path.join(LMS_FOLDER, "logo_icon.ico") shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) shortcut.SetPath(exe_path) shortcut.SetDescription( "Offline LMS app for Open Prison Education project") shortcut.SetIconLocation(ico_path, 0) persist_file = shortcut.QueryInterface(pythoncom.IID_IPersistFile) persist_file.Save(lnk_path, 0) # If current user is not the laptop_admin_user - ask if we should disable this account? me = accounts.me() if laptop_admin_user != me.name: p("}}rb!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" ) p("}}rbYou are currently logged in as " + str(me.name) + " but the Laptop Admin user is " + str(laptop_admin_user) + ".") p("}}rb---> Please make sure to set a password and/or disable accounts that aren't needed on this laptop.}}xx" ) p("}}rb!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" ) countdown = 8 while countdown > 0: p("\r}}mb" + str(countdown) + "}}xx", end="") time.sleep(1) countdown -= 1 p("\n}}gbCanvas token saved.}}xx") p("") p("}}zn --------------> !!!!!CONFIRM BIOS!!!!! <-------------- }}xx" ) p("}}zn --------------> VERIFY BIOS PASSWORD/SETTINGS BEFORE HANDING OUT LAPTOP! <-------------- }}xx" ) countdown = 8 while countdown > 0: p("\r}}mb" + str(countdown) + "}}xx", end="") time.sleep(1) countdown -= 1 return True
import uuid from winsys import accounts, security, fs username = filename = str(uuid.uuid1())[:8] user = accounts.User.create(username, "password") f = fs.file(filename) assert(not f) assert accounts.me() != user try: with user: assert accounts.me() == user f.touch() assert f.security().owner == user f.delete() finally: user.delete()
from winsys import accounts print accounts.me()
from __future__ import with_statement from winsys import registry, accounts new_key = registry.copy(r"HKLM\Software\Python", r"HKLM\Software\WinsysPython") try: with new_key.security() as sec: sec.break_inheritance(copy_first=False) sec.dacl += [ ("Users", "R", "ALLOW"), (accounts.me(), "F", "ALLOW"), ] sec.dump() finally: print "***" new_key.security().dump()