Пример #1
0
 def getToken(self):
     return auth.authenticate(
         self.url,
         self.admin,
         self.password,
         admin_auth=True
     )
Пример #2
0
    def test_fault_non_existing_folder_genrequest_xml(self):
        """ Request a non existing folder, so we get a fitting fault
        """

        config = get_config()

        if config.getboolean('fault_test', 'enabled'):

            comm = Communication(config.get('fault_test', 'url'))

            token = auth.authenticate(config.get('fault_test', 'url'),
                                      config.get('fault_test', 'account'),
                                      config.get('fault_test', 'preauthkey'),
                                      config.get('fault_test', 'account_by'))

            request = comm.gen_request(request_type="xml", token=token)

            request.add_request(
                "GetFolderRequest",
                {
                    "folder": {
                        "path": config.get('fault_test', 'folder')
                    }
                },
                "urn:zimbraMail"
            )

            response = comm.send_request(request)

            self.check_response(
                response
            )
Пример #3
0
    def test_auth_failure_xml(self):
        """ Send a configured auth request with a wrong password in XML format
        and check the result
        """

        config = get_config()

        if config.getboolean('auth_test', 'enabled'):

            # Run only if enabled

            try:

                timestamp = config.getint('auth_test', 'timestamp')

            except ValueError:

                # If timestamp is set to a none-integer, we'll just assume
                # that it's unset

                timestamp = None

            response = authenticate(
                config.get('auth_test', 'url'),
                config.get('auth_test', 'account'),
                config.get('auth_test', 'preauthkey') + "1234",
                config.get('auth_test', 'account_by'),
                config.getint('auth_test', 'expires'), timestamp)

            self.assertEqual(
                response, None,
                "Authentication did not return 'None', but %s instead." %
                (response))
Пример #4
0
    def test_auth_xml(self):
        """ Send a configured auth request in XML format and check a
        successfully returned token
        """

        config = get_config()

        if config.getboolean('auth_test', 'enabled'):

            # Run only if enabled

            try:

                timestamp = config.getint('auth_test', 'timestamp')

            except ValueError:

                # If timestamp is set to a none-integer, we'll just assume
                # that it's unset

                timestamp = None

            response = authenticate(config.get('auth_test', 'url'),
                                    config.get('auth_test', 'account'),
                                    config.get('auth_test', 'preauthkey'),
                                    config.get('auth_test', 'account_by'),
                                    config.getint('auth_test', 'expires'),
                                    timestamp)

            self.assertNotEqual(
                response, None, "Authentication with the configured settings "
                "was not successful")
Пример #5
0
    def test_admin_auth_json(self):

        """ Send a configured admin auth request in json format using the
        admin auth-method and check a successfully returned token
        """

        config = get_config()

        if config.getboolean("admin_auth_test", "enabled"):

            # Run only if enabled

            response = authenticate(
                config.get("admin_auth_test", "url"),
                config.get("admin_auth_test", "account"),
                config.get("admin_auth_test", "password"),
                config.get("admin_auth_test", "account_by"),
                admin_auth=True,
                request_type="json"
            )

            if response is None:

                self.fail("Authentication with the configured settings "
                          "was not successful")
Пример #6
0
    def test_password_auth_xml(self):

        """ Send a configured auth request in xml format using password
        based authentication and check a successfully returned token
        """

        config = get_config()

        if config.getboolean("auth_by_password_test", "enabled"):

            # Run only if enabled

            response = authenticate(
                config.get("auth_by_password_test", "url"),
                config.get("auth_by_password_test", "account"),
                config.get("auth_by_password_test", "password"),
                config.get("auth_by_password_test", "account_by"),
                use_password=True,
                request_type="xml"
            )

            if response is None:

                self.fail("Authentication with the configured settings "
                          "was not ssuccessful")
Пример #7
0
    def test_fault_non_existing_folder_genrequest_invalidurl(self):
        """ Request a non existing folder, so we get a fitting fault
        """

        config = get_config()

        if config.getboolean('fault_test', 'enabled'):

            comm = Communication(config.get('fault_test', 'url') + "1234")

            token = auth.authenticate(config.get('fault_test', 'url'),
                                      config.get('fault_test', 'account'),
                                      config.get('fault_test', 'preauthkey'),
                                      config.get('fault_test', 'account_by'))

            request = comm.gen_request(token=token)

            request.add_request(
                "GetFolderRequest",
                {
                    "folder": {
                        "path": config.get('fault_test', 'folder')
                    }
                },
                "urn:zimbraMail"
            )

            # A 404 error should by raised as an exception.

            self.assertRaises(
                Exception,
                comm.send_request,
                request
            )
Пример #8
0
    def test_genrequest_default(self):
        """ Create a request only using the Communication-object
        """

        config = get_config()

        if config.getboolean("genrequest_test", "enabled"):

            # Run only if enabled

            comm = Communication(config.get("genrequest_test", "url"))

            token = authenticate(config.get("genrequest_test", "url"),
                                 config.get("genrequest_test", "account"),
                                 config.get("genrequest_test", "preauthkey"))

            self.assertNotEqual(token, None, "Cannot authenticate.")

            request = comm.gen_request(token=token)

            request.add_request("NoOpRequest", {}, "urn:zimbraMail")

            response = comm.send_request(request)

            if response.is_fault():

                self.fail(
                    "Reponse failed: (%s) %s" %
                    (response.get_fault_code(), response.get_fault_message()))
