Beispiel #1
0
# This file is part of the GOsa framework.
#
#  http://gosa-project.org
#
# Copyright:
#  (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de
#
# See the LICENSE file in the project's top-level directory for details.

__import__('pkg_resources').declare_namespace(__name__)
import pkg_resources
from gosa.common.utils import N_
from gosa.common.error import GosaErrorHandler as C

C.register_codes(
    dict(FILTER_NO_INSTANCE=N_("No filter instance for '%(filter)s' found")))


def get_filter(name):
    for entry in pkg_resources.iter_entry_points("gosa.object.filter"):
        module = entry.load()
        if module.__name__ == name:
            return module

    raise KeyError(C.make_error("FILTER_NO_INSTANCE", filter=name))


class ElementFilter(object):
    def __init__(self, obj):  # pragma: nocover
        pass
Beispiel #2
0
__import__('pkg_resources').declare_namespace(__name__)
import ldap
from itertools import permutations
from gosa.common.utils import N_
from gosa.common.error import GosaErrorHandler as C
from gosa.backend.exceptions import DNGeneratorError


# Register the errors handled  by us
C.register_codes(dict(
    GENERATOR_RDN_ATTRIBUTE_MISSING=N_("Attribute '%(topic)s' needed to generate a RDN is missing"),
    RDN_NOT_SPECIFIED=N_("No 'RDN' backend parameter specified"),
    NO_UNIQUE_DN=N_("Cannot generate a unique DN in '%(base)s' using a combination of %(rdns)s"),
    TARGET_EXISTS=N_("Target DN '%(target)s' already exists"),
    DB_CONFIG_MISSING=N_("No database configuration found for '%(target)s'"),
    BACKEND_ATTRIBUTE_CONFIG_MISSING=N_("Attribute '%s' uses the ObjectHandler backend but there is no config for it"),
    SOURCE_OBJECT_NOT_FOUND=N_("Cannot find source object '%(object)s'"),
    NO_UNIQUE_ENTRY=N_("No unique '%(object)s' object which matches '%(attribute)s == %(value)s'"),
    ID_GENERATION_FAILED=N_("Failed to generate a unique ID"),
    ENTRY_UUID_NOT_FOUND=N_("Entry '%(uuid)s' not found"),
    ENTRY_UUID_NOT_UNIQUE=N_("Entry '%(uuid)s' not unique"),
    ))


class ObjectBackend(object):

    def dn2uuid(self, dn):  # pragma: nocover
        """
        Convert DN to uuid.
        """
        raise NotImplementedError(C.make_error("NOT_IMPLEMENTED", dn, method="dn2uuid"))
Beispiel #3
0
import itertools
import tornado.wsgi
import tornado.web
import pkg_resources
import socket
from tornado.ioloop import IOLoop
from tornado.httpserver import HTTPServer
from zope.interface import implementer
from gosa.common import Environment
from gosa.common.hsts_request_handler import HSTSRequestHandler, HSTSStaticFileHandler
from gosa.common.handler import IInterfaceHandler
from gosa.common.utils import N_
from gosa.common.error import GosaErrorHandler as C

C.register_codes(
    dict(HTTP_PATH_ALREADY_REGISTERED=N_(
        "'%(path)s' has already been registered")))


@implementer(IInterfaceHandler)
class HTTPService(object):
    """
    Class to serve HTTP fragments to the interested client. It makes
    makes use of a couple of configuration flags provided by the clacks
    configuration files ``[http]`` section:

    ============== =============
    Key            Description
    ============== =============
    host           hostname
    port           port
Beispiel #4
0
from zope.interface import implementer
from gosa.common.utils import N_
from gosa.common import Environment
from gosa.common.error import GosaErrorHandler as C
from gosa.common.handler import IInterfaceHandler
from gosa.common.components import Command, PluginRegistry, ObjectRegistry, Plugin
from gosa.backend.objects import ObjectProxy, ObjectFactory

# Register the errors handled  by us
C.register_codes(
    dict(
        REFERENCE_NOT_FOUND=N_("Reference '%(ref)s' not found"),
        PROPERTY_NOT_FOUND=N_("Property '%(property)s' not found"),
        METHOD_NOT_FOUND=N_("Method '%(method)s' not found"),
        OBJECT_LOCKED=N_(
            "Object '%(object)s' has been locked by '%(user)s' on %(when)s"),
        OID_NOT_FOUND=N_("Object OID '%(oid)s' not found"),
        NOT_OBJECT_OWNER=N_("Caller does not own the referenced object"),
        AUTOGENERATED_ATTRIBUTE=N_(
            "Tried to manually set an auto-generated attribute"),
        SLAVE_MODE_NEEDS_MASTER=N_(
            "No master backend defined in slave mode. Please configure a master server in 'core.master' config option"
        )))


@implementer(IInterfaceHandler)
class JSONRPCObjectMapper(Plugin):
    """
    The *JSONRPCObjectMapper* is a GOsa backend plugin that implements a stack
    which can handle object instances. These can be passed via JSONRPC using
    the *__jsonclass__* helper attribute and allows remote proxies to emulate
    the object on the stack. The stack can hold objects that have been
Beispiel #5
0
from u2flib_server.jsapi import DeviceRegistration
from u2flib_server.u2f import (start_register, complete_register,
                               start_authenticate, verify_authenticate)
from cryptography.hazmat.primitives.serialization import Encoding
from pyotp import TOTP, random_base32
from gosa.backend.exceptions import ACLException
from gosa.backend.objects import ObjectProxy
from gosa.common import Environment
from gosa.common.components import Plugin
from gosa.common.components import PluginRegistry
from gosa.common.utils import N_
from gosa.common.error import GosaErrorHandler as C

# Register the errors handled  by us
C.register_codes(dict(
    UNKNOWN_2FA_METHOD=N_("Unknown two factor authentication method '%(method)s'"),
    CHANGE_2FA_METHOD_FORBIDDEN=N_("Wrong password! Changing two-factor authentication method denied.")
))


class UnknownTwoFAMethod(Exception):
    pass


class ChangingNotAllowed(Exception):
    pass


class TwoFactorAuthManager(Plugin):
    """
    Manages the two factor authentication settings for users
    """
Beispiel #6
0
from gosa.common.event import EventMaker
from zope.interface import implementer
from gosa.common.utils import N_
from gosa.common import Environment
from gosa.common.error import GosaErrorHandler as C, GosaException
from gosa.common.handler import IInterfaceHandler
from gosa.common.components import Command, PluginRegistry, ObjectRegistry, Plugin
from gosa.backend.objects import ObjectProxy


# Register the errors handled  by us
C.register_codes(dict(
    REFERENCE_NOT_FOUND=N_("Reference '%(ref)s' not found"),
    PROPERTY_NOT_FOUND=N_("Property '%(property)s' not found"),
    METHOD_NOT_FOUND=N_("Method '%(method)s' not found"),
    OBJECT_LOCKED=N_("Object '%(object)s' has been locked by '%(user)s' on %(when)s"),
    OID_NOT_FOUND=N_("Object OID '%(oid)s' not found"),
    NOT_OBJECT_OWNER=N_("Caller does not own the referenced object"),
    AUTOGENERATED_ATTRIBUTE=N_("Tried to manually set an auto-generated attribute")
    ))

