예제 #1
0
파일: auth.py 프로젝트: pombreda/buildbot-1
 def __init__(self, passwdFile, **kwargs):
     TwistedICredAuthBase.__init__(
         self,
         [DigestCredentialFactory("md5", "buildbot"),
          BasicCredentialFactory("buildbot")],
         [FilePasswordDB(passwdFile)],
         **kwargs)
예제 #2
0
def require_digest_auth(resource):
    p = portal.Portal(TestAuthRealm(DIGEST_AUTH_PAGE))
    c = checkers.InMemoryUsernamePasswordDatabaseDontUse()
    c.addUser("digestuser", "digestuser")
    p.registerChecker(c)
    cred_factory = DigestCredentialFactory("md5", "Digest Auth protected area")
    return HTTPAuthSessionWrapper(p, [cred_factory])
예제 #3
0
파일: auth.py 프로젝트: pombreda/buildbot-1
 def __init__(self, users, **kwargs):
     TwistedICredAuthBase.__init__(
         self,
         [DigestCredentialFactory("md5", "buildbot"),
          BasicCredentialFactory("buildbot")],
         [InMemoryUsernamePasswordDatabaseDontUse(**dict(users))],
         **kwargs)
예제 #4
0
파일: web.py 프로젝트: MazeXD/cuwo-scripts
    def on_load(self):
        self.config = self.server.config.web
        with open('./web/js/init.js', 'w') as f:
            port = self.config.web_interface_port2
            auth = self.config.auth_key
            f.write('var server_port = "%s";\n var auth_key = "%s"' % (port,
                                                                       auth))
        root = File('./web')
        root.indexNames = ['index.html']
        root.putChild('css', static.File("./web/css"))
        root.putChild('js', static.File("./web/js"))
        root.putChild('img', static.File("./web/img"))

        checker = PasswordDictChecker(self.config)
        realm = HttpPasswordRealm(root)
        p = portal.Portal(realm, [checker])

        credentialFactory = DigestCredentialFactory("md5",
                                                    "Cuwo Interface Login")
        protected_resource = HTTPAuthSessionWrapper(p, [credentialFactory])

        auth_resource = resource.Resource()
        auth_resource.putChild("", protected_resource)
        site = SiteOverride(auth_resource)

        reactor.listenTCP(self.config.web_interface_port1, site)
        self.web_factory = WebFactory(self)
        reactor.listenTCP(self.config.web_interface_port2,
                          WebSocketFactory(self.web_factory))
예제 #5
0
 def __init__(self, users, **kwargs):
     for user, password in users.items():
         users[user] = unicode2bytes(password)
     TwistedICredAuthBase.__init__(
         self,
         [DigestCredentialFactory(b"md5", b"buildbot"),
          BasicCredentialFactory(b"buildbot")],
         [InMemoryUsernamePasswordDatabaseDontUse(**dict(users))],
         **kwargs)
예제 #6
0
파일: auth.py 프로젝트: pmisik/buildbot
 def __init__(self, users, **kwargs):
     if isinstance(users, dict):
         users = {user: unicode2bytes(pw) for user, pw in users.items()}
     elif isinstance(users, list):
         users = [(user, unicode2bytes(pw)) for user, pw in users]
     super().__init__([
         DigestCredentialFactory(b"MD5", b"buildbot"),
         BasicCredentialFactory(b"buildbot")
     ], [InMemoryUsernamePasswordDatabaseDontUse(**dict(users))], **kwargs)
예제 #7
0
def get_web_app(config, controller):
    auth = config.get_bool('web', 'auth', False)
    if auth:
        auth_file = config.get_string('web', 'auth-db')
        portal = Portal(PublicHTMLRealm(config, controller),
                        [FilePasswordDB(auth_file)])
        credential_factory = DigestCredentialFactory('md5', b'scrapy-do')
        resource = HTTPAuthSessionWrapper(portal, [credential_factory])
        return resource

    return WebApp(config, controller)