Пример #9
0
    def test_auth_failure_xml(self):

        """ Send a configured auth request with a wrong password in XML format
        and check the result
        """

        config = get_config()

        if config.getboolean("auth_test", "enabled"):

            # Run only if enabled

            try:

                timestamp = config.getint("auth_test", "timestamp")

            except ValueError:

                # If timestamp is set to a none-integer, we'll just assume
                # that it's unset

                timestamp = None

            response = authenticate(
                config.get("auth_test", "url"),
                config.get("auth_test", "account"),
                config.get("auth_test", "preauthkey") + "1234",
                config.get("auth_test", "account_by"),
                config.getint("auth_test", "expires"),
                timestamp,
            )

            self.assertEqual(response, None, "Authentication did not return 'None', but %s instead." % (response))
Пример #10
0
    def set_user( self , user_name ):
        """
        Tente de se connecter à l'API Zimbra avec un utilisateur donné. Si le
        nom d'utilisateur n'inclut pas un domaine, il sera rajouté.

        :param str user_name: le nom d'utilisateur

        :raises ZimbraError: une erreur de communication s'est produite
        """
        if '@' not in user_name:
            user_name = '{}@{}'.format( user_name , self.domain_ )

        if self.user_ is not None and self.user_ == user_name:
            return
        self.terminate( ) # ...Yes dear, you can self-terminate.

        from pythonzimbra.tools import auth
        from pythonzimbra.exceptions.auth import AuthenticationFailed
        Logging( 'zimbra' ).debug( 'Connexion pour {}'.format( user_name ) )
        try:
            ttok = auth.authenticate(
                    self.url_ , user_name ,
                    self.dkey_ , raise_on_error = True )
        except AuthenticationFailed as e:
            Logging( 'zimbra' ).error(
                    'Échec de la connexion: {}'.format( str( e ) ) )
            raise ZimbraConnectionError( e ) #FIXME
        Logging( 'zimbra' ).debug( 'Connexion réussie; jeton: {}'.format(
                ttok ) )

        assert ttok is not None
        self.user_ = user_name
        self.token_ = ttok
Пример #11
0
    def test_auth_xml(self):

        """ Send a configured auth request in XML format and check a
        successfully returned token
        """

        config = get_config()

        if config.getboolean("auth_test", "enabled"):

            # Run only if enabled

            try:

                timestamp = config.getint("auth_test", "timestamp")

            except ValueError:

                # If timestamp is set to a none-integer, we'll just assume
                # that it's unset

                timestamp = None

            response = authenticate(
                config.get("auth_test", "url"),
                config.get("auth_test", "account"),
                config.get("auth_test", "preauthkey"),
                config.get("auth_test", "account_by"),
                config.getint("auth_test", "expires"),
                timestamp,
            )

            self.assertNotEqual(response, None, "Authentication with the configured settings " "was not successful")
Пример #12
0
def get_token():
    url = os.environ['ZIMBRA_URL']
    account = os.environ['ZIMBRA_ACCOUNT']
    password = os.environ['ZIMBRA_PASSWORD']
    try:
        token = auth.authenticate(url, account, password, admin_auth=True)
    except:
        log.exception("locals=%s", locals())
    return token
Пример #13
0
def getToken(url, user, password):
    usr_token = auth.authenticate(
        url,
        user,
        password,
        admin_auth=True,
        use_password=True,
    )
    return usr_token
Пример #14
0
def get_token():
    url = os.environ['ZIMBRA_URL']
    account = os.environ['ZIMBRA_ACCOUNT']
    password = os.environ['ZIMBRA_PASSWORD']
    try:
        token = auth.authenticate(url, account, password, admin_auth=True)
    except:
        log.exception("locals=%s", locals())
    return token
Пример #15
0
 def getTokenUser(self,**kwargs):
     return auth.authenticate(
         self.url,
         #"http://mail.iservery.cz:81/service/soap",
         kwargs.get('user'),
         kwargs.get('password'),
         admin_auth=False,
         use_password=True
     )
Пример #16
0
 def auth(self):
     response = authenticate(self.url,
                             self.mail_addr,
                             self.pre_auth,
                             by='name',
                             expires=0,
                             timestamp=self.timestamp,
                             use_password=True,
                             raise_on_error=True)
     return response
Пример #17
0
 def generate_token(self):
     if self.token is None:
         self.token = auth.authenticate(self.url,
                                        self.mail_addr,
                                        self.pre_auth,
                                        by='name',
                                        expires=0,
                                        timestamp=self.timestamp,
                                        use_password=True,
                                        raise_on_error=True)
     return self.token
Пример #18
0
 def connect(self):
     url = os.environ['ZIMBRA_URL']
     account = os.environ['ZIMBRA_ACCOUNT']
     password = os.environ['ZIMBRA_PASSWORD']
     try:
         self.comm = Communication(url)
         self.token = auth.authenticate(url, account, password, admin_auth=True)
     except:
         log.exception("locals=%s", locals())
     if not self.token:
         raise Exception("Authentication failed: locals=%s", locals())
