Ejemplo n.º 1
0
def main():
    # sleep(5) #added a sleep to avoid "Connection refused" or "404" errors
    parser = argparse.ArgumentParser()
    parser.add_argument('dir', help='the directory of the example')
    args = parser.parse_args()

    # locate config file
    base_path = os.path.abspath(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), "..",
                     "examples", args.dir, "config"))
    config_file = os.path.join(base_path, "sdx_global.cfg")
    # locate the monitor's flows configuration file
    access_control_flows_file = os.path.join(base_path,
                                             "access_control_flows.cfg")
    config = Config(config_file)

    if os.path.exists(access_control_flows_file):
        with file(access_control_flows_file) as f:
            flows = json.load(f)
    else:
        flows = {"access_control_flows": {}}

    # start umbrella fabric manager
    logger = util.log.getLogger('access-control')
    logger.info('init')

    # Keep it for now just in case we decide to send messages to Refmon
    logger.info('REFMON client: ' + str(config.refmon["IP"]) + ' ' +
                str(config.refmon["Port"]))
    client = RefMonClient(config.refmon["IP"], config.refmon["Port"],
                          config.refmon["key"])

    controller = AccessControl(config, flows, client, logger)
    logger.info('start')
    controller.start()
Ejemplo n.º 2
0
def main():
    """Main function for the project.
    """

    # Call CreateConfig class
    cc = CreateConfig()
    # Read config.ini file
    config = cc.read()
    cd_port = config["Card_Reader"]["Port"]
    cd_id = config["Card_Reader"]["ID"]
    io_port = config["Controller"]["Port"]
    io_id = config["Controller"]["ID"]

    # Create card reader one
    card_reader = ACT230(cd_port, cd_id)

    # Call class Tokens and get_tokens method
    tokens = Tokens()

    # Create controller
    controller = IOController(io_port, io_id)

    # Call AccessControl class
    ac = AccessControl(card_reader, tokens, controller)

    #call update method in a while cycle to check for token input non-stop
    while (1):
        ac.update()
Ejemplo n.º 3
0
def main():
    # sleep(5) #added a sleep to avoid "Connection refused" or "404" errors
    parser = argparse.ArgumentParser()
    parser.add_argument('dir', help='the directory of the example')
    args = parser.parse_args()

    # locate config file
    base_path = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)),"..","examples",args.dir,"config"))
    config_file = os.path.join(base_path, "sdx_global.cfg")
    # locate the monitor's flows configuration file
    access_control_flows_file = os.path.join(base_path, "access_control_flows.cfg")
    config = Config(config_file)
    
    if os.path.exists(access_control_flows_file):
        with file(access_control_flows_file) as f:
            flows = json.load(f)
    else:
        flows={"access_control_flows" : {}}

    # start umbrella fabric manager
    logger = util.log.getLogger('access-control')
    logger.info('init')

    # Keep it for now just in case we decide to send messages to Refmon
    logger.info('REFMON client: ' + str(config.refmon["IP"]) + ' ' + str(config.refmon["Port"]))
    client = RefMonClient(config.refmon["IP"], config.refmon["Port"], config.refmon["key"])

    controller = AccessControl(config, flows, client, logger)
    logger.info('start')
    controller.start()
Ejemplo n.º 4
0
  def test_rules_only_(self):
    config_rules_only = """
      [[rules]]
      allow = [
        ['user1', 'res_a', 'GET'],
      ]
      deny = [
        ['user1', 'res_a', 'POST'],
      ]
    """
    ac = AccessControl(config_rules_only)

    is_allowed, reason = ac.check('user1', 'res_a', 'GET')
    self.assertEqual(is_allowed, True)
    self.assertEqual(reason, '[rules.1] "user1" is allowed to do "GET" on "res_a"')

    is_allowed, reason = ac.check('user1', 'res_a', 'POST')
    self.assertEqual(is_allowed, False)
    self.assertEqual(reason, '[rules.1] "user1" is not allowed to do "POST" on "res_a"')
Ejemplo n.º 5
0
def main():
    """Main function for the project.
    """

    # Create card reader one
    card_reader = ACT230("COM3")

    # Call class Tokens and get_database method
    tokens = Tokens()
    tbase = tokens.get_database()

    # Create controller
    controller = IOController()

    # Call AccessControl class
    ac = AccessControl(card_reader, tbase, controller)

    #call update method in a while cycle to check for token input non-stop
    while (1):
        ac.update()