예제 #8
0
 def start_rest_api(self):
     root_page = resource.Resource()
     root_page.putChild('api', make_rest_api())
     site = AuthenticatedSite(root_page)
     site.credentialFactories = [
         BasicCredentialFactory("CloudMailing API"),
         DigestCredentialFactory("md5", "CloudMailing API")
     ]
     site.credentialsCheckers = [AdminChecker()]
     site.sessionFactory = UTSession
     self.p = reactor.listenTCP(0, site, interface="127.0.0.1")
     self.port = self.p.getHost().port
     self.api_base_url = 'http://127.0.0.1:%d/api/' % self.port
     self.agent = None
예제 #9
0
    def secure_resource(self, api_resource):
        """
        Wrap the provide API resource with an HTTP Authentication Session Wrapper

        :param api_resource: API resource to wrap

        :return: Resource, wrapped as requested
        """
        checkers = [self._checker]
        realm = Realm(api_resource, self._checker.users)
        portal = Portal(realm, checkers)

        credentials_factory = DigestCredentialFactory(self._algorithm,
                                                      self._auth_realm)
        resource = HTTPAuthSessionWrapper(portal, [credentials_factory])
        return resource
예제 #10
0
def get_api_service(application=None, interface='', port=33610, ssl_context_factory=None):
    """
    Return a service suitable for creating an application object.

    This service is a simple web server that serves files on port 8080 from
    underneath the current working directory.
    """
    # if not ssl_context_factory:
    #     ssl_context_factory = make_SSL_context()

    # check if an API KEY exists?
    config = ConfigFile()
    config.read(settings.CONFIG_FILE)

    key = config.get('CM_MASTER', 'API_KEY', '')
    if not key:
        logging.warn("API KEY not found. Generating a new one...")
        config.set('CM_MASTER', 'API_KEY', "".join([random.choice("abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)") for i in range(50)]))
        with file(settings.CONFIG_FILE, 'wt') as f:
            config.write(f)

    home_page = HomePage()
    home_page.put_child('CloudMailing',  CloudMailingRpc(useDateTime=True), True)
    home_page.put_child('api',  make_rest_api(xmlrpc_port=port, xmlrpc_use_ssl=ssl_context_factory is not None, api_key=key))
    home_page.make_home_page()

    webServer = AuthenticatedSite( home_page )
    webServer.credentialFactories = [BasicCredentialFactory("CloudMailing API"), DigestCredentialFactory("md5", "CloudMailing API")]
    webServer.credentialsCheckers = [AdminChecker()]

    if application:
        if ssl_context_factory:
            apiService = internet.SSLServer(port, webServer, ssl_context_factory, interface=interface)
        else:
            apiService = internet.TCPServer(port, webServer, interface=interface)
        apiService.setServiceParent(application)
    else:
        if ssl_context_factory:
            apiService = reactor.listenSSL(port, webServer, ssl_context_factory, interface=interface)
        else:
            apiService = reactor.listenTCP(port, webServer, interface=interface)

    logging.info("Supervisor XMLRPC%s server started on port %d", ssl_context_factory and " SSL" or "", port)
    return apiService
예제 #11
0
def setMain(opt):
    """Create a MainServer class based on `opt` options"""
    instanceName = opt['-n']
    if not instanceName:
        instanceName = ''
    print 'setMain', opt
    # Determine logfile path into datadir
    log_filename = params.log_filename if not opt.has_key(
        '-d') else os.path.join(opt['-d'], 'log', 'misura.log')
    params.log_filename = log_filename
    # Start the object sharing process
    share.init(connect=False, log_filename=log_filename)
    # Instantiate mainserver class
    main = MainServer(instanceName=instanceName,
                      port=opt['-p'],
                      confdir=opt['-c'],
                      datadir=opt['-d'],
                      plug=opt['-e'],
                      manager=share.manager)
    xmlrpc.addIntrospection(main)
    mimetypes = {'.h5': 'application/x-hdf;subtype=bag'}
    static.File.contentTypes.update(mimetypes)
    web = static.File(params.webdir)
    web.putChild('RPC', main)
    web.putChild('data', static.File(params.datadir))
    web.putChild('conf', static.File(params.confdir))
    # StreamServer
    mdir = MisuraDirectory(main)
    web.putChild('stream', mdir)

    # Further reading about auth stuff:
    # http://www.tsheffler.com/blog/?p=502
    realm = MisuraRealm()
    realm.resource = web
    # TODO: use also for FTP!
    checker = UsersChecker(main.users)
    portal = Portal(realm, [checker])
    cred_methods = (DigestCredentialFactory("md5", "MISURA"),
                    BasicCredentialFactory('MISURA'))
    wrapper = HTTPAuthSessionWrapper(portal, cred_methods)
    site = server.Site(wrapper)
    return main, web, site