Пример #19
0
    def connect(self):
        try:
            self.comm = Communication(self.url)

            self.__token = auth.authenticate(self.url, self.usr, self.__password, admin_auth=True)
            self.request = self.comm.gen_request(token=self.__token, set_batch=True)

            return 'Conectado'

        except urllib.error.URLError as E:
        # catastrophic error. bail.
            return f'Erro na conexão: {E}'
Пример #20
0
def get_token(url):
    '''Get authentication token from Zimbra SOAP API'''
    login = os.getenv('LOGNAME') or os.getenv('USER') or os.getlogin()
    login = unicode(login)
    passwd = getpass.getpass()

    return auth.authenticate(
        url,
        login,
        passwd,
        use_password=True
    )
    def test_autoresponse_xml(self):

        """ Create an XML-request and pass this to send_request expection a
        xml response.
        """

        config = get_config()

        if config.getboolean("autoresponse_test", "enabled"):

            # Run only if enabled

            token = authenticate(
                config.get("autoresponse_test", "url"),
                config.get("autoresponse_test", "account"),
                config.get("autoresponse_test", "preauthkey")
            )

            self.assertNotEqual(
                token,
                None,
                "Cannot authenticate."
            )

            request = RequestXml()
            request.set_auth_token(token)
            request.add_request(
                "NoOpRequest",
                {

                },
                "urn:zimbraMail"
            )

            comm = Communication(config.get("autoresponse_test", "url"))

            response = comm.send_request(request)

            if response.is_fault():

                self.fail(
                    "Reponse failed: (%s) %s" % (
                        response.get_fault_code(),
                        response.get_fault_message()
                    )
                )

            self.assertEqual(
                response.response_type,
                "xml",
                "Invalid response type %s" % response.response_type
            )
Пример #22
0
def getAllInfo(url, adm, pword, domain):
    token = auth.authenticate(url, adm, pword, admin_auth=True)
    request = comm.gen_request(token=token)
    request.add_request("GetQuotaUsageRequest", {
        "domain": domain,
        "allServers": "1"
    }, "urn:zimbraAdmin")

    response = comm.send_request(request)
    if not response.is_fault():
        return response.get_response()['GetQuotaUsageResponse']['account']
    else:
        return "Error on zimbraAdmin: " + response.get_fault_message()
Пример #23
0
    def test_genrequest_fail(self):

        """ Create a request only using the Communication-object
        """

        config = get_config()

        if config.getboolean("genrequest_test", "enabled"):

            # Run only if enabled

            comm = Communication(config.get("genrequest_test", "url"))

            token = authenticate(
                config.get("genrequest_test", "url"),
                config.get("genrequest_test", "account"),
                config.get("genrequest_test", "preauthkey")
            )

            self.assertNotEqual(
                token,
                None,
                "Cannot authenticate."
            )

            self.assertRaises(
                UnknownRequestType,
                comm.gen_request,
                request_type="INVALID",
                token=token
            )

            request = comm.gen_request(token=token)

            request.add_request(
                "NoOpRequest",
                {

                },
                "urn:zimbraMail"
            )

            # Deliberately break the request

            request.request_type = "INVALID"

            self.assertRaises(
                UnknownRequestType,
                comm.send_request,
                request
            )
Пример #24
0
    def test_genrequest_check_response_xml(self):

        """ Create a request only using the Communication-object, send it and
            check the response
        """

        config = get_config()

        if config.getboolean("genrequest_test", "enabled"):

            # Run only if enabled

            comm = Communication(config.get("genrequest_test", "url"))

            token = authenticate(
                config.get("genrequest_test", "url"),
                config.get("genrequest_test", "account"),
                config.get("genrequest_test", "preauthkey")
            )

            self.assertNotEqual(
                token,
                None,
                "Cannot authenticate."
            )

            request = comm.gen_request(request_type="xml", token=token)

            request.add_request(
                "GetInfoRequest",
                {
                },
                "urn:zimbraAccount"
            )

            response = comm.send_request(request)

            if response.is_fault():

                self.fail(
                    "Reponse failed: (%s) %s" % (
                        response.get_fault_code(),
                        response.get_fault_message()
                    )
                )

            self.assertEqual(
                response.get_response()["GetInfoResponse"]["name"],
                config.get("genrequest_test", "account"),
                "Request returned unexpected response"
            )
    def test_genrequest_xml(self):

        """ Create a request only using the Communication-object
        """

        config = get_config()

        if config.getboolean("genrequest_test", "enabled"):

            # Run only if enabled

            comm = Communication(config.get("genrequest_test", "url"))

            token = authenticate(
                config.get("genrequest_test", "url"),
                config.get("genrequest_test", "account"),
                config.get("genrequest_test", "preauthkey")
            )

            self.assertNotEqual(
                token,
                None,
                "Cannot authenticate."
            )

            request = comm.gen_request(request_type="xml", token=token)

            request.add_request(
                "NoOpRequest",
                {

                },
                "urn:zimbraMail"
            )

            response = comm.send_request(request)

            if response.is_fault():

                self.fail(
                    "Reponse failed: (%s) %s" % (
                        response.get_fault_code(),
                        response.get_fault_message()
                    )
                )

            self.assertEqual(
                response.response_type,
                "xml",
                "Invalid response type %s" % response.response_type
            )
