# Path: opennode/oms/core.py
# class IApplicationInitializedEvent(Interface):
#     """Emitted when application is initialized"""
# 
# Path: opennode/oms/endpoint/ssh/pubkey.py
# class InMemoryPublicKeyCheckerDontUse(SSHPublicKeyDatabase):
#     """Loads the public key from ~/.ssh/id_[rd]sa.pub at startup, and accepts logins for those keys
#     Designed for testing, especially local testing.
#     """
# 
#     def __init__(self):
#         # Super is old-style class without constructor
#         self.publicKey = None
# 
#     def checkKey(self, credentials):
#         """Accepts any user name"""
#         log.msg('Checking key for creds: %s' % credentials, system='ssh-pubkey', logLevel=DEBUG)
#         home = os.environ.get("HOME")
#         if home is not None:
#             key_path = '%s/.ssh/authorized_keys' % home
#         else:
#             key_path = '/etc/opennode/authorized_keys'
#         with open(key_path) as f:
#             for key in f:
#                 if self._checkKey(credentials, key):
#                     log.msg('Check success, found matching key', system='ssh-pubkey', logLevel=DEBUG)
#                     return True
#         log.msg('Check failed: pubkey not found in authorized list', system='ssh-pubkey', logLevel=DEBUG)
#         return False
# 
#     def _checkKey(self, credentials, key):
#         try:
#             return keys.Key.fromString(data=key).blob() == getattr(credentials, 'blob', None)
#         except Exception:
#             log.err(system='ssh-pubkey')
# 
# Path: opennode/oms/security/acl.py
# class NoSuchPermission(Exception):
# def preload_acl_file(iterable, filename=''):
# def preload_acl_line(path, permspec, filename='-', lineno='-'):
# 
# Path: opennode/oms/security/checker.py
# class strong_defaultdict(defaultdict):
# class AuditingPermissionDictionary(dict):
# class Checker(object):
#     def get(self, name):
# def get_interaction(obj):
#     def __getitem__(self, key):
#     def get(self, key, default=None):
# def _select_checker(value, interaction):
# def proxy_factory(value, interaction):
#     def __init__(self, get_permissions, set_permissions={}, interaction=None):
#     def permission_id(self, name):
#     def setattr_permission_id(self, name):
#     def check_getattr(self, obj, name):
#     def _checkPermission(self, obj, name, permission):
#     def check_setattr(self, obj, name):
#     def check(self, obj, name):
#     def proxy(self, value):
# 
# Path: opennode/oms/security/interaction.py
# def new_interaction(principal):
#     if not IPrincipal.providedBy(principal):
#         auth = getUtility(IAuthentication, context=None)
#         principal = auth.getPrincipal(principal)
# 
#     interaction = OmsSecurityPolicy()
#     interaction.add(SessionStub(principal))
#     return interaction
# 
# Path: opennode/oms/security/permissions.py
# class Role(ZopeRole):
#     """Oms roles act as permissions"""
# 
#     nick_to_role = {}
#     role_to_nick = {}
# 
#     def __init__(self, name, nick):
#         super(Role, self).__init__(name, name)
#         self.nick = nick
# 
#         if nick:
#             self.nick_to_role[nick] = self
#             self.role_to_nick[self.id] = nick


import grp
import hashlib
import logging
import os
import pkg_resources
import pam
import pwd
import sys
import time
import subprocess
import json
from sys import platform as _platform
from base64 import decodestring as decode
from base64 import encodestring as encode
from contextlib import closing
from grokcore.component import GlobalUtility, subscribe
from twisted.cred.checkers import FilePasswordDB
from twisted.cred.checkers import ICredentialsChecker
from twisted.cred.credentials import IUsernamePassword
from twisted.cred.error import UnauthorizedLogin
from twisted.internet import defer
from twisted.python import filepath
from zope.authentication.interfaces import IAuthentication
from zope.component import getUtility, provideUtility, queryUtility
from zope.interface import implements
from zope.security.proxy import Proxy, getObject, getChecker
from zope.security.management import system_user
from zope.securitypolicy.interfaces import IRole
from zope.securitypolicy.principalpermission import principalPermissionManager
from zope.securitypolicy.principalrole import principalRoleManager
from zope.securitypolicy.rolepermission import rolePermissionManager
from opennode.oms.core import IApplicationInitializedEvent
from opennode.oms.config import get_config
from opennode.oms.endpoint.ssh.pubkey import InMemoryPublicKeyCheckerDontUse
from opennode.oms.security import acl, checker
from opennode.oms.security.interaction import new_interaction
from opennode.oms.security.permissions import Role
from opennode.oms.security.principals import User, Group
    from twisted.internet import inotify
            if ':' in groups:
                groups, uid = groups.split(':', 1)
                uid = int(uid) if uid.strip() != 'None' else None
            else:
                uid = None
            oms_user = User(user.strip(), uid=uid)
            oms_user.groups = [group.strip() for group in groups.split(',') if group.strip()]
            log.debug('Loaded %s', oms_user)
            auth.registerPrincipal(oms_user)


class Sudo(object):

    def __init__(self, obj):
        self._obj = obj
        assert type(self._obj) is Proxy

    def __enter__(self):
        _checker = getChecker(self._obj)
        self.previous_interaction = _checker.interaction
        _checker.interaction = new_interaction('root')
        return self._obj

    def __exit__(self, *args):
        getChecker(self._obj).interaction = self.previous_interaction


def sudo(obj):
    """ System utility to elevate privileges to certain object accesses """
    obj = getObject(obj) if type(obj) is Proxy else obj