예제 #12
0
    def __init__(self, server):
        Adapter.__init__(self, server)
        Resource.__init__(self)

        portal = Portal(LoginRealm())
        # todo: get this to work (to not store user passwords in plaintext)
        #passwordDB = FilePasswordDB('server.passwd', hash=lambda p: sha256(p).hexdigest())
        args = IMainSetup(100)
        passwordDB = FilePasswordDB(args.passwordfile)
        portal.registerChecker(passwordDB)
        # does not work as i expected: (keeping it still for the memories :)
        #portal.registerChecker(AllowAnonymousAccess(), IAnonymous)

        wrapper = HTTPAuthSessionWrapper(
            portal, [DigestCredentialFactory('md5', 'game_server')])
        #wrapper = HTTPAuthSessionWrapper(portal, [BasicCredentialFactory('game_server')])

        self.loginWrapper = wrapper
        self.putChild("login", wrapper)
        self.putChild("logout", LogoutResource())
예제 #13
0
def init():

    for num, cam in enumerate(CONFIG.get("cams", [])):
        cam_service = CamService(num, cam["cam"], cam)
        cam_service.signal_mdetect_trig.connect(emailNotifyDetector)
        cam_service.signal_mdetect_trig.connect(telegramNotifyDetector)
        checkAndCreateDir(
            os.path.join(CONFIG["etc"], str(num), CONFIG["motion_screenshot"]))
        checkAndCreateDir(
            os.path.join(CONFIG["etc"], str(num), CONFIG["motion_video"]))
        checkAndCreateDir(
            os.path.join(CONFIG["etc"], str(num), CONFIG["records"]))
        CAMS_LIST.append(cam_service)

    site = resource.Resource()

    log_pass = {CONFIG["security"]["login"]: CONFIG["security"]["password"]}

    checker = PasswordDictChecker(log_pass)
    realm = HttpPasswordRealm(site)
    p = portal.Portal(realm, [checker])

    credentialFactory = DigestCredentialFactory("md5", "PiSecrutyCenter")
    protected_resource = HTTPAuthSessionWrapper(p, [credentialFactory])

    site.putChild("cam", HttpCameraApi(CAMS_LIST))
    site.putChild("resource", static.File("resource"))
    site.putChild("history", static.File("history"))

    reactor.listenTCP(CONFIG["server"]["port"],
                      server.Site(protected_resource))
    reactor.addSystemEventTrigger('before', 'shutdown', cleanup)
    tg.run()

    for user in CONFIG["telegram"]["notified_users"]:
        tg.sendMessage(
            user,
            "Уведомление системы: WakeUp, i'm ready!For start work with me click /menu"
        )
예제 #14
0
파일: auth.py 프로젝트: pmisik/buildbot
 def __init__(self, passwdFile, **kwargs):
     super().__init__([
         DigestCredentialFactory(b"MD5", b"buildbot"),
         BasicCredentialFactory(b"buildbot")
     ], [FilePasswordDB(passwdFile)], **kwargs)
예제 #15
0
 def getChallenge(self, address):
     result = DigestCredentialFactory.getChallenge(self, address)
     del result["qop"]
     return result
예제 #16
0
    d = couch.openView(designID, 'models', include_docs=True, stale=False)
    d.addCallback(update)


class Realm(object):
    implements(IRealm)

    def requestAvatar(self, avatarId, mind, *interfaces):
        if IResource in interfaces:
            return (IResource, AdminGate(File(realm_dir)), lambda: None)
        raise NotImplementedError()