Пример #26
0
    def test_fault_non_existing_folder_batch_json(self):

        """ Request a non existing folder multiple times to get multiple
        faults
        """

        config = get_config()

        if config.getboolean('fault_test', 'enabled'):

            comm = Communication(config.get('fault_test', 'url'))

            token = auth.authenticate(config.get('fault_test', 'url'),
                                      config.get('fault_test', 'account'),
                                      config.get('fault_test', 'preauthkey'),
                                      config.get('fault_test', 'account_by'))

            request = RequestJson()

            request.set_auth_token(token)

            request.enable_batch()

            request.add_request(
                "GetFolderRequest",
                {
                    "folder": {
                        "path": config.get('fault_test', 'folder')
                    }
                },
                "urn:zimbraMail"
            )

            request.add_request(
                "GetFolderRequest",
                {
                    "folder": {
                        "path": config.get('fault_test', 'folder')
                    }
                },
                "urn:zimbraMail"
            )

            response = ResponseJson()

            comm.send_request(request, response)

            self.check_response(
                response
            )
Пример #27
0
    def __init__(self, admin_url, admin_user, admin_pass):
        self.admin_url = admin_url
        self.admin_user = admin_user
        self.admin_pass = admin_pass
        self.admin_account_by = 'name'
        self.request = None

        self.token = authenticate(self.admin_url,
                                  self.admin_user,
                                  self.admin_pass,
                                  self.admin_account_by,
                                  admin_auth=True,
                                  request_type="json")

        self.comm = Communication(self.admin_url)
Пример #28
0
def getAllInfo(url, adm, pword, domain):
    token = auth.authenticate(url, adm, pword, admin_auth=True)
    request = comm.gen_request(token=token, set_batch=True)
    request.add_request("GetAllCosRequest", {}, "urn:zimbraAdmin")
    request.add_request("GetAllAccountsRequest",
                        {"domain": {
                            "_content": domain,
                            "by": "name"
                        }}, "urn:zimbraAdmin")

    response = comm.send_request(request)
    if not response.is_fault():
        resp = [response.get_response(1), response.get_response(2)]
        return resp
    else:
        print "Error on zimbraAdmin: " + str(response.get_fault_message())
        sys.exit(3)
Пример #29
0
  def __init__(self, admin_url, admin_user, admin_pass):
    self.admin_url = admin_url
    self.admin_user = admin_user
    self.admin_pass = admin_pass
    self.admin_account_by = 'name'
    self.request = None

    self.token = authenticate(
      self.admin_url, 
      self.admin_user,
      self.admin_pass,
      self.admin_account_by,
      admin_auth=True,
      request_type="json"
    )

    self.comm = Communication(self.admin_url)
Пример #30
0
def getUserToken(url, adm, acc, pword):
    token = auth.authenticate(url, adm, pword, admin_auth=True)
    request = comm.gen_request(token=token)
    request.add_request(
        "DelegateAuthRequest",
        {
            "account": {
                "_content": acc,
                "by": "name"
            }
        },
        "urn:zimbraAdmin"
    )

    response = comm.send_request(request)
    if not response.is_fault():
        return response.get_response()['DelegateAuthResponse'][
            'authToken']['_content']
    else:
        print "Error on zimbraAdmin: " + response.get_fault_message()
        sys.exit(3)
Пример #31
0
    def test_admin_auth_xml(self):

        """ Send a configured admin auth request in xml format using the
        admin auth-method and check a successfully returned token
        """

        config = get_config()

        if config.getboolean("admin_auth_test", "enabled"):

            # Run only if enabled

            response = authenticate(
                config.get("admin_auth_test", "admin_url"),
                config.get("admin_auth_test", "admin_account"),
                config.get("admin_auth_test", "admin_password"),
                config.get("admin_auth_test", "admin_account_by"),
                admin_auth=True,
                request_type="xml",
            )

            self.assertNotEqual(response, None, "Authentication with the configured settings " "was not successful")
Пример #32
0
    def test_password_auth_json(self):

        """ Send a configured auth request in json format using password
        based authentication and check a successfully returned token
        """

        config = get_config()

        if config.getboolean("auth_by_password_test", "enabled"):

            # Run only if enabled

            response = authenticate(
                config.get("auth_by_password_test", "url"),
                config.get("auth_by_password_test", "account"),
                config.get("auth_by_password_test", "password"),
                config.get("auth_by_password_test", "account_by"),
                use_password=True,
                request_type="json",
            )

            self.assertNotEqual(response, None, "Authentication with the configured settings " "was not successful")
Пример #33
0
    def test_password_auth_failure_json(self):

        """ Send a configured auth request in json format using password based
        authentication and a wrong password and check the error
        """

        config = get_config()

        if config.getboolean("auth_by_password_test", "enabled"):

            # Run only if enabled

            response = authenticate(
                config.get("auth_by_password_test", "url"),
                config.get("auth_by_password_test", "account"),
                config.get("auth_by_password_test", "password") + "1234",
                config.get("auth_by_password_test", "account_by"),
                use_password=True,
                request_type="json",
            )

            self.assertEqual(response, None, "Authentication with a bad password" "was successful")