Ejemplo n.º 6
0
    def check_init(self, sas_if, sas_api, config=None, logger=print) -> bool:
        final_ret = True
        with self.__lock:
            if self.__init:
                return True

            self.__sas_if = sas_if
            self.__sas_api = sas_api

            self.__config = config if config is not None else self.__sas_api.config(
            )
            self.__logger = logger

            self.__sas_terminal = SasTerminal(self.__sas_if, self.__sas_api)
            self.__user_manager = UserManager()
            self.__access_control = AccessControl()

            ret = self.__init_offline_analysis_result()
            final_ret = ret and final_ret

            self.__init = final_ret
        return final_ret
Ejemplo n.º 7
0
def main():
    # Relay GPIO Board Pin
    RELAY_PIN = 37

    # Setup relay
    relay = Relay(RELAY_PIN)

    # Setup Databases
    credentials = []
    with open("/home/pi/fecoteme_access_control/dbcredentials.txt") as f:
        for line in f:
            credentials.append(line.split())

    # Read-Only Access Subscription Database
    accessDB = Database(*credentials[0])
    accessDB.connect()

    # Write-Only Movements Register Database (Handled by daemon)
    movQueue = multiprocessing.JoinableQueue(False)
    movementsDB_Handler = multiprocessing.Process(target=mov_write_db_handle,
                                      args=(credentials[1], movQueue))
    movementsDB_Handler.daemon = True
    movementsDB_Handler.start()

    # Setup Access Control System
    accessControl = AccessControl(accessDB, movQueue)

    # Set Barscanners Callbacks
    barscanner_cb = functools.partial(barscanner_handle,
                                       relay=relay,
                                       access_ctl=accessControl)
    # Setup Barscanners
    barscanner0 = Barscanner('/dev/barscanner0', "in", barscanner_cb)
    barscanner1 = Barscanner('/dev/barscanner1', "out", barscanner_cb)

    barscanners = {bs.device.fd: bs for bs in [barscanner0,barscanner1]}
    devices = {bs.device.fd: bs.device for bs in [barscanner0,barscanner1]}

    try:
        while True:
            r, w, x = select(devices, [], [])
            for fd in r:
                barscanners[fd].read_code_handler()
    finally:
        movQueue.join(10)  # Wait for all DB transactions to complete
Ejemplo n.º 8
0
 def test_first_match_deny_(self):
   ac = AccessControl(config_first_match)
   is_allowed, reason = ac.check('user3', 'part_c', 'PUT')
   self.assertEqual(is_allowed, False)
   self.assertEqual(reason, '[rules.r2] "reader" is not allowed to do "PUT" on "res2"')
Ejemplo n.º 9
0
 def test_all_allow_allow_(self):
   ac = AccessControl(config_all_allow)
   is_allowed, reason = ac.check('user1', 'part_a', 'PUT')
   self.assertEqual(is_allowed, True)
   self.assertEqual(reason, 'All matched rules allowed')
Ejemplo n.º 10
0
from employee import Employee
from access_control import AccessControl

EMPLOYEES = {
    1: Employee(1, 'Bob', '4 Jul 1994', 80000.00),
    2: Employee(2, 'Carol', '28 May 1992', 85000.00),
    3: Employee(3, 'Ted', '18 Feb 1988', 55000.00),
    4: Employee(4, 'Alice', '25 Nov 1987', 40000.00),
    101: Employee(101, 'Morgan the Manager', '14 Mar 1975', 100000.00)
}

ACCESSCONTROLS = {101: AccessControl(101, True)}
Ejemplo n.º 11
0
from employee import Employee
from access_control import AccessControl

EMPLOYEES = {
    1: Employee(1, 'Bob', '4 Jul 1994', 80000.00),
    2: Employee(2, 'Carol', '28 May 1992', 85000.00),
    3: Employee(3, 'Ted', '18 Feb 1988', 55000.00),
    4: Employee(4, 'Alice', '25 Nov 1987', 40000.00),
    101: Employee(101, 'Morgan the Manager', '14 Mar 1975', 100000.00)
}

ACCESSCONTROL = {
    101: AccessControl(101, True)
}
Ejemplo n.º 12
0
    # e.g. /admin/org1/auth
    return app.session_interface.tenant_path_prefix().rstrip(
        "/") + "/" + AUTH_PATH.lstrip("/")


# create controllers (including their routes)
UsersController(app, handler)
GroupsController(app, handler)
RolesController(app, handler)
ResourcesController(app, handler)
PermissionsController(app, handler)
if app.config.get('QWC_GROUP_REGISTRATION_ENABLED'):
    RegistrableGroupsController(app, handler)
    RegistrationRequestsController(app, handler, i18n, mail)

access_control = AccessControl(handler, app.logger)

plugins_loaded = False