@implementer(IInterfaceHandler)
class JSONRPCObjectMapper(Plugin):
    """
    The *JSONRPCObjectMapper* is a GOsa backend plugin that implements a stack
    which can handle object instances. These can be passed via JSONRPC using
    the *__jsonclass__* helper attribute and allows remote proxies to emulate
    the object on the stack. The stack can hold objects that have been
    retrieved by their *OID* using the :class:`gosa.common.components.objects.ObjectRegistry`.

    Example::
Beispiel #7
0
from gosa.common import Environment
from gosa.common.components import Plugin, Command, PluginRegistry
from gosa.common.gjson import loads
from gosa.common.handler import IInterfaceHandler
from gosa.common.utils import N_

C.register_codes(
    dict(
        ERROR_GETTING_SERVER_PPD=N_(
            "Server PPD file could not be retrieved: '%(type)s'"),
        PPD_NOT_FOUND=N_("PPD file '%(ppd)s' not found"),
        OPTION_CONFLICT=N_(
            "Setting option '%(option)s' to '%(value)s' caused %(conflicts)s"),
        OPTION_NOT_FOUND=N_("Option '%(option)s' not found in PPD"),
        COULD_NOT_READ_SOURCE_PPD=N_("Could not read source PPD file"),
        USER_NOT_FOUND=N_("User '%(topic)s' not found"),
        PPD_DIFF_TO_LARGE=N_(
            "Cannot find new ppd file per diff, because to many new printers where found"
        ),
        PPD_ALREADY_EXISTS=N_(
            "Cannot find new ppd file per diff, because if already exists"),
        PPD_NOT_EXACTLY_ONE=N_(
            "Cannot find cups ppd - there should be exactly one for the manufacturer but there are %(number_ppds)s"
        ),
    ))


@implementer(IInterfaceHandler)
class CupsClient(Plugin):
    _priority_ = 99
    _target_ = "cups"
Beispiel #8
0
from gosa.common.env import make_session
from gosa.common.event import EventMaker
from gosa.common.handler import IInterfaceHandler
from zope.interface import implementer
from gosa.common.error import GosaErrorHandler as C
from gosa.common.utils import N_, generate_random_key, cache_return
from gosa.common.components import PluginRegistry
from gosa.common.gjson import loads, dumps
from base64 import b64encode as encode
from gosa.backend.objects.backend.back_foreman import Foreman as ForemanBackend, ForemanClient, ForemanBackendException

C.register_codes(dict(
    FOREMAN_UNKNOWN_TYPE=N_("Unknown object type '%(type)s'"),
    NO_MAC=N_("No MAC given to identify host '%(hostname)s'"),
    DEVICE_NOT_FOUND=N_("Cannot find device '%(hostname)s'"),
    NO_FOREMAN_OBJECT=N_("This object is not managed by foreman"),
    MULTIPLE_DEVICES_FOUND=N_("(%devices)s found for hostname '%(hostname)s'"),
    HOSTGROUP_NOT_FOUND=N_("Cannot find hostgroup with id '%(group_id)s'"),
    MULTIPLE_HOSTGROUPS_FOUND=N_("(%groups)s found for group id '%(group_id)s'"),
))


@implementer(IInterfaceHandler)
class Foreman(Plugin):
    """
    The Foreman plugin takes care about syncing the required data between the foreman and GOsa.
    Currently the following foreman objects are synced:

    * ``hosts``, ``discovered_hosts`` as ``ForemanHost`` objects
    * ``hostgroups`` as ``Foreman`` objects
Beispiel #9
0
in the foreman API response. If not specified the backend assumes that ``_uuidSourceAttribute == _uuidAttribute``.
These two settings are used to generate the API URL to access the object in foreman.
In this example the URL for HTTP-requests would be <foreman-host>/api/hosts/<cn>.

``needs`` is optional and defines attribute names which values the backend needs to know to perform its task.

*Example:*

    The ForemanHost needs to know the value of the status attribute. If status="discovered" the backend needs to talk to the API
    endpoint "discovered_hosts" instead of "hosts". 
"""

# Register the errors handled  by us
C.register_codes(
    dict(FOREMAN_OBJECT_NOT_FOUND=N_(
        "The requested foreman object does not exist: '%(topic)s'"),
         FOREMAN_COMMUNICATION_ERROR=N_(
             "Foreman communication error type: '%(topic)s'")))


class Foreman(ObjectBackend):
    modifier = None

    @classmethod
    def set_modifier(cls, val):
        cls.modifier = val

    @classmethod
    def get_modifier(cls):
        return cls.modifier
Beispiel #10
0
from zope.interface import implementer
import hmac
from gosa.backend.exceptions import ACLException, WebhookException
from gosa.common import Environment
from gosa.common.error import GosaErrorHandler as C
from gosa.common.components import Command
from gosa.common.components import Plugin
from gosa.common.components import PluginRegistry
from gosa.common.gjson import loads, dumps
from gosa.common.handler import IInterfaceHandler
from gosa.common.hsts_request_handler import HSTSRequestHandler
from gosa.common.utils import N_

# Register the errors handled  by us
C.register_codes(
    dict(NO_REGISTERED_WEBHOOK_HANDLER=N_(
        "No webhook handler for content type '%(topic)s' found")))


@implementer(IInterfaceHandler)
class WebhookRegistry(Plugin):
    _priority_ = 0
    _target_ = "core"
    __hooks = {}
    __handlers = {}

    def __init__(self):
        self.env = Environment.getInstance()
        self.log = logging.getLogger(__name__)
        self.log.info("initializing webhook registry")
Beispiel #11
0
from gosa.common.components.auth import *
from gosa.backend import __version__ as VERSION
from gosa.backend.lock import GlobalLock
from gosa.backend.utils.ldap import check_auth
from gosa.backend.exceptions import FilterException
from gosa.common.components.command import no_login_commands
import hashlib


# Register the errors handled  by us
from tornado.concurrent import Future

C.register_codes(dict(
    INVALID_JSON=N_("Invalid JSON string '%(data)s'"),
    JSON_MISSING_PARAMETER=N_("Parameter missing in JSON body"),
    PARAMETER_LIST_OR_DICT=N_("Parameter must be list or dictionary"),
    INDEXING=N_("Index rebuild in progress - try again later"),
    REGISTRY_NOT_READY=N_("Registry is not ready")
    ), module="gosa.backend")


class JsonRpcHandler(HSTSRequestHandler):
    """
    This is the tornado request handler which is responsible for serving the
    :class:`gosa.backend.command.CommandRegistry` via HTTP/JSONRPC.
    """

    # Simple authentication saver
    __session = {}
    # denial service for some time after login fails to often
    __dos_manager = {}
Beispiel #12
0
from gosa.backend.exceptions import ACLException, WebhookException
from gosa.common import Environment
from gosa.common.error import GosaErrorHandler as C
from gosa.common.components import Command
from gosa.common.components import Plugin
from gosa.common.components import PluginRegistry
from gosa.common.gjson import loads, dumps
from gosa.common.handler import IInterfaceHandler
from gosa.common.hsts_request_handler import HSTSRequestHandler
from gosa.common.utils import N_


# Register the errors handled  by us
C.register_codes(dict(
    NO_REGISTERED_WEBHOOK_HANDLER=N_("No webhook handler for mime type '%(topic)s' found"),
    EXISTING_WEBHOOK_HANDLER=N_("There is already a webhook registered for mime-type '%(topic)s' with name '%(name)s'"),
    INVALID_WEBHOOK_SENDER_NAME=N_("Invalid sender name syntax: only ASCII letters and optional hyphens are allowed"),
    INVALID_WEBHOOK_MIME_TYPEE=N_("Invalid mime-type syntax: only alphanumeric, . (dot), + (plus) and / (slash) characters are allowed")
))


@implementer(IInterfaceHandler)
class WebhookRegistry(Plugin):
    _priority_ = 10
    _target_ = "core"
    __handlers = {}
    settings = None
    path_separator = '###'

    name_check = re.compile("^[a-zA-Z\-]+$")
    mime_type_check = re.compile("^[\w\.\+\/\-]+$")
Beispiel #13
0
from gosa.backend.objects.filter import ElementFilter
from gosa.backend.exceptions import ElementFilterException
from gosa.common.components import PluginRegistry
from gosa.common.env import make_session, declarative_base
from gosa.common.error import GosaErrorHandler as C
from gosa.common.utils import N_
from io import BytesIO
from sqlalchemy.orm import relationship
from sqlalchemy import Column, String, Integer, DateTime, and_, Sequence, ForeignKey
from sqlalchemy.exc import OperationalError

Base = declarative_base()

# Register the errors handled  by us
C.register_codes(dict(
    USER_IMAGE_CACHE_BROKEN=N_("Invalid image cache"),
    USER_IMAGE_SIZE_MISSING=N_("Image sizes not specified")))


class ImageSize(Base):
    __tablename__ = 'image-sizes'

    id = Column(Integer, Sequence('size_id_seq'), primary_key=True, nullable=False)
    uuid = Column(String(36), ForeignKey('image-index.uuid'))
    size = Column(Integer)
    path = Column(String)

    def __repr__(self):  # pragma: nocover
        return "<ImageSize(uuid='%s', path='%s', size='%d')>" % (self.uuid, self.path, self.size)

Beispiel #14
0
from gosa.common.utils import N_
from zope.interface import implementer
from gosa.common.handler import IInterfaceHandler
from gosa.backend.objects.proxy import ObjectProxy
from gosa.common.components import PluginRegistry
from gosa.common import Environment
from gosa.backend.exceptions import ACLException
from gosa.common.error import GosaErrorHandler as C


# Register the errors handled  by us
C.register_codes(dict(
    PASSWORD_METHOD_UNKNOWN=N_("Cannot detect password method"),
    PASSWORD_UNKNOWN_HASH=N_("No password method to generate hash of type '%(type)s' available"),
    PASSWORD_INVALID_HASH=N_("Invalid hash type for password method '%(method)s'"),
    PASSWORD_NO_ATTRIBUTE=N_("Object has no 'userPassword' attribute"),
    PASSWORD_NOT_AVAILABLE=N_("No password to lock."),
    UID_UNKNOWN=N_("User ID '%(target)s' is unknown."),
    PASSWORD_RECOVERY_IMPOSSIBLE=N_("The password recovery process cannot be started for this user, because of invalid ot missing data"),
    PASSWORD_RECOVERY_STATE_ERROR=N_("This step of the password recovery process cannot be executed at the current state")
))


class PasswordException(Exception):
    pass

@implementer(IInterfaceHandler)
class PasswordManager(Plugin):
    """
    Manager password changes
    """
    _priority_ = 91
Beispiel #15
0
from gosa.common.utils import N_
from gosa.common.components import PluginRegistry
from gosa.backend.objects import ObjectProxy
from gosa.backend.objects.factory import ObjectFactory
from gosa.common.handler import IInterfaceHandler
from gosa.common.error import GosaErrorHandler as C
from gosa.backend.objects.index import ObjectInfoIndex, KeyValueIndex
from sqlalchemy import and_, or_, func

# Register the errors handled  by us
C.register_codes(
    dict(
        INVALID_SEARCH_SCOPE=N_(
            "Invalid scope '%(scope)s' [SUB, BASE, ONE, CHILDREN]"),
        INVALID_SEARCH_DATE=N_(
            "Invalid date specification '%(date)s' [hour, day, week, month, year, all]"
        ),
        UNKNOWN_USER=N_("Unknown user '%(target)s'"),
        BACKEND_PARAMETER_MISSING=N_(
            "Backend parameter for '%(extension)s.%(attribute)s' is missing"),
        UNKNOWN_EXTENSION=N_("Unknown extension '%(target)s'")))


class GOsaException(Exception):
    pass


@implementer(IInterfaceHandler)
class RPCMethods(Plugin):
    """
    Key for configuration section **gosa**