Пример #34
0
    def test_password_auth_failure_json(self):
        """ Send a configured auth request in json format using password based
        authentication and a wrong password and check the error
        """

        config = get_config()

        if config.getboolean("auth_by_password_test", "enabled"):

            # Run only if enabled

            response = authenticate(
                config.get("auth_by_password_test", "url"),
                config.get("auth_by_password_test", "account"),
                config.get("auth_by_password_test", "password") + "1234",
                config.get("auth_by_password_test", "account_by"),
                use_password=True,
                request_type="json")

            self.assertEqual(
                response, None, "Authentication with a bad password"
                "was successful")
Пример #35
0
        def test_auth_json(self):

            """ Send a configured auth request in json format and check a
            successfully returned token
            """

            config = get_config()

            if config.getboolean('auth_test', 'enabled'):

                # Run only if enabled

                try:

                    timestamp = config.getint('auth_test', 'timestamp')

                except ValueError:

                    # If timestamp is set to a none-integer, we'll just assume
                    # that it's unset

                    timestamp = None

                response = authenticate(
                    config.get('auth_test', 'url'),
                    config.get('auth_test', 'account'),
                    config.get('auth_test', 'preauthkey'),
                    config.get('auth_test', 'account_by'),
                    config.getint('auth_test', 'expires'),
                    timestamp,
                    request_type='json'
                )

                if response is None:

                    self.fail("Authentication with the configured settings "
                              "was not successful")
Пример #36
0
    def test_admin_auth_json(self):
        """ Send a configured admin auth request in json format using the
        admin auth-method and check a successfully returned token
        """

        config = get_config()

        if config.getboolean("admin_auth_test", "enabled"):

            # Run only if enabled

            response = authenticate(config.get("admin_auth_test", "admin_url"),
                                    config.get("admin_auth_test",
                                               "admin_account"),
                                    config.get("admin_auth_test",
                                               "admin_password"),
                                    config.get("admin_auth_test",
                                               "admin_account_by"),
                                    admin_auth=True,
                                    request_type="json")

            self.assertNotEqual(
                response, None, "Authentication with the configured settings "
                "was not successful")
Пример #37
0
    def test_password_auth_xml(self):
        """ Send a configured auth request in xml format using password
        based authentication and check a successfully returned token
        """

        config = get_config()

        if config.getboolean("auth_by_password_test", "enabled"):

            # Run only if enabled

            response = authenticate(config.get("auth_by_password_test", "url"),
                                    config.get("auth_by_password_test",
                                               "account"),
                                    config.get("auth_by_password_test",
                                               "password"),
                                    config.get("auth_by_password_test",
                                               "account_by"),
                                    use_password=True,
                                    request_type="xml")

            self.assertNotEqual(
                response, None, "Authentication with the configured settings "
                "was not successful")
    # Calculate the epoch-timestamps for Zimbra (in milliseconds)

    expand_start_epoch = calendar.timegm(expand_start.utctimetuple()) * 1000
    expand_end_epoch = calendar.timegm(expand_end.utctimetuple()) * 1000

    # Build up Zimbra communication

    url = "https://%s:7071/service/admin/soap" % server_name
    user_url = "https://%s/service/soap" % server_name

    comm = Communication(url)

    user_comm = Communication(user_url)

    token = auth.authenticate(url, admin_account, admin_password, admin_auth=True)

    if token is None:

        logging.error("Cannot login into zimbra with the supplied credentials.")

        exit(1)

    # Search for groupcal dictionaries

    search_request = comm.gen_request(token=token)

    search_request.add_request(
        "SearchDirectoryRequest", {"query": "uid=%s*" % options.prefix, "types": "distributionlists"}, "urn:zimbraAdmin"
    )
Пример #39
0
    def run_admin_test(self, request_type):

        """ Actually do the work
        """

        config = get_config()

        if config.getboolean("admin_request_test", "enabled"):

            # Run only if enabled

            token = authenticate(
                config.get("admin_request_test", "url"),
                config.get("admin_request_test", "account"),
                config.get("admin_request_test", "password"),
                config.get("admin_request_test", "account_by"),
                admin_auth=True,
                request_type=request_type
            )

            if token is None:

                self.fail("Authentication with the configured settings "
                          "was not successful")

            # Create an account

            comm = Communication(config.get("admin_request_test", "url"))

            if request_type == "xml":

                request = RequestXml()

            else:

                request = RequestJson()

            request.set_auth_token(token)

            request.add_request(
                "CreateAccountRequest",
                {
                    "name": config.get("admin_request_test", "test_account"),
                    "password": config.get(
                        "admin_request_test",
                        "test_password"
                    )
                },
                "urn:zimbraAdmin"
            )

            if request_type == "xml":

                response = ResponseXml()

            else:

                response = ResponseJson()

            comm.send_request(request, response)

            if response.is_fault():

                self.fail(
                    "CreateAccount faulted. %s" % (response.get_response())
                )

            account_id = response.get_response(
            )["CreateAccountResponse"]["account"]["id"]

            # Try to log in as the new account

            user_token = authenticate(
                config.get("admin_request_test", "user_url"),
                config.get("admin_request_test", "test_account"),
                config.get("admin_request_test", "test_password"),
                "name",
                request_type=request_type,
                use_password=True
            )

            if user_token is None:

                self.fail("Cannot log in as the test user.")

            # Remove account

            request.clean()
            response.clean()
            request.set_auth_token(token)

            request.add_request(
                "DeleteAccountRequest",
                {
                    "id": account_id
                },
                "urn:zimbraAdmin"
            )

            comm.send_request(request, response)

            if response.is_fault():

                self.fail(
                    "Cannot remove test account. %s" % response.get_response()
                )