@app.before_first_request
def load_plugins():
    global plugins_loaded
    if not plugins_loaded:
        plugins_loaded = True
        app.config['PLUGINS'] = []
        for plugin in handler().config().get("plugins", []):
            app.logger.info("Loading plugin '%s'" % plugin)
            try:
                mod = importlib.import_module("plugins." + plugin)
                mod.load_plugin(app, handler)
Ejemplo n.º 13
0
            break

    return lookup


# create controllers (including their routes)
UsersController(app, config_models)
GroupsController(app, config_models)
RolesController(app, config_models)
ResourcesController(app, config_models)
PermissionsController(app, config_models)
if app.config.get('QWC_GROUP_REGISTRATION_ENABLED'):
    RegistrableGroupsController(app, config_models)
    RegistrationRequestsController(app, config_models, i18n, mail)

acccess_control = AccessControl(config_models, app.logger)


@app.before_request
@jwt_optional
def assert_admin_role():
    identity = get_jwt_identity()
    app.logger.debug("Access with identity %s" % identity)
    if not acccess_control.is_admin(identity):
        app.logger.info("Access denied for user %s" % identity)
        if app.debug:
            pass  # Allow access in debug mode
        else:
            if identity:
                # Already logged in, but not with admin role
                return redirect('/auth/logout?url=%s' % request.url)
Ejemplo n.º 14
0
        res_pin = self.ipfs_http.pin_add(res_add['Hash'])
        print(res_pin)
        res_publish = self.ipfs_http.publish(res_add['Hash'])
        print(" Published: ") #Il dove viene pubblicato è importante per scaricare il file
        print(res_publish)
        self.lock.release()




# SmartContractINFOS
providerURL = "wss://rinkeby.infura.io/_ws"
smart_contract_address = "0xC1D3f319947bD3C79D8F63B3aE4cB3126181ED0c"

ipfs_http = IPFS_http('http://127.0.0.1:5001/api/v0/')
access_control = AccessControl.Factory(providerURL, smart_contract_address, contract_abi.abi)

layer = Layer(ipfs_http, access_control, 50, pin=True, log_path='./logs/')
#Abbiamo gli event, ed ok.
#La lista degli accessi invece, deve poter essere aggiornabile
#ipfs anche sul cellulare? Pinnano i loro che gli interessano

for i in range(1, 30):
    layer.ipfs_log('Ciao')


acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530')
print(acct.address)
wallet = Account.encrypt(acct.privateKey, 'password')
print(wallet)
with open ('./my-account','w') as keyfile:
Ejemplo n.º 15
0
class ServiceProvider(metaclass=ThreadSafeSingleton):
    def __init__(self):
        self.__init = False
        self.__lock = threading.Lock()

        self.__sas_if = None
        self.__sas_api = None

        self.__config = None
        self.__logger = print
        self.__sas_terminal = None
        self.__user_manager = None
        self.__access_control = None

        self.__offline_analysis_result = None

    def is_inited(self) -> bool:
        return self.__init

    def check_init(self, sas_if, sas_api, config=None, logger=print) -> bool:
        final_ret = True
        with self.__lock:
            if self.__init:
                return True

            self.__sas_if = sas_if
            self.__sas_api = sas_api

            self.__config = config if config is not None else self.__sas_api.config(
            )
            self.__logger = logger

            self.__sas_terminal = SasTerminal(self.__sas_if, self.__sas_api)
            self.__user_manager = UserManager()
            self.__access_control = AccessControl()

            ret = self.__init_offline_analysis_result()
            final_ret = ret and final_ret

            self.__init = final_ret
        return final_ret

    # def __init_sas(self) -> bool:
    #     try:
    #         self.log('Init StockAnalysisSystem...')
    #         from StockAnalysisSystem.interface.interface_local import LocalInterface
    #         # from StockAnalysisSystem.core.StockAnalysisSystem import StockAnalysisSystem
    #         self.__sas_interface = LocalInterface()
    #         self.__sas_interface.if_init(os.getcwd(), config=self.__config)
    #         # if not self.__sas_interface.sas_init(project_path=os.getcwd(), config=self.__config):
    #         #     raise Exception(sasIF.__sas().get_log_errors())
    #         self.__sas_api = sasApi
    #         self.log('Init StockAnalysisSystem Complete.')
    #         return True
    #     except Exception as e:
    #         self.__sas = None
    #         self.log(str(e))
    #         self.log(str(traceback.format_exc()))
    #         self.log('Init StockAnalysisSystem Fail')
    #         return False
    #     finally:
    #         pass

    def __init_offline_analysis_result(self) -> bool:
        self.log('Init OfflineAnalysisResult...')
        from .offline_analysis_result import OfflineAnalysisResult
        self.__offline_analysis_result = OfflineAnalysisResult(self.__logger)
        self.__offline_analysis_result.init(self.__config)
        self.log('Init OfflineAnalysisResult Complete.')
        return True

    # ---------------------------------------------------------------------------------------------------------

    def terminal_interact(self, text: str, **kwargs) -> str:
        """
        Interact with sas terminal.
        :param text: The input text
        :param kwargs: Any data that will passed to __async_terminal_interact_handler if it has async ack.
        :return: The response text
        """
        if not self.__init:
            return ''
        ctx = TerminalContext(self.__async_terminal_interact_handler, **kwargs)
        result = self.__sas_terminal.interact(ctx, text)
        return result

    def __async_terminal_interact_handler(self, **kwargs):
        pass

    # --------------------------------------------- Offline Analysis Result --------------------------------------------

    def get_security_analysis_result_url(self, security: str) -> str:
        if not self.__init:
            return ''
        if self.__offline_analysis_result is None:
            return ''
        if not self.__offline_analysis_result.security_result_exists(security):
            return ''
        return 'http://211.149.229.160/analysis?security=%s' % security

    def get_security_analysis_result_page(self, security: str) -> str:
        if not self.__init:
            return ''
        if self.__offline_analysis_result is None:
            return ''
        result_html = self.__offline_analysis_result.get_analysis_result_html(
            security)
        return generate_display_page('分析结果' + security, result_html)

    # ------------------------------------------------------------------------------------------------------------------

    def sys_call(self, token: str, feature: str, *args, **kwargs):
        if not self.__init:
            return ''
        access, reason = self.check_accessible(token, feature, *args, **kwargs)
        if access:
            resp = self.__sas_api.sys_call(feature, *args, **kwargs)
            return resp
        else:
            return reason

    def interface_call(self, token: str, feature: str, *args,
                       **kwargs) -> (bool, any):
        if not self.__init:
            return ''
        access, reason = self.check_accessible(token, feature, *args, **kwargs)
        if access:
            func = getattr(self.__sas_if, feature, None)
            resp = func(*args, **kwargs) if func is not None else None
            return resp
        else:
            return reason

    def check_accessible(self, token: str, feature, *args, **kwargs):
        return self.__access_control.accessible(token, feature, **kwargs) \
            if self.__access_control is not None else False, ''

    # @AccessControl.apply('query')
    # def query(self, uri: str, identity: str or None = None,
    #           since: str or None = None, until: str or None = None, **extra) -> str:
    #     if not isinstance(uri, str):
    #         return ''
    #     if isinstance(identity, str):
    #         identity = identity.split(',')
    #         identity = [s.strip() for s in identity]
    #     elif identity is None:
    #         pass
    #     else:
    #         return ''
    #     time_serial = (sasTimeUtil.text_auto_time(since),
    #                    sasTimeUtil.text_auto_time(until))
    #     if time_serial[0] is None and time_serial[1] is None:
    #         time_serial = None
    #     df = sasIF.sas_query(uri, identity, time_serial, **extra)
    #     return df

    # ------------------------------------------------------------------------------------------------------------------

    def log(self, text: str):
        if self.__logger is not None:
            self.__logger(text)
Ejemplo n.º 16
0
 def test_first_match_allow_(self):
   ac = AccessControl(config_first_match)
   is_allowed, reason = ac.check('user1', 'part_b', 'GET')
   self.assertEqual(is_allowed, True)
   self.assertEqual(reason, '[rules.r1] "admin" is allowed to do "any action" on "res1"')
Ejemplo n.º 17
0
 def test_rule_mismatch_(self):
   ac = AccessControl(config_first_match)
   is_allowed, reason = ac.check('user1', 'part_c', 'GET')
   self.assertEqual(is_allowed, True)
   self.assertEqual(reason, 'No matched rule found, use mismatch_decision: True')
Ejemplo n.º 18
0
 def test_all_allow_deny_(self):
   ac = AccessControl(config_all_allow)
   is_allowed, reason = ac.check('user5', 'part_a', 'POST')
   self.assertEqual(is_allowed, False)
   self.assertEqual(reason, '[rules.r2] "reader" is not allowed to do "POST" on "res2"')
Ejemplo n.º 19
0
 def test_any_allow_deny_(self):
   ac = AccessControl(config_any_allow)
   is_allowed, reason = ac.check('user5', 'part_c', 'POST')
   self.assertEqual(is_allowed, False)
   self.assertEqual(reason, 'All matched rules denied')
Ejemplo n.º 20
0
 def test_any_allow_allow_(self):
   ac = AccessControl(config_any_allow)
   is_allowed, reason = ac.check('user1', 'part_a', 'POST')
   self.assertEqual(is_allowed, True)
   self.assertEqual(reason, '[rules.r1] "admin" is allowed to do "*" on "res1"')