Beispiel #16
0
------
"""
import ldapurl
import ldap.sasl
import logging
from ldap.filter import filter_format
from contextlib import contextmanager
from gosa.common import Environment
from gosa.common.utils import N_
from gosa.common.error import GosaErrorHandler as C
from gosa.backend.exceptions import LDAPException


C.register_codes(dict(
    NO_SASL_SUPPORT=N_("No SASL support in the installed python-ldap detected"),
    LDAP_NO_CONNECTIONS=N_("No LDAP connection available"),
    ))


class LDAPHandler(object):
    """
    The LDAPHandler provides a connection pool with automatically reconnecting
    LDAP connections and is accessible thru the
    :meth:`gosa.backend.utils.ldap.LDAPHandler.get_instance` method.

    Example::

        >>> from gosa.backend.utils.ldap import LDAPHandler
        >>> from ldap.filter import filter_format
        >>> lh = LDAPHandler.get_instance()
        >>> uuid = 'you-will-not-find-anything'
Beispiel #17
0
#  (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de
#
# See the LICENSE file in the project's top-level directory for details.

import re
from gosa.common.utils import N_
from gosa.common import Environment
from gosa.backend.objects.filter import ElementFilter
from gosa.common.components import PluginRegistry
from gosa.backend.objects.comparator import ElementComparator
from gosa.common.error import GosaErrorHandler as C


# Register the errors handled  by us
C.register_codes(dict(
    SAMBA_DOMAIN_WITHOUT_SID=N_("Domain %(topic)s has no SID"),
    SAMBA_NO_SID_TYPE=N_("Invalid type '%(type)s' for SID generator [user, group]")
))


class SambaException(Exception):
    pass


class CheckSambaSIDList(ElementComparator):
    """
    Checks whether the given sambaSIDList can be saved or if it
    will produce recursions.
    """

    def process(self, all_props, key, value):
        errors = []
Beispiel #18
0
from gosa.backend.exceptions import EntryNotFound
from gosa.backend.objects import ObjectProxy
from gosa.common.error import GosaErrorHandler as C
from gosa.common import Environment
from gosa.common.components import Plugin, Command, PluginRegistry
from gosa.common.gjson import loads
from gosa.common.handler import IInterfaceHandler
from gosa.common.utils import N_


C.register_codes(dict(
    ERROR_GETTING_SERVER_PPD=N_("Server PPD file could not be retrieved: '%(type)s'"),
    PPD_NOT_FOUND=N_("PPD file '%(ppd)s' not found"),
    OPTION_CONFLICT=N_("Setting option '%(option)s' to '%(value)s' caused %(conflicts)s"),
    OPTION_NOT_FOUND=N_("Option '%(option)s' not found in PPD"),
    COULD_NOT_READ_SOURCE_PPD=N_("Could not read source PPD file"),
    USER_NOT_FOUND=N_("User '%(user)s' not found"),
    PPD_DIFF_TO_LARGE=N_("Cannot find new ppd file per diff, because to many new printers where found"),
    PPD_ALREADY_EXISTS=N_("Cannot find new ppd file per diff, because if already exists"),
    PPD_NOT_EXACTLY_ONE=N_(
        "Cannot find cups ppd - there should be exactly one for the manufacturer but there are %(number_ppds)s"),
))


@implementer(IInterfaceHandler)
class CupsClient(Plugin):
    _priority_ = 99
    _target_ = "cups"
    client = None
    __printer_list = None

    def __init__(self):
Beispiel #19
0
#  http://gosa-project.org
#
# Copyright:
#  (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de
#
# See the LICENSE file in the project's top-level directory for details.

__import__('pkg_resources').declare_namespace(__name__)
import pkg_resources
from gosa.common.utils import N_
from gosa.common.error import GosaErrorHandler as C


# Register the errors handled  by us
C.register_codes(dict(
    OPERATOR_NO_INSTANCE=N_("No operator instance for '%(operator)s' found")
    ))


def get_operator(name):
    for entry in pkg_resources.iter_entry_points("gosa.object.operator"):
        module = entry.load()
        if module.__name__ == name:
            return module

    raise KeyError(C.make_error("OPERATOR_NO_INSTANCE", operator=name))


class ElementOperator(object):

    def process(self, *args, **kwargs):  # pragma: nocover
Beispiel #20
0
from gosa.backend.routes.sse.main import SseHandler
from gosa.common.event import EventMaker
from gosa.common import Environment
from gosa.common.error import GosaErrorHandler as C
from gosa.common.components import Plugin, PluginRegistry
from gosa.common.components.command import Command
from gosa.common.utils import N_
from gosa.backend.components.workflow import Workflow, WorkflowException
from lxml import objectify, etree
from pkg_resources import resource_filename