Пример #40
0
 def get_token(self, url, user, secret, admin_auth):
     return auth.authenticate(
         url, user, secret, admin_auth=admin_auth)
Пример #41
0
        logging.basicConfig(level=logging.ERROR)
    elif options.debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)

    logging.debug("Starting followup-agent.")

    logging.debug("Authenticating as administrator to get users and domain "
                  "preauth")

    server_url = "https://%s:7071/service/admin/soap" % server_name

    comm = Communication(server_url)

    token = auth.authenticate(server_url,
                              admin_account, admin_password, admin_auth=True)

    users = []

    if options.distlist:

        logging.debug("Retrieving distribution list members from list %s" % (
            options.distlist
        ))

        get_members_request = comm.gen_request(token=token)
        get_members_request.add_request(
            "GetDistributionListRequest",
            {
                "dl": {
                    "_content": options.distlist,
Пример #42
0
    def test_genrequest_batch_xml(self):

        """ Create a batch-request only using the Communication-object (
            xml-version)
        """

        config = get_config()

        if config.getboolean("genrequest_test", "enabled"):

            # Run only if enabled

            comm = Communication(config.get("genrequest_test", "url"))

            token = authenticate(
                config.get("genrequest_test", "url"),
                config.get("genrequest_test", "account"),
                config.get("genrequest_test", "preauthkey")
            )

            self.assertNotEqual(
                token,
                None,
                "Cannot authenticate."
            )

            request = comm.gen_request(
                request_type="xml",
                token=token,
                set_batch=True
            )

            self.assertEqual(
                type(request),
                RequestXml,
                "Generated request wasn't an xml-request"
            )

            request.add_request(
                "NoOpRequest",
                {

                },
                "urn:zimbraMail"
            )

            request.add_request(
                "NoOpRequest",
                {

                },
                "urn:zimbraMail"
            )

            response = comm.send_request(request)

            if response.is_fault():

                self.fail(
                    "Reponse failed: (%s) %s" % (
                        response.get_fault_code(),
                        response.get_fault_message()
                    )
                )

            self.assertEqual(
                response.is_batch(),
                True,
                "Batch-request didn't return a Batch response."
            )

            expected_batch = {
                'nameToId': {
                    'NoOpResponse': [
                        '1',
                        '2'
                    ]
                },
                'hasFault': False,
                'idToName': {
                    '1': 'NoOpResponse',
                    '2': 'NoOpResponse'
                }
            }

            self.assertEqual(
                response.get_batch(),
                expected_batch,
                "Batch-dictionary wasn't expected"
            )
Пример #43
0
    def test_genrequest_check_response_batch_xml(self):

        """ Create a batch-request only using the Communication-object
        """

        config = get_config()

        if config.getboolean("genrequest_test", "enabled"):

            # Run only if enabled

            comm = Communication(config.get("genrequest_test", "url"))

            token = authenticate(
                config.get("genrequest_test", "url"),
                config.get("genrequest_test", "account"),
                config.get("genrequest_test", "preauthkey")
            )

            self.assertNotEqual(
                token,
                None,
                "Cannot authenticate."
            )

            request = comm.gen_request(
                request_type="xml",
                token=token,
                set_batch=True
            )

            self.assertEqual(
                type(request),
                RequestXml,
                "Generated request wasn't an json-request, which should be "
                "the default."
            )

            request.add_request(
                "NoOpRequest",
                {

                },
                "urn:zimbraMail"
            )

            request.add_request(
                "GetInfoRequest",
                {
                },
                "urn:zimbraAccount"
            )

            response = comm.send_request(request)

            if response.is_fault():

                self.fail(
                    "Reponse failed: (%s) %s" % (
                        response.get_fault_code(),
                        response.get_fault_message()
                    )
                )

            self.assertEqual(
                response.get_response(2)["GetInfoResponse"]["name"],
                config.get("genrequest_test", "account"),
                "Request returned unexpected response"
            )
Пример #44
0
    def run_admin_test(self, request_type):

        """ Actually do the work
        """

        config = get_config()

        if config.getboolean("admin_request_test", "enabled"):

            # Run only if enabled

            token = authenticate(
                config.get("admin_request_test", "admin_url"),
                config.get("admin_request_test", "admin_account"),
                config.get("admin_request_test", "admin_password"),
                config.get("admin_request_test", "admin_account_by"),
                admin_auth=True,
                request_type=request_type
            )

            if token is None:

                self.fail("Authentication with the configured settings "
                          "was not successful")

            # Create an account

            comm = Communication(config.get("admin_request_test", "admin_url"))

            if request_type == "xml":

                request = RequestXml()

            else:

                request = RequestJson()

            request.set_auth_token(token)

            test_account = config.get("admin_request_test", "test_account")

            if "TEMP" in test_account:

                # Generate a random number and add it to the test account

                random.seed()
                temp_account = random.randint(1000000, 5000000)

                test_account = test_account.replace("TEMP", str(temp_account))

            test_displayname = config.get(
                "admin_request_test",
                "test_displayname"
            )

            if sys.version < '3':

                # Create unicode string for py2

                test_displayname = test_displayname.decode("utf-8")

            request.add_request(
                "CreateAccountRequest",
                {
                    "name": test_account,
                    "password": config.get(
                        "admin_request_test",
                        "test_password"
                    ),
                    "a": {
                        "n": "displayName",
                        "_content": test_displayname
                    }
                },
                "urn:zimbraAdmin"
            )

            if request_type == "xml":

                response = ResponseXml()

            else:

                response = ResponseJson()

            comm.send_request(request, response)

            if response.is_fault():

                self.fail(
                    "CreateAccount faulted. (%s) %s" % (
                        response.get_fault_code(),
                        response.get_fault_message()
                    )
                )

            account_id = response.get_response(
            )["CreateAccountResponse"]["account"]["id"]

            # Get account from database and compare display name to the setting

            request.clean()
            request.set_auth_token(token)
            response.clean()

            request.add_request(
                "GetAccountRequest",
                {
                    "account": {
                        "by": "name",
                        "_content": test_account
                    }
                },
                "urn:zimbraAdmin"
            )

            comm.send_request(request, response)

            if response.is_fault():

                self.fail(
                    "GetAccount faulted. (%s) %s" % (
                        response.get_fault_code(),
                        response.get_fault_message()
                    )
                )

            returned_name = get_value(
                response.get_response()["GetAccountResponse"]["account"]["a"],
                "displayName"
            )

            self.assertEqual(
                returned_name,
                test_displayname,
                "Zimbra didn't save the display name as requested."
            )

            # Try to log in as the new account

            user_token = authenticate(
                config.get("admin_request_test", "url"),
                test_account,
                config.get("admin_request_test", "test_password"),
                "name",
                request_type=request_type,
                use_password=True
            )

            if user_token is None:

                self.fail("Cannot log in as the test user.")

            # Remove account

            request.clean()
            response.clean()
            request.set_auth_token(token)

            request.add_request(
                "DeleteAccountRequest",
                {
                    "id": account_id
                },
                "urn:zimbraAdmin"
            )

            comm.send_request(request, response)

            if response.is_fault():

                self.fail(
                    "Cannot remove test account: (%s) %s" % (
                        response.get_fault_code(),
                        response.get_fault_message()
                    )
                )
Пример #45
0
    def default(self):

        self.app.log.debug("Starting process.")

        self.url = self.app.pargs.url

        if self.url == "":

            self.url = "https://%s:7071/service/admin/soap" % \
                       self.app.pargs.host

        self.user_url = self.app.pargs.user_url

        if self.user_url == "":

            self.user_url = "https://%s/service/soap" % self.app.pargs.host

        if self.app.pargs.passwordfile:

            password = self.app.pargs.passwordfile.read().strip()

        else:

            password = self.app.pargs.password

        self.token = auth.authenticate(
            self.url,
            self.app.pargs.user,
            password,
            admin_auth=True
        )

        if self.token is None:

            self.app.log.fatal("Cannot login into zimbra")
            exit(1)

        # Read in approved file

        approved = self._read_approved()

        # Read in users

        userlist = self._get_scope()

        disapproved = {}

        for user in userlist:

            # Fetch the devices of the user

            devices = self._get_devices(user)

            # Check against approved devices

            for device in devices:

                found = False

                for approved_test in approved:

                    if re.search(approved_test["value"], device[
                            approved_test["selector"]]):

                        found = True

                if not found:

                    self.app.log.debug("Found disapproved device: %s" % device)

                    # Add device to the disapproved list

                    if user not in disapproved.keys():

                        disapproved[user] = []

                    disapproved[user].append(device)

        if len(disapproved.keys()) > 0:

            for key in disapproved.keys():

                print "=== %s ===\n" % key

                for device in disapproved[key]:

                    for device_key in device.keys():

                        print "%s: %s" % (device_key, device[device_key])

                    print ""
Пример #46
0
    def run_admin_test(self, request_type):
        """ Actually do the work
        """

        config = get_config()

        if config.getboolean("admin_request_test", "enabled"):

            # Run only if enabled

            token = authenticate(config.get("admin_request_test", "admin_url"),
                                 config.get("admin_request_test",
                                            "admin_account"),
                                 config.get("admin_request_test",
                                            "admin_password"),
                                 config.get("admin_request_test",
                                            "admin_account_by"),
                                 admin_auth=True,
                                 request_type=request_type)

            if token is None:

                self.fail("Authentication with the configured settings "
                          "was not successful")

            # Create an account

            comm = Communication(config.get("admin_request_test", "admin_url"))

            if request_type == "xml":

                request = RequestXml()

            else:

                request = RequestJson()

            request.set_auth_token(token)

            request.add_request(
                "CreateAccountRequest", {
                    "name": config.get("admin_request_test", "test_account"),
                    "password": config.get("admin_request_test",
                                           "test_password")
                }, "urn:zimbraAdmin")

            if request_type == "xml":

                response = ResponseXml()

            else:

                response = ResponseJson()

            comm.send_request(request, response)

            if response.is_fault():

                self.fail(
                    "CreateAccount faulted. (%s) %s" %
                    (response.get_fault_code(), response.get_fault_message()))

            account_id = response.get_response(
            )["CreateAccountResponse"]["account"]["id"]

            # Try to log in as the new account

            user_token = authenticate(config.get("admin_request_test", "url"),
                                      config.get("admin_request_test",
                                                 "test_account"),
                                      config.get("admin_request_test",
                                                 "test_password"),
                                      "name",
                                      request_type=request_type,
                                      use_password=True)

            if user_token is None:

                self.fail("Cannot log in as the test user.")

            # Remove account

            request.clean()
            response.clean()
            request.set_auth_token(token)

            request.add_request("DeleteAccountRequest", {"id": account_id},
                                "urn:zimbraAdmin")

            comm.send_request(request, response)

            if response.is_fault():

                self.fail(
                    "Cannot remove test account: (%s) %s" %
                    (response.get_fault_code(), response.get_fault_message()))
Пример #47
0
    def test_genrequest_batch_invalid_xml(self):

        """ Create a batchrequest only using the Communication-object,
            send it and request an invalid request id (xml)
        """

        config = get_config()

        if config.getboolean("genrequest_test", "enabled"):

            # Run only if enabled

            comm = Communication(config.get("genrequest_test", "url"))

            token = authenticate(
                config.get("genrequest_test", "url"),
                config.get("genrequest_test", "account"),
                config.get("genrequest_test", "preauthkey")
            )

            self.assertNotEqual(
                token,
                None,
                "Cannot authenticate."
            )

            request = comm.gen_request(
                request_type="xml",
                token=token,
                set_batch=True
            )

            self.assertEqual(
                type(request),
                RequestXml,
                "Generated request wasn't an json-request, which should be "
                "the default."
            )

            request.add_request(
                "NoOpRequest",
                {

                },
                "urn:zimbraMail"
            )

            request.add_request(
                "NoOpRequest",
                {

                },
                "urn:zimbraMail"
            )

            response = comm.send_request(request)

            if response.is_fault():

                self.fail(
                    "Reponse failed: (%s) %s" % (
                        response.get_fault_code(),
                        response.get_fault_message()
                    )
                )

            self.assertIsNone(
                response.get_response(3),
                "Querying an invalid requestId didn't return None"
            )
Пример #48
0
    def _get_devices(self, user):

        self.app.log.debug("Fetching devices of user %s" % user)

        (local_part, domain_part) = user.split("@")

        if domain_part not in self.preauth_cache:

            # No preauth key cached. Fetch one

            self.app.log.debug("Fetch preauth key for domain %s" % domain_part)

            comm = Communication(self.url)

            preauthkey_request = comm.gen_request(token=self.token)

            preauthkey_request.add_request(
                "GetDomainRequest",
                {
                    "domain": {
                        "by": "name",
                        "_content": domain_part
                    }
                },
                "urn:zimbraAdmin"
            )

            preauthkey_response = comm.send_request(preauthkey_request)

            if preauthkey_response.is_fault():

                self.app.log.fatal(
                    "Cannot fetch preauth key for domain %s" % domain_part,
                    preauthkey_response.get_fault_code(),
                    preauthkey_response.get_fault_message(),
                )

                exit(1)

            preauth = get_value(
                preauthkey_response.get_response()["GetDomainResponse"][
                    "domain"]["a"],
                "zimbraPreAuthKey"
            )

            if preauth is None:

                self.app.log.fatal(
                    "Domain %s has no preauthkey. Please use zmprov gdpak "
                    "<domain> first." % domain_part
                )

                exit(1)

            self.preauth_cache[domain_part] = preauth

        else:

            preauth = self.preauth_cache[domain_part]

        user_token = auth.authenticate(
            self.user_url,
            user,
            preauth
        )

        if user_token is None:

            self.app.log.fatal("Cannot login as user %s" % user)

            exit(1)

        user_comm = Communication(self.user_url)

        get_device_status_request = user_comm.gen_request(token=user_token)

        get_device_status_request.add_request(
            "GetDeviceStatusRequest",
            {},
            "urn:zimbraSync"
        )

        get_device_status_response = user_comm.send_request(
            get_device_status_request)

        if get_device_status_response.is_fault():

            self.app.log.fatal(
                "Cannot fetch devices for user %s: (%s) %s" % (
                    user,
                    get_device_status_response.get_fault_code(),
                    get_device_status_response.get_fault_message()
                )
            )

            exit(1)

        devices = []

        if "device" in get_device_status_response.get_response()[
                "GetDeviceStatusResponse"]:

            devices = get_device_status_response.get_response()[
                "GetDeviceStatusResponse"]["device"]

        if type(devices) == dict:

            devices = [devices]

        return devices