portal = Portal(Realm(), [FilePasswordDB('/home/aganzha/pswrds')])
credentialFactory = DigestCredentialFactory("md5", "buildpc.ru")
auth_wrapper = HTTPAuthSessionWrapper(portal, [credentialFactory])


class Admin(Resource):
    def render_GET(self, request):
        return "<html><body><h1>No way!</h1></body></html>"

    def getChild(self, name, request):
        return auth_wrapper.getChildWithDefault(name, request)


class AdminGate(Resource):
    def __init__(self, static):
        Resource.__init__(self)
        self.static = static
예제 #17
0
class SimpleRealm(object):
    """
    A realm which gives out L{GuardedResource} instances for authenticated users.
    """

    implements(IRealm)

    def requestAvatar(self, avatarId, mind, *interfaces):
        if resource.IResource in interfaces:
            return resource.IResource, GuardedResource(), lambda: None
        raise NotImplementedError()


#####
portal = Portal(SimpleRealm(), [FilePasswordDB('passwd.txt', '=')])
credFactory = DigestCredentialFactory('sha256', 'localhost:7070')
wrapper = HTTPAuthSessionWrapper(portal, [credFactory])

################################################################################
################################################################################


class Armory_Json_Rpc_Server(jsonrpc.JSONRPC):
    def __init__(self, wallet):
        self.wallet = wallet

    def jsonrpc_getnewaddress(self):
        addr = self.wallet.getNextUnusedAddress()
        return addr.getAddrStr()

    def jsonrpc_getbalance(self):
예제 #18
0
        ds1.addCallbacks(self.cbDBRes, callbackArgs=(cambot, request))
        return ds1

    def render_POST(self, request):
        d = self.generateCookie(request)
        #d.addCallback(self.cbDBRes, callbackArgs=(cambot,request))

        return NOT_DONE_YET


if __name__ == '__main__':
    from twisted.python import log
    from twisted.web.static import File
    from twisted.web.server import Site
    from twisted.internet import reactor

    log.startLogging(sys.stdout)

    checker = DBCredentialChecker()

    realm = WSRealm()
    p = portal.Portal(realm, [checker])
    credentialFactory = DigestCredentialFactory("md5", "PacketServo")
    protected_resource = HTTPAuthSessionWrapper(p, [credentialFactory])

    root = File(".")
    root.putChild("ws", protected_resource)
    site = Site(root)
    reactor.listenTCP(8888, site)
    reactor.run()
예제 #19
0
 def getChallenge(self, address):
     result = DigestCredentialFactory.getChallenge(self, address)
     del result["qop"]
     return result
예제 #20
0
파일: main.py 프로젝트: muraj/pyiradio
 def protect_resource(self, res, realm='Auth'):
   portal = Portal(ProtectedResource.PublicHTMLRealm(res), self.checkers)
   credFactory = DigestCredentialFactory('md5', realm)
   return HTTPAuthSessionWrapper(portal, [credFactory])
예제 #21
0
        glob_rules_file = conf.get('nx_extract', 'rules_path')
    except:
        print "No rules path in conf file ! Using default (/etc/nginx/sec-rules/core.rules)"

    try:
        glob_user = conf.get('nx_extract', 'username')
    except:
        print 'No username for web access ! Nx_extract will exit.'
        exit(-1)

    try:
        glob_pass = conf.get('nx_extract', 'password')
    except:
        print 'No password for web access ! Nx_extract will exit.'
        exit(-1)
    fd.close()

    credshandler = InMemoryUsernamePasswordDatabaseDontUse(
    )  # i know there is DontUse in the name
    credshandler.addUser(glob_user, glob_pass)
    portal = Portal(HTTPRealm(), [credshandler])
    credentialFactory = DigestCredentialFactory("md5", "Naxsi-UI")

    webroot = HTTPAuthSessionWrapper(portal, [credentialFactory])

    factory = Site(webroot)
    reactor.listenTCP(port, factory)

    #   daemonize(stdout = '/tmp/nx_extract_output', stderr = '/tmp/nx_extract_error')
    reactor.run()