# Register the errors handled  by us
C.register_codes(dict(
    WORKFLOW_DIR_ERROR=N_("Workflow directory '%(path)s' does not exist"),
    WORKFLOW_PERMISSION_DELETE=N_("No permission to delete workflow '%(id)s'"),
    WORKFLOW_DELETE_ERROR=N_("Error removing workflow '%(id)s': %(error)s"),
    WORKFLOW_NOT_FOUND=N_("Workflow '%(id)s' does not exist")
))


"""
Workflow Registery
==================

TODO: documentation
"""
class WorkflowRegistry(Plugin):
    _target_ = "workflow"
    instance = None
    env = None
Beispiel #21
0
from gosa.backend.routes.sse.main import SseHandler
from gosa.common.event import EventMaker
from gosa.common import Environment
from gosa.common.error import GosaErrorHandler as C
from gosa.common.components import Plugin, PluginRegistry
from gosa.common.components.command import Command
from gosa.common.utils import N_
from gosa.backend.components.workflow import Workflow, WorkflowException
from lxml import objectify, etree
from pkg_resources import resource_filename

# Register the errors handled  by us
C.register_codes(
    dict(WORKFLOW_DIR_ERROR=N_("Workflow directory '%(path)s' does not exist"),
         WORKFLOW_PERMISSION_DELETE=N_(
             "No permission to delete workflow '%(id)s'"),
         WORKFLOW_DELETE_ERROR=N_(
             "Error removing workflow '%(id)s': %(error)s"),
         WORKFLOW_NOT_FOUND=N_("Workflow '%(id)s' does not exist")))
"""
Workflow Registery
==================

TODO: documentation
"""


class WorkflowRegistry(Plugin):
    _target_ = "workflow"
    instance = None
    env = None
Beispiel #22
0
#
#  http://gosa-project.org
#
# Copyright:
#  (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de
#
# See the LICENSE file in the project's top-level directory for details.

from passlib.hash import lmhash, nthash
from gosa.backend.objects.filter import ElementFilter
from gosa.common.error import GosaErrorHandler as C
from gosa.common.utils import N_


# Register the errors handled  by us
C.register_codes(dict(
    TYPE_UNKNOWN=N_("Filter '%(topic)s' does not support input type '%(type)s'")))


class SambaHash(ElementFilter):
    """
    An object filter which generates samba NT/LM Password hashes for the incoming value.
    """
    def __init__(self, obj):
        super(SambaHash, self).__init__(obj)

    def process(self, obj, key, valDict):
        if len(valDict[key]['value']) and type(valDict[key]['value'][0]) == str:
            valDict['sambaNTPassword']['value'] = [nthash.encrypt(valDict[key]['value'][0])]
            valDict['sambaLMPassword']['value'] = [lmhash.encrypt(valDict[key]['value'][0])]
        else:
            raise ValueError(C.make_error("TYPE_UNKNOWN", self.__class__.__name__, type=type(valDict[key]['value'])))
Beispiel #23
0
                               start_authenticate, verify_authenticate)
from cryptography.hazmat.primitives.serialization import Encoding
from pyotp import TOTP, random_base32
from gosa.backend.exceptions import ACLException
from gosa.backend.objects import ObjectProxy
from gosa.common import Environment
from gosa.common.components import Plugin
from gosa.common.components import PluginRegistry
from gosa.common.utils import N_
from gosa.common.error import GosaErrorHandler as C

# Register the errors handled  by us
C.register_codes(
    dict(
        UNKNOWN_2FA_METHOD=N_(
            "Unknown two factor authentication method '%(method)s'"),
        CHANGE_2FA_METHOD_FORBIDDEN=N_(
            "Wrong password! Changing two-factor authentication method denied."
        )))


class UnknownTwoFAMethod(Exception):
    pass


class ChangingNotAllowed(Exception):
    pass


class TwoFactorAuthManager(Plugin):
    """
Beispiel #24
0
from gosa.common.utils import is_uuid, N_
from gosa.common.components import PluginRegistry
from gosa.common.error import GosaErrorHandler as C
from gosa.backend.exceptions import ACLException, ProxyException
from gosa.common.components.jsonrpc_utils import Binary
from io import StringIO

# Register the errors handled  by us
C.register_codes(dict(
    OBJECT_UNKNOWN_TYPE=N_("Unknown object type '%(type)s'"),
    OBJECT_EXTENSION_NOT_ALLOWED=N_("Extension '%(extension)s' not allowed"),
    OBJECT_EXTENSION_DEFINED=N_("Extension '%(extension)s' already there"),
    OBJECT_EXTENSION_DEPENDS=N_("Extension '%(extension)s' depends on '%(missing)s'"),
    PERMISSION_EXTEND=N_("No permission to extend %(target)s with %(extension)s"),
    OBJECT_NO_SUCH_EXTENSION=N_("Extension '%(extension)s' already retracted"),
    OBJECT_EXTENSION_IN_USE=N_("Extension '%(extension)s' is required by '%(origin)s'"),
    PERMISSION_RETRACT=N_("No permission to retract '%(extension)s' from '%(target)s'"),
    PERMISSION_MOVE=N_("No permission to move '%(source)s' to '%(target)s'"),
    OBJECT_HAS_CHILDREN=N_("Object '%(target)s' has children"),
    PERMISSION_REMOVE=N_("No permission to remove '%(target)s'"),
    PERMISSION_CREATE=N_("No permission to create '%(target)s'"),
    PERMISSION_ACCESS=N_("No permission to access '%(topic)s' on '%(target)s'"),
    OBJECT_UUID_MISMATCH=N_("UUID of base (%(b_uuid)s) and extension (%(e_uuid)s) differ")
    ))


class ObjectProxy(object):
    _no_pickle_ = True
    dn = None
    uuid = None
    __env = None
    __log = None
Beispiel #25
0
from gosa.common.handler import IInterfaceHandler
from gosa.common.components import Command, Plugin, PluginRegistry
from gosa.common.error import GosaErrorHandler as C
from gosa.backend.objects import ObjectFactory, ObjectProxy, ObjectChanged
from gosa.backend.exceptions import FilterException, IndexException, ProxyException, ObjectException
from gosa.backend.lock import GlobalLock
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import Column, String, Integer, Sequence, DateTime, ForeignKey, or_, and_, not_, func

Base = declarative_base()

# Register the errors handled  by us
C.register_codes(dict(
    OBJECT_EXISTS=N_("Object with UUID %(uuid)s already exists"),
    OBJECT_NOT_FOUND=N_("Cannot find object %(id)s"),
    INDEXING=N_("Index rebuild in progress - try again later"),
    NOT_SUPPORTED=N_("Requested search operation %(operation)s is not supported"),
))


class Schema(Base):
    __tablename__ = 'schema'

    hash = Column(String(32), primary_key=True)

    def __repr__(self):  # pragma: nocover
       return "<Schema(hash='%s')>" % self.hash


class KeyValueIndex(Base):
    __tablename__ = 'kv-index'
Beispiel #26
0
from gosa.backend.objects.filter import ElementFilter
from gosa.backend.exceptions import ElementFilterException
from gosa.common.components import PluginRegistry
from gosa.common.env import make_session, declarative_base
from gosa.common.error import GosaErrorHandler as C
from gosa.common.utils import N_
from io import BytesIO
from sqlalchemy.orm import relationship
from sqlalchemy import Column, String, Integer, DateTime, and_, Sequence, ForeignKey
from sqlalchemy.exc import OperationalError

Base = declarative_base()

# Register the errors handled  by us
C.register_codes(
    dict(USER_IMAGE_CACHE_BROKEN=N_("Invalid image cache"),
         USER_IMAGE_SIZE_MISSING=N_("Image sizes not specified")))


class ImageSize(Base):
    __tablename__ = 'image-sizes'

    id = Column(Integer,
                Sequence('size_id_seq'),
                primary_key=True,
                nullable=False)
    uuid = Column(String(36), ForeignKey('image-index.uuid'))
    size = Column(Integer)
    path = Column(String)

    def __repr__(self):  # pragma: nocover
Beispiel #27
0
from gosa.backend.objects import ObjectProxy
from gosa.common.error import GosaErrorHandler as C, GosaException
from gosa.backend.plugins.misc.transliterate import Transliterate
from gosa.common import Environment
from gosa.common.components import Command
from gosa.common.components import Plugin
from gosa.common.components import PluginRegistry
from gosa.common.handler import IInterfaceHandler
from gosa.common.utils import N_
from zope.interface import implementer
import re
import random

C.register_codes(
    dict(CONFIG_NO_FORMAT_STRING=N_(
        "Cannot find a format_string in the configuration"),
         GROUP_ID_IS_AMBIGUOUS=N_(
             "Multiple PosixGroups with gid '%(gid)s' found")))


@implementer(IInterfaceHandler)
class User(Plugin):
    _priority_ = 0
    _target_ = "core"

    @Command(__help__=N_('Generates a uid'))
    def generateUid(self, data):

        format_string = Environment.getInstance().config.get(
            'core.idGenerator')
        if not format_string:
Beispiel #28
0
``_uuidSourceAttribute`` is optional and specifies the attribute name where the ID value can be found
in the foreman API response. If not specified the backend assumes that ``_uuidSourceAttribute == _uuidAttribute``.
These two settings are used to generate the API URL to access the object in foreman.
In this example the URL for HTTP-requests would be <foreman-host>/api/hosts/<cn>.

``needs`` is optional and defines attribute names which values the backend needs to know to perform its task.

*Example:*

    The ForemanHost needs to know the value of the status attribute. If status="discovered" the backend needs to talk to the API
    endpoint "discovered_hosts" instead of "hosts". 
"""