# Path: opennode/oms/core.py
# class IApplicationInitializedEvent(Interface):
#     """Emitted when application is initialized"""
# 
# Path: opennode/oms/endpoint/ssh/pubkey.py
# class InMemoryPublicKeyCheckerDontUse(SSHPublicKeyDatabase):
#     """Loads the public key from ~/.ssh/id_[rd]sa.pub at startup, and accepts logins for those keys
#     Designed for testing, especially local testing.
#     """
# 
#     def __init__(self):
#         # Super is old-style class without constructor
#         self.publicKey = None
# 
#     def checkKey(self, credentials):
#         """Accepts any user name"""
#         log.msg('Checking key for creds: %s' % credentials, system='ssh-pubkey', logLevel=DEBUG)
#         home = os.environ.get("HOME")
#         if home is not None:
#             key_path = '%s/.ssh/authorized_keys' % home
#         else:
#             key_path = '/etc/opennode/authorized_keys'
#         with open(key_path) as f:
#             for key in f:
#                 if self._checkKey(credentials, key):
#                     log.msg('Check success, found matching key', system='ssh-pubkey', logLevel=DEBUG)
#                     return True
#         log.msg('Check failed: pubkey not found in authorized list', system='ssh-pubkey', logLevel=DEBUG)
#         return False
# 
#     def _checkKey(self, credentials, key):
#         try:
#             return keys.Key.fromString(data=key).blob() == getattr(credentials, 'blob', None)
#         except Exception:
#             log.err(system='ssh-pubkey')
# 
# Path: opennode/oms/security/acl.py
# class NoSuchPermission(Exception):
# def preload_acl_file(iterable, filename=''):
# def preload_acl_line(path, permspec, filename='-', lineno='-'):
# 
# Path: opennode/oms/security/checker.py
# class strong_defaultdict(defaultdict):
# class AuditingPermissionDictionary(dict):
# class Checker(object):
#     def get(self, name):
# def get_interaction(obj):
#     def __getitem__(self, key):
#     def get(self, key, default=None):
# def _select_checker(value, interaction):
# def proxy_factory(value, interaction):
#     def __init__(self, get_permissions, set_permissions={}, interaction=None):
#     def permission_id(self, name):
#     def setattr_permission_id(self, name):
#     def check_getattr(self, obj, name):
#     def _checkPermission(self, obj, name, permission):
#     def check_setattr(self, obj, name):
#     def check(self, obj, name):
#     def proxy(self, value):
# 
# Path: opennode/oms/security/interaction.py
# def new_interaction(principal):
#     if not IPrincipal.providedBy(principal):
#         auth = getUtility(IAuthentication, context=None)
#         principal = auth.getPrincipal(principal)
# 
#     interaction = OmsSecurityPolicy()
#     interaction.add(SessionStub(principal))
#     return interaction
# 
# Path: opennode/oms/security/permissions.py
# class Role(ZopeRole):
#     """Oms roles act as permissions"""
# 
#     nick_to_role = {}
#     role_to_nick = {}
# 
#     def __init__(self, name, nick):
#         super(Role, self).__init__(name, name)
#         self.nick = nick
# 
#         if nick:
#             self.nick_to_role[nick] = self
#             self.role_to_nick[self.id] = nick


# Path: opennode/oms/security/authentication.py
import grp
import hashlib
import logging
import os
import pkg_resources
import pam
import pwd
import sys
import time
import subprocess
import json
from sys import platform as _platform
from base64 import decodestring as decode
from base64 import encodestring as encode
from contextlib import closing
from grokcore.component import GlobalUtility, subscribe
from twisted.cred.checkers import FilePasswordDB
from twisted.cred.checkers import ICredentialsChecker
from twisted.cred.credentials import IUsernamePassword
from twisted.cred.error import UnauthorizedLogin
from twisted.internet import defer
from twisted.python import filepath
from zope.authentication.interfaces import IAuthentication
from zope.component import getUtility, provideUtility, queryUtility
from zope.interface import implements
from zope.security.proxy import Proxy, getObject, getChecker
from zope.security.management import system_user
from zope.securitypolicy.interfaces import IRole
from zope.securitypolicy.principalpermission import principalPermissionManager
from zope.securitypolicy.principalrole import principalRoleManager
from zope.securitypolicy.rolepermission import rolePermissionManager
from opennode.oms.core import IApplicationInitializedEvent
from opennode.oms.config import get_config
from opennode.oms.endpoint.ssh.pubkey import InMemoryPublicKeyCheckerDontUse
from opennode.oms.security import acl, checker
from opennode.oms.security.interaction import new_interaction
from opennode.oms.security.permissions import Role
from opennode.oms.security.principals import User, Group
    from twisted.internet import inotify

            if ':' in groups:
                groups, uid = groups.split(':', 1)
                uid = int(uid) if uid.strip() != 'None' else None
            else:
                uid = None
            oms_user = User(user.strip(), uid=uid)
            oms_user.groups = [group.strip() for group in groups.split(',') if group.strip()]
            log.debug('Loaded %s', oms_user)
            auth.registerPrincipal(oms_user)


class Sudo(object):

    def __init__(self, obj):
        self._obj = obj
        assert type(self._obj) is Proxy

    def __enter__(self):
        _checker = getChecker(self._obj)
        self.previous_interaction = _checker.interaction
        _checker.interaction = new_interaction('root')
        return self._obj

    def __exit__(self, *args):
        getChecker(self._obj).interaction = self.previous_interaction


def sudo(obj):
    """ System utility to elevate privileges to certain object accesses """
    obj = getObject(obj) if type(obj) is Proxy else obj

    return checker.proxy_factory(obj, new_interaction('root'))