# Register the errors handled  by us
C.register_codes(dict(
    FOREMAN_OBJECT_NOT_FOUND=N_("The requested foreman object does not exist: '%(topic)s'"),
    FOREMAN_COMMUNICATION_ERROR=N_("Foreman communication error type: '%(topic)s'")
))


class Foreman(ObjectBackend):

    def __init__(self):
        # Initialize environment and logger
        self.env = Environment.getInstance()
        self.log = getLogger(__name__)
        self.client = ForemanClient()
        self.e = EventMaker()

    def load(self, uuid, info, back_attrs=None, data=None, needed=None):
        """
        Loading attribute values from foreman API
Beispiel #29
0
import logging
import pkg_resources
from zope.interface import implementer

from gosa.backend.exceptions import ACLException
from gosa.common import Environment
from gosa.common.error import GosaErrorHandler as C
from gosa.common.components import Plugin, PluginRegistry
from gosa.common.components.command import Command
from gosa.common.handler import IInterfaceHandler
from gosa.common.utils import N_

# Register the errors handled  by us
C.register_codes(dict(
    NO_SETTINGS_HANDLER_FOUND=N_("No settings handler found for path '%(path)s'")
))


@implementer(IInterfaceHandler)
class SettingsRegistry(Plugin):
    _priority_ = 0
    _target_ = "settings"
    __handlers = {}
    _acl = None

    def __init__(self):
        self.env = Environment.getInstance()
        self.__log = logging.getLogger(__name__)

    def serve(self):
Beispiel #30
0
from gosa.backend.exceptions import ACLException, WebhookException
from gosa.common import Environment
from gosa.common.error import GosaErrorHandler as C
from gosa.common.components import Command
from gosa.common.components import Plugin
from gosa.common.components import PluginRegistry
from gosa.common.gjson import loads, dumps
from gosa.common.handler import IInterfaceHandler
from gosa.common.hsts_request_handler import HSTSRequestHandler
from gosa.common.utils import N_


# Register the errors handled  by us
C.register_codes(dict(
    NO_REGISTERED_WEBHOOK_HANDLER=N_("No webhook handler for mime type '%(topic)s' found"),
    EXISTING_WEBHOOK_HANDLER=N_("There is already a webhook registered for mime-type '%(topic)s' with name '%(name)s'"),
    INVALID_WEBHOOK_SENDER_NAME=N_("Invalid sender name syntax: only ASCII letters and optional hyphens are allowed"),
    INVALID_WEBHOOK_MIME_TYPEE=N_("Invalid mime-type syntax: only alphanumeric, . (dot), + (plus) and / (slash) characters are allowed")
))


@implementer(IInterfaceHandler)
class WebhookRegistry(Plugin):
    _priority_ = 10
    _target_ = "core"
    __handlers = {}
    settings = None
    path_separator = '###'

    name_check = re.compile("^[a-zA-Z\-]+$")
    mime_type_check = re.compile("^[\w\.\+\/\-]+$")
Beispiel #31
0
from gosa.common.events import Event, EventNotAuthorized
from gosa.backend.exceptions import CommandInvalid, CommandNotAuthorized
from gosa.backend.routes.sse.main import SseHandler


# Global command types
NORMAL = 1
FIRSTRESULT = 2
CUMULATIVE = 4


# Register the errors handled  by us
C.register_codes(dict(
    COMMAND_NO_USERNAME=N_("Calling method '%(method)s' without a valid user session is not permitted"),
    COMMAND_NOT_DEFINED=N_("Method '%(method)s' is not defined"),
    PERMISSION_EXEC=N_("No permission to execute method '%(method)s'"),
    PERMISSION_EVENT=N_("No permission to send event '%(topic)s'"),
    COMMAND_WITHOUT_DOCS=N_("Method '%(method)s' has no documentation")
    ))


@implementer(IInterfaceHandler)
class CommandRegistry(Plugin):
    """
    This class covers the registration and invocation of methods
    imported thru plugins.
    """
    _priority_ = 0
    _target_ = "core"

    objects = {}
Beispiel #32
0
from gosa.common.event import EventMaker
from zope.interface import implementer
from gosa.common.utils import N_
from gosa.common import Environment
from gosa.common.error import GosaErrorHandler as C, GosaException
from gosa.common.handler import IInterfaceHandler
from gosa.common.components import Command, PluginRegistry, ObjectRegistry, Plugin
from gosa.backend.objects import ObjectProxy

# Register the errors handled  by us
C.register_codes(
    dict(REFERENCE_NOT_FOUND=N_("Reference '%(ref)s' not found"),
         PROPERTY_NOT_FOUND=N_("Property '%(property)s' not found"),
         METHOD_NOT_FOUND=N_("Method '%(method)s' not found"),
         OBJECT_LOCKED=N_(
             "Object '%(object)s' has been locked by '%(user)s' on %(when)s"),
         OID_NOT_FOUND=N_("Object OID '%(oid)s' not found"),
         NOT_OBJECT_OWNER=N_("Caller does not own the referenced object"),
         AUTOGENERATED_ATTRIBUTE=N_(
             "Tried to manually set an auto-generated attribute")))


@implementer(IInterfaceHandler)
class JSONRPCObjectMapper(Plugin):
    """
    The *JSONRPCObjectMapper* is a GOsa backend plugin that implements a stack
    which can handle object instances. These can be passed via JSONRPC using
    the *__jsonclass__* helper attribute and allows remote proxies to emulate
    the object on the stack. The stack can hold objects that have been
    retrieved by their *OID* using the :class:`gosa.common.components.objects.ObjectRegistry`.
Beispiel #33
0
import hmac
from gosa.backend.exceptions import ACLException, WebhookException
from gosa.common import Environment
from gosa.common.error import GosaErrorHandler as C
from gosa.common.components import Command
from gosa.common.components import Plugin
from gosa.common.components import PluginRegistry
from gosa.common.gjson import loads, dumps
from gosa.common.handler import IInterfaceHandler
from gosa.common.hsts_request_handler import HSTSRequestHandler
from gosa.common.utils import N_


# Register the errors handled  by us
C.register_codes(dict(
    NO_REGISTERED_WEBHOOK_HANDLER=N_("No webhook handler for content type '%(topic)s' found")
))


@implementer(IInterfaceHandler)
class WebhookRegistry(Plugin):
    _priority_ = 0
    _target_ = "core"
    __hooks = {}
    __handlers = {}

    def __init__(self):
        self.env = Environment.getInstance()
        self.log = logging.getLogger(__name__)
        self.log.info("initializing webhook registry")
Beispiel #34
0
#
#  http://gosa-project.org
#
# Copyright:
#  (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de
#
# See the LICENSE file in the project's top-level directory for details.

from passlib.hash import lmhash, nthash
from gosa.backend.objects.filter import ElementFilter
from gosa.common.error import GosaErrorHandler as C
from gosa.common.utils import N_

# Register the errors handled  by us
C.register_codes(
    dict(TYPE_UNKNOWN=N_(
        "Filter '%(topic)s' does not support input type '%(type)s'")))


class SambaHash(ElementFilter):
    """
    An object filter which generates samba NT/LM Password hashes for the incoming value.
    """
    def __init__(self, obj):
        super(SambaHash, self).__init__(obj)

    def process(self, obj, key, valDict):
        if len(valDict[key]['value']) and type(
                valDict[key]['value'][0]) == str:
            valDict['sambaNTPassword']['value'] = [
                nthash.encrypt(valDict[key]['value'][0])
Beispiel #35
0
# This file is part of the GOsa framework.
#
#  http://gosa-project.org
#
# Copyright:
#  (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de
#
# See the LICENSE file in the project's top-level directory for details.

__import__('pkg_resources').declare_namespace(__name__)
import pkg_resources
from gosa.common.utils import N_
from gosa.common.error import GosaErrorHandler as C

C.register_codes(
    dict(COMPARATOR_NO_INSTANCE=N_(
        "No comparator instance for '%(comparator)s' found")))


def get_comparator(name):
    for entry in pkg_resources.iter_entry_points("gosa.object.comparator"):

        module = entry.load()
        if module.__name__ == name:
            return module

    raise KeyError(C.make_error("COMPARATOR_NO_INSTANCE", comparator=name))


class ElementComparator(object):
    def process(self, *args, **kwargs):  # pragma: nocover
Beispiel #36
0
#  http://GOsa-project.org
#
# Copyright:
#  (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de
#
# See the LICENSE file in the project's top-level directory for details.

from gosa.backend.objects.filter import ElementFilter
from gosa.backend.objects.backend.registry import ObjectBackendRegistry
from gosa.common.error import GosaErrorHandler as C
from gosa.common.utils import N_

# Register the errors handled  by us
C.register_codes(
    dict(PARAMETER_NOT_NUMERIC=N_(
        "Parameter for '%(topic)s' have to be numeric"),
         BACKEND_TOO_MANY=N_("Too many backends for %(topic)s specified"),
         POSIX_ID_POOL_EMPTY=N_(
             "ID pool for attribute %(topic)s is empty [> %(max)s]")))


class PosixException(Exception):
    pass


class GenerateIDs(ElementFilter):
    """
    Generate gid/uidNumbers on demand
    """
    def __init__(self, obj):
        super(GenerateIDs, self).__init__(obj)
Beispiel #37
0
# Copyright:
#  (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de
#
# See the LICENSE file in the project's top-level directory for details.

import inspect
from gosa.common.utils import N_
from gosa.common.error import GosaErrorHandler as C
from gosa.backend.exceptions import ConversationNotSupported
__import__('pkg_resources').declare_namespace(__name__)

# Register the errors handled  by us
C.register_codes(
    dict(
        TYPE_NO_CHECK=N_("Cannot check value of type %(type)s"),
        TYPE_NO_MATCH=N_("Cannot match value of type %(type)s"),
        TYPE_NO_CONVERT=N_(
            "Cannot convert from '%(source)s' type to '%(target)s' type"),
    ))


class AttributeType(object):

    __alias__ = ""

    def _cnv_topic(self):
        fname = inspect.stack()[1][3]
        if fname[:12:] == "_convert_to_":
            return self.__alias__.lower(), fname[12:].replace("_", " ")
        else:
            return self.__alias__.lower(), fname[14:].replace("_", " ")
Beispiel #38
0
from gosa.common.components import Command, Plugin, PluginRegistry
from gosa.common.error import GosaErrorHandler as C
from gosa.backend.objects import ObjectFactory, ObjectProxy, ObjectChanged
from gosa.backend.exceptions import FilterException, IndexException, ProxyException, ObjectException
from gosa.backend.lock import GlobalLock
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import Column, String, Integer, Sequence, DateTime, ForeignKey, or_, and_, not_, func

Base = declarative_base()

# Register the errors handled  by us
C.register_codes(
    dict(
        OBJECT_EXISTS=N_("Object with UUID %(uuid)s already exists"),
        OBJECT_NOT_FOUND=N_("Cannot find object %(id)s"),
        INDEXING=N_("Index rebuild in progress - try again later"),
        NOT_SUPPORTED=N_(
            "Requested search operation %(operation)s is not supported"),
    ))


class Schema(Base):
    __tablename__ = 'schema'

    hash = Column(String(32), primary_key=True)

    def __repr__(self):  # pragma: nocover
        return "<Schema(hash='%s')>" % self.hash


class KeyValueIndex(Base):
Beispiel #39
0
from gosa.common.components import PluginRegistry
from gosa.backend.objects import ObjectProxy
from gosa.backend.objects.factory import ObjectFactory
from gosa.common.handler import IInterfaceHandler
from gosa.common.error import GosaErrorHandler as C
from gosa.backend.objects.index import ObjectInfoIndex, KeyValueIndex, SearchObjectIndex
from sqlalchemy import and_, or_, func
from sqlalchemy.inspection import inspect


# Register the errors handled  by us
from gosa.backend.utils import print_query

C.register_codes(dict(
    INVALID_SEARCH_SCOPE=N_("Invalid scope '%(scope)s' [SUB, BASE, ONE, CHILDREN]"),
    INVALID_SEARCH_DATE=N_("Invalid date specification '%(date)s' [hour, day, week, month, year, all]"),
    UNKNOWN_USER=N_("Unknown user '%(target)s'"),
    BACKEND_PARAMETER_MISSING=N_("Backend parameter for '%(extension)s.%(attribute)s' is missing"),
    UNKNOWN_EXTENSION=N_("Unknown extension '%(target)s'")))


class GOsaException(Exception):
    pass


@implementer(IInterfaceHandler)
class RPCMethods(Plugin):
    """
    Key for configuration section **gosa**

    +------------------+------------+-------------------------------------------------------------+
    + Key              | Format     +  Description                                                |
Beispiel #40
0
#
#  http://gosa-project.org
#
# Copyright:
#  (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de
#
# See the LICENSE file in the project's top-level directory for details.

__import__('pkg_resources').declare_namespace(__name__)
import pkg_resources
from gosa.common.utils import N_
from gosa.common.error import GosaErrorHandler as C


C.register_codes(dict(
    COMPARATOR_NO_INSTANCE=N_("No comparator instance for '%(comparator)s' found")
    ))


def get_comparator(name):
    for entry in pkg_resources.iter_entry_points("gosa.object.comparator"):

        module = entry.load()
        if module.__name__ == name:
            return module

    raise KeyError(C.make_error("COMPARATOR_NO_INSTANCE", comparator=name))


class ElementComparator(object):
Beispiel #41
0
from gosa.common.error import GosaErrorHandler as C
from gosa.common.components import Plugin
from gosa.common.events import Event, EventNotAuthorized
from gosa.backend.exceptions import CommandInvalid, CommandNotAuthorized
from gosa.backend.routes.sse.main import SseHandler

# Global command types
NORMAL = 1
FIRSTRESULT = 2
CUMULATIVE = 4

# Register the errors handled  by us
C.register_codes(
    dict(COMMAND_NO_USERNAME=N_(
        "Calling method '%(method)s' without a valid user session is not permitted"
    ),
         COMMAND_NOT_DEFINED=N_("Method '%(method)s' is not defined"),
         PERMISSION_EXEC=N_("No permission to execute method '%(method)s'"),
         PERMISSION_EVENT=N_("No permission to send event '%(topic)s'"),
         COMMAND_WITHOUT_DOCS=N_("Method '%(method)s' has no documentation")))


@implementer(IInterfaceHandler)
class CommandRegistry(Plugin):
    """
    This class covers the registration and invocation of methods
    imported thru plugins.
    """
    _priority_ = 0
    _target_ = "core"

    objects = {}
Beispiel #42
0
from gosa.common.error import GosaErrorHandler as C
from gosa.common.components.registry import PluginRegistry
from gosa.common.components.mqtt_proxy import MQTTServiceProxy
from gosa.common.components import Plugin
from gosa.common.components.command import Command
from gosa.plugins.goto.in_out_filters import mapping
from base64 import b64encode as encode
from Crypto.Cipher import AES

# Register the errors handled  by us
C.register_codes(dict(
    DEVICE_EXISTS=N_("Device with hardware address '%(topic)s' already exists"),
    USER_NOT_UNIQUE=N_("User '%(topic)s' is not unique"),
    CLIENT_NOT_FOUND=N_("Client '%(topic)s' not found"),
    CLIENT_OFFLINE=N_("Client '%(topic)s' is offline"),
    CLIENT_METHOD_NOT_FOUND=N_("Client '%(topic)s' has no method %(method)s"),
    CLIENT_DATA_INVALID=N_("Invalid data '%(entry)s:%(data)s' for client '%(topic)s provided'"),
    CLIENT_TYPE_INVALID=N_("Device type '%(type)s' for client '%(topic)s' is invalid [terminal, workstation, server, sipphone, switch, router, printer, scanner]"),
    CLIENT_OWNER_NOT_FOUND=N_("Owner '%(owner)s' for client '%(topic)s' not found"),
    CLIENT_UUID_INVALID=N_("Invalid client UUID '%(topic)s'"),
    CLIENT_STATUS_INVALID=N_("Invalid status '%(status)s' for client '%(topic)s'")))


class GOtoException(Exception):
    pass


@implementer(IInterfaceHandler)
class ClientService(Plugin):
    """
    Plugin to register clients and expose their functionality
Beispiel #43
0
from gosa.common.utils import N_
from gosa.common.error import GosaErrorHandler as C
from gosa.backend.exceptions import DNGeneratorError

# Register the errors handled  by us
C.register_codes(
    dict(
        GENERATOR_RDN_ATTRIBUTE_MISSING=N_(
            "Attribute '%(topic)s' needed to generate a RDN is missing"),
        RDN_NOT_SPECIFIED=N_("No 'RDN' backend parameter specified"),
        NO_UNIQUE_DN=N_(
            "Cannot generate a unique DN in '%(base)s' using a combination of %(rdns)s"
        ),
        TARGET_EXISTS=N_("Target DN '%(target)s' already exists"),
        DB_CONFIG_MISSING=N_(
            "No database configuration found for '%(target)s'"),
        BACKEND_ATTRIBUTE_CONFIG_MISSING=N_(
            "Attribute '%s' uses the ObjectHandler backend but there is no config for it"
        ),
        SOURCE_OBJECT_NOT_FOUND=N_("Cannot find source object '%(object)s'"),
        NO_UNIQUE_ENTRY=N_(
            "No unique '%(object)s' object which matches '%(attribute)s == %(value)s'"
        ),
        ID_GENERATION_FAILED=N_("Failed to generate a unique ID"),
        ENTRY_UUID_NOT_FOUND=N_("Entry '%(uuid)s' not found"),
        ENTRY_UUID_NOT_UNIQUE=N_("Entry '%(uuid)s' not unique"),
    ))
"""
Shared backend attributes:
--------------------------

* `_uuidAttribute`: change the attribute where the uuid is stored to identify the object in the backend
Beispiel #44
0
# Copyright:
#  (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de
#
# See the LICENSE file in the project's top-level directory for details.

import inspect
from gosa.common.utils import N_
from gosa.common.error import GosaErrorHandler as C
from gosa.backend.exceptions import ConversationNotSupported
__import__('pkg_resources').declare_namespace(__name__)


# Register the errors handled  by us
C.register_codes(dict(
    TYPE_NO_CHECK=N_("Cannot check value of type %(type)s"),
    TYPE_NO_MATCH=N_("Cannot match value of type %(type)s"),
    TYPE_NO_CONVERT=N_("Cannot convert from '%(source)s' type to '%(target)s' type"),
    ))


class AttributeType(object):

    __alias__ = ""

    def _cnv_topic(self):
        fname = inspect.stack()[1][3]
        if fname[:12:] == "_convert_to_":
            return self.__alias__.lower(), fname[12:].replace("_", " ")
        else:
            return self.__alias__.lower(), fname[14:].replace("_", " ")
Beispiel #45
0
------
"""
import ldapurl
import ldap.sasl
import logging
from ldap.filter import filter_format
from contextlib import contextmanager
from gosa.common import Environment
from gosa.common.utils import N_
from gosa.common.error import GosaErrorHandler as C
from gosa.backend.exceptions import LDAPException

C.register_codes(
    dict(
        NO_SASL_SUPPORT=N_(
            "No SASL support in the installed python-ldap detected"),
        LDAP_NO_CONNECTIONS=N_("No LDAP connection available"),
    ))


class LDAPHandler(object):
    """
    The LDAPHandler provides a connection pool with automatically reconnecting
    LDAP connections and is accessible thru the
    :meth:`gosa.backend.utils.ldap.LDAPHandler.get_instance` method.

    Example::

        >>> from gosa.backend.utils.ldap import LDAPHandler
        >>> from ldap.filter import filter_format
        >>> lh = LDAPHandler.get_instance()
Beispiel #46
0
from gosa.backend.objects.proxy import ObjectProxy
from gosa.common.components import PluginRegistry
from gosa.common import Environment
from gosa.backend.exceptions import ACLException
from gosa.common.error import GosaErrorHandler as C

# Register the errors handled  by us
C.register_codes(
    dict(
        PASSWORD_METHOD_UNKNOWN=N_("Cannot detect password method"),
        PASSWORD_UNKNOWN_HASH=N_(
            "No password method to generate hash of type '%(type)s' available"
        ),
        PASSWORD_INVALID_HASH=N_(
            "Invalid hash type for password method '%(method)s'"),
        PASSWORD_NO_ATTRIBUTE=N_("Object has no 'userPassword' attribute"),
        PASSWORD_NOT_AVAILABLE=N_("No password to lock."),
        UID_UNKNOWN=N_("User ID '%(target)s' is unknown."),
        PASSWORD_RECOVERY_IMPOSSIBLE=N_(
            "The password recovery process cannot be started for this user, because of invalid ot missing data"
        ),
        PASSWORD_RECOVERY_STATE_ERROR=N_(
            "This step of the password recovery process cannot be executed at the current state"
        )))


class PasswordException(Exception):
    pass


@implementer(IInterfaceHandler)
Beispiel #47
0
# See the LICENSE file in the project's top-level directory for details.
from gosa.backend.objects import ObjectProxy
from gosa.common.error import GosaErrorHandler as C, GosaException
from gosa.backend.plugins.misc.transliterate import Transliterate
from gosa.common import Environment
from gosa.common.components import Command
from gosa.common.components import Plugin
from gosa.common.components import PluginRegistry
from gosa.common.handler import IInterfaceHandler
from gosa.common.utils import N_
from zope.interface import implementer
import re
import random

C.register_codes(dict(
    CONFIG_NO_FORMAT_STRING=N_("Cannot find a format_string in the configuration"),
    GROUP_ID_IS_AMBIGUOUS=N_("Multiple PosixGroups with gid '%(gid)s' found")
    ))

@implementer(IInterfaceHandler)
class User(Plugin):
    _priority_ = 0
    _target_ = "core"

    @Command(__help__=N_('Generates a uid'))
    def generateUid(self, data):

        format_string = Environment.getInstance().config.get('core.idGenerator')
        if not format_string:
            raise EnvironmentError(C.make_error('CONFIG_NO_FORMAT_STRING'))
        format_string = format_string.strip()
        if format_string.startswith('"') and format_string.endswith('"'):
Beispiel #48
0
import logging
import pkg_resources
from zope.interface import implementer

from gosa.backend.exceptions import ACLException
from gosa.common import Environment
from gosa.common.error import GosaErrorHandler as C
from gosa.common.components import Plugin, PluginRegistry
from gosa.common.components.command import Command
from gosa.common.handler import IInterfaceHandler
from gosa.common.utils import N_

# Register the errors handled  by us
C.register_codes(dict(
    NO_SETTINGS_HANDLER_FOUND=N_("No settings handler found for path '%(path)s'")
))


@implementer(IInterfaceHandler)
class SettingsRegistry(Plugin):
    _priority_ = 0
    _target_ = "settings"
    __handlers = {}
    _acl = None

    def __init__(self):
        self.env = Environment.getInstance()
        self.__log = logging.getLogger(__name__)

    def serve(self):
Beispiel #49
0
import time
import datetime
from itertools import permutations
from logging import getLogger
from gosa.common import Environment
from gosa.common.utils import is_uuid, N_
from gosa.common.components.jsonrpc_utils import Binary
from gosa.common.error import GosaErrorHandler as C
from gosa.backend.utils.ldap import LDAPHandler
from gosa.backend.objects.backend import ObjectBackend
from gosa.backend.exceptions import EntryNotFound, RDNNotSpecified, DNGeneratorError


# Register the errors handled  by us
C.register_codes(dict(
    NO_POOL_ID=N_("No ID pool found"),
    MULTIPLE_ID_POOLS=N_("Multiple ID pools found")
    ))


class LDAP(ObjectBackend):
    con = None

    def __init__(self):
        # Load LDAP handler class
        self.env = Environment.getInstance()
        self.log = getLogger(__name__)

        self.lh = LDAPHandler.get_instance()
        self.con = self.lh.get_connection()
        self.uuid_entry = self.env.config.get("backend-ldap.uuid-attribute", "entryUUID")
        self.create_ts_entry = self.env.config.get("backend-ldap.create-attribute", "createTimestamp")
Beispiel #50
0
from gosa.common.utils import stripNs, N_, encrypt_key, generate_random_key, is_uuid
from gosa.common.error import GosaErrorHandler as C
from gosa.common.components.registry import PluginRegistry
from gosa.common.components.mqtt_proxy import MQTTServiceProxy
from gosa.common.components import Plugin
from gosa.common.components.command import Command
from gosa.plugins.goto.in_out_filters import mapping
from base64 import b64encode as encode

# Register the errors handled  by us
C.register_codes(dict(
    DEVICE_EXISTS=N_("Device with hardware address '%(mac)s' already exists"),
    USER_NOT_UNIQUE=N_("User '%(user)s' is not unique"),
    CLIENT_NOT_FOUND=N_("Client '%(client)s' not found"),
    CLIENT_OFFLINE=N_("Client '%(client)s' is offline"),
    CLIENT_METHOD_NOT_FOUND=N_("Client '%(client)s' has no method %(method)s"),
    CLIENT_DATA_INVALID=N_("Invalid data '%(entry)s:%(data)s' for client '%(client)s provided'"),
    CLIENT_TYPE_INVALID=N_("Device type '%(type)s' for client '%(client)s' is invalid [terminal, workstation, server, sipphone, switch, router, printer, scanner]"),
    CLIENT_OWNER_NOT_FOUND=N_("Owner '%(owner)s' for client '%(client)s' not found"),
    CLIENT_UUID_INVALID=N_("Invalid client UUID '%(uuid)s'"),
    CLIENT_STATUS_INVALID=N_("Invalid status '%(status)s' for client '%(client)s'")))


class GOtoException(Exception):
    pass


@implementer(IInterfaceHandler)
class ClientService(Plugin):
    """
    Plugin to register clients and expose their functionality
Beispiel #51
0
#
#  http://gosa-project.org
#
# Copyright:
#  (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de
#
# See the LICENSE file in the project's top-level directory for details.

import pkg_resources
from gosa.common.utils import N_
from gosa.common.error import GosaErrorHandler as C


# Register the errors handled  by us
C.register_codes(dict(
    BACKEND_NOT_FOUND=N_("Backend '%(topic)s' not found"),
    ))


class ObjectBackendRegistry(object):
    instance = None
    backends = {}
    uuidAttr = "entryUUID"

    def __init__(self):
        # Load available backends
        for entry in pkg_resources.iter_entry_points("gosa.object.backend"):
            clazz = entry.load()
            ObjectBackendRegistry.backends[clazz.__name__] = clazz()

    def dn2uuid(self, backend, dn):
Beispiel #52
0
from zope.interface import implementer

from gosa.backend.exceptions import ProxyException
from gosa.common.utils import N_, is_uuid
from gosa.common import Environment
from gosa.common.error import GosaErrorHandler as C
from gosa.common.handler import IInterfaceHandler
from gosa.common.components import Command, PluginRegistry, ObjectRegistry, Plugin
from gosa.backend.objects import ObjectProxy, ObjectFactory

# Register the errors handled  by us
C.register_codes(dict(
    REFERENCE_NOT_FOUND=N_("Reference '%(ref)s' not found"),
    PROPERTY_NOT_FOUND=N_("Property '%(property)s' not found"),
    METHOD_NOT_FOUND=N_("Method '%(method)s' not found"),
    OBJECT_LOCKED=N_("Object '%(object)s' has been locked by '%(user)s' on %(when)s"),
    OID_NOT_FOUND=N_("Object OID '%(oid)s' not found"),
    NOT_OBJECT_OWNER=N_("Caller does not own the referenced object"),
    AUTOGENERATED_ATTRIBUTE=N_("Tried to manually set an auto-generated attribute"),
    SLAVE_MODE_NEEDS_MASTER=N_("No master backend defined in slave mode. Please configure a master server in 'core.master' config option")
    ))


@implementer(IInterfaceHandler)
class JSONRPCObjectMapper(Plugin):
    """
    The *JSONRPCObjectMapper* is a GOsa backend plugin that implements a stack
    which can handle object instances. These can be passed via JSONRPC using
    the *__jsonclass__* helper attribute and allows remote proxies to emulate
    the object on the stack. The stack can hold objects that have been
    retrieved by their *OID* using the :class:`gosa.common.components.objects.ObjectRegistry`.
Beispiel #53
0
import itertools
import tornado.wsgi
import tornado.web
import pkg_resources
import socket
from tornado.ioloop import IOLoop
from tornado.httpserver import HTTPServer
from zope.interface import implementer
from gosa.common import Environment
from gosa.common.hsts_request_handler import HSTSRequestHandler, HSTSStaticFileHandler
from gosa.common.handler import IInterfaceHandler
from gosa.common.utils import N_
from gosa.common.error import GosaErrorHandler as C

C.register_codes(dict(
    HTTP_PATH_ALREADY_REGISTERED=N_("'%(path)s' has already been registered")
    ))


@implementer(IInterfaceHandler)
class HTTPService(object):
    """
    Class to serve HTTP fragments to the interested client. It makes
    makes use of a couple of configuration flags provided by the clacks
    configuration files ``[http]`` section:

    ============== =============
    Key            Description
    ============== =============
    host           hostname
    port           port
Beispiel #54
0
from gosa.backend.objects.xml_parsing import XmlParsing
from lxml import objectify, etree

from gosa.backend.routes.sse.main import SseHandler
from gosa.common.event import EventMaker
from gosa.common.gjson import dumps
from gosa.common.utils import N_
from gosa.backend.objects import ObjectProxy
from gosa.common import Environment
from gosa.common.components import PluginRegistry
from gosa.common.error import GosaErrorHandler as C, GosaErrorHandler
from pkg_resources import resource_filename

# Register the errors handled  by us
C.register_codes(
    dict(WORKFLOW_SCRIPT_ERROR=N_(
        "Error executing workflow script '%(topic)s'")))

#TODO: exceptions
#      attribute handling


class WorkflowException(Exception):
    pass


class Workflow:

    env = None
    dn = None
    uuid = None