KSC Open API
Kaspersky Security Center API description
KlAkOAPI Python package

The KlAkOAPI Python package presents a wrapper library for interacting with the Administration Server via the Kaspersky Security Center Open API (KSC Open API). With this package, calls to Administration Server can be performed as calls for methods of provided classes. The params datatype is also represented as a class, along with the methods for parsing, composing, and re-composing its contents. The KlAkOAPI package requires Python 3.6 or higher.

Installation

The KlAkOAPI package is located in the same Kaspersky Security Center installation folder as the KlAkOAPI.tar.gz archive. The KlAkOAPI package a includes set of samples that perform typical operations. Samples are supposed to be executed on the machine where Administration Server is installed. Connection to Administration Server is performed by default by using NTLM authentication.

To install the KlAkOAPI package:

  1. (optional) Create a python virtual environment, and then activate it:

            >python3 -m venv klakoapi-env
            >klakoapi-env\Scripts\activate.bat
            

    Perform this step if you want to install the KlAkOAPI package locally in a virtual environment folder. Python creates a folder named "klakoapi-env" and further calls to Python affect this virtual environment only. Skip this step if you want to install the KlAkOAPI package system-wide.

  2. Install the KlAkOAPI package:

            >pip install KlAkOAPI-1.0.0.0.tar.gz
            

    The Pip tool downloads and installs dependency packages automatically from the PyPI server. Please note that the default PyPI server is located on https://pypi.org/, according to the default Python settings. You can setup your own PyPI server to prevent interaction with external sources on internet. Please refer to the Python documentation for details.

  3. (optional) Extract samples:

            >tar -xzf KlAkOAPI-1.0.0.0.tar.gz KlAkOAPI-1.0.0.0/samples/*
            

  4. Now, samples are ready to execute, as well as any modules written by using the KlAkOAPI package:
            >.\samples\sample_connect.py
            

Quick guide

Using the KlAkOAPI package connection to Administration Server is performed by using the following static method:

    server = KlAkOAPI.AdmServer.KlAkAdmServer.Create(server_url, username, password, verify = False, vserver = 'vs1')
    

The arguments are as follows:

  • server_url - address where Administration Server is installed. If samples are executed on a machine where Administration Server is installed, the FQDN of the current machine is used along with the default KLOAPI port number: https://machine.domain:13299.
  • username - account username used to connect to Administration Server. To execute samples, the user should be created and granted with proper privileges in advance.
  • password - password to the account used to connect to Administration Server.
  • verify - path to the Administration Server's SSL certificate to verify the connection. False can be used for an unverified connection. Samples use "C:\\ProgramData\\KasperskyLab\\adminkit\\1093\\cert\\klserver.cer" that works on a machine with Administration Server installed.
  • vserver - name of the virtual server to connect. If vserver is None or an empty string, a connection to the main server is performed.

Using the KlAkOAPI package connection to Administration Server is performed with the following static method:

    server = KlAkOAPI.AdmServer.KlAkAdmServer.Create(server_url, username, password, verify = False, vserver = 'vs1')
    

The arguments are as follows:

  • server_url - address where Administration Server is installed. If samples are executed on a machine where Administration Server is installed, the FQDN of the current machine is used along with the default KLOAPI port number: https://machine.domain:13299.
  • username - account username used to connect to Administration Server. To execute samples, the user should be created and granted with proper privileges in advance.
  • password - password to the account used to connect to Administration Server.
  • verify - path to the Administration Server's SSL certificate to verify connection. False can be used for unverified connection. Samples use C:\ProgramData\KasperskyLab\adminkit\1093\cert\klserver.cer which works on the machine with Administration Server installed.
  • vserver - name of the virtual server to connect. If vserver is None or an empty string, connection to the main server is performed.

A connection that uses a token or web token authentication can be performed as well, by using the following methods:

    server = KlAkOAPI.AdmServer.KlAkAdmServer.CreateByToken(server_url, token, verify = False, vserver = 'vs1')
    

and

    server = KlAkOAPI.AdmServer.KlAkAdmServer.CreateByWebToken(server_url, token, verify = False, vserver = 'vs1')
    

The arguments in both calls are similar:

  • server_url - address where Administration Server is installed. If samples are executed on a machine where Administration Server is installed, the FQDN of the current machine is used along with the default KLOAPI port number: https://machine.domain:13299.
  • token - token or web token string.
  • verify - path to the Administration Server's SSL certificate, to verify the connection. False can be used for an unverified connection. Samples use C:\ProgramData\KasperskyLab\adminkit\1093\cert\klserver.cer which works on the machine with Administration Server installed.
  • vserver - name of the virtual server to connect. If vserver is None or an empty string, a connection to the main server is performed.

To perform a gateway connection, refer to Creating gateway connections.

Further calls are performed by using a server object:

    # create object correspondent to KLOAPI interface
    oHostGroup = KlAkOAPI.HostGroup.KlAkHostGroup(server)
    # call method
    res = oHostGroup.FindGroups('', vecFieldsToReturn=['id', 'name', 'grp_full_name', 'parentId', 'level'], vecFieldsToOrder = [], pParams = {'KLGRP_FIND_FROM_CUR_VS_ONLY': True}, lMaxLifeTime=100)
    # refer to return value
    print('Found ' + str(res.RetVal()) + ' groups on server.')    
    

If the requested method is processed successfully, KLOAPI returns a JSON object with the Result. In the KlAkOAPI package, this object corresponds to the KlAkOAPI.KlAkBase.KlAkResponse object, which has the following methods:

  • RetVal() - returns the return value ("PxgRetVal" field) cast to the proper Python datatype. In the sample above, res.RetVal() is the int value for the number of found groups.
  • OutPars() - returns a dictionary of the output parameters in the form {output_parameter_name: output_parameter_value}. Values are cast to the proper Python datatypes.
  • OutPar(output_parameter_name) - returns the value of the output parameter with the name output_parameter_name cast to the proper Python datatype. In the sample above, res.OutPar('strAccessor') is a string value for the result-set ID, which identifies the server-side ordered collection of found groups.

Otherwise, if the requested method fails with an error, KLOAPI returns a JSON object containing the error description. The KlAkOAPI package raises an exception of the KlAkOAPI.Error.KlAkError type which has the following properties:

  • data - contains a string in the JSON format, corresponding to a raw response body from the KLOAPI protocol. Other fields of KlAkError are:
  • code - contains a code of the error.
  • subcode - contains a subcode of the error (starting with Kaspersky Security Center version 12.2).
  • module - contains a binary module name.
  • file - contains the source file name.
  • line - contains the line number where the exception occurs.
  • message - contains a non-localized error message.
  • locdata - contains a dictionary with localized information about the error. Optional.
  • loc_message - contains a formatted localized error message, in the case when locdata is not empty.

The params datatype of the KLOAPI protocol corresponds to the KlAkOAPI.Params.KlAkParams class. The KlAkParams object can be composed either by values or transformed from a dictionary:

    oPar = KlAkOAPI.Params.KlAkParams({})
    oPar.AddString('key_name_1', 'key_value')
    oPar.AddLong('key_name_2', 1234)
    oPar.AddBinary('key_name_3', b'1234')
    # as Python does not distinguish int and long datatypes, further sample should use converter to long explicitly
    oParCopy = KlAkOAPI.Params.KlAkParams({'key_name_1': 'key_value', 'key_name_2': KlAkOAPI.Params.paramLong(1234), 'key_name_3': b'1234'})
    

KlAkParams tries to perform datatype casting from the Python built-in datatypes into KLOAPI datatypes. However as far as Python cannot distinguish between int/long and double/float, explicit casting is sometimes needed. In the sample above, the paramLong converter is used explicitly to perform casting to the paramLong KLOAPI datatype. Details about KLOAPI datatypes are described in The KLOAPI types.

If KlAkParams fails to perform datatype casting, it raises the KlAkOAPI.Error.KlAkParamTypeError exception type, with the following data members:

  • data - contains a string with a description of the datatype issue description.

Sample

Here is a sample of a connection to Administration Server installed on a current machine and the printing its groups:

    import socket
    import KlAkOAPI.AdmServer
    import KlAkOAPI.HostGroup

    def main():
        # server details - connect to server installed on current machine
        server_address = socket.getfqdn()
        server_port = 13299
        server_url = 'https://' + server_address + ':' + str(server_port)

        # account for connecting server - user 'test' with password 'test1234!' should be created on Administration Server in advance
        username = 'test'
        password = 'test1234!'

        # create server object
        server = KlAkOAPI.AdmServer.KlAkAdmServer.Create(server_url, username, password, verify = 'C:\\ProgramData\\KasperskyLab\\adminkit\\1093\\cert\\klserver.cer')

        # create object correspondent to OpenAPI interface
        oHostGroup = KlAkOAPI.HostGroup.KlAkHostGroup(server)
        
        # find all groups on current server and print them
        res = oHostGroup.FindGroups('', vecFieldsToReturn=['id', 'name', 'grp_full_name', 'parentId', 'level'], vecFieldsToOrder = [], pParams = {'KLGRP_FIND_FROM_CUR_VS_ONLY': True}, lMaxLifeTime=100)
        print('Found ' + str(res.RetVal()) + ' groups on server:')    
        
        strAccessor = res.OutPar('strAccessor')
            
        # chunkAccessor object allows iteration over search results
        chunkAccessor = KlAkOAPI.ChunkAccessor.KlAkChunkAccessor (server)
        nItemsCount = chunkAccessor.GetItemsCount(strAccessor).RetVal()
        nStart = 0
        nStep = 20000
        while nStart < nItemsCount:        
            pChunk = chunkAccessor.GetItemsChunk(strAccessor, nStart, nStep).OutPar('pChunk')
            for parGroup in pChunk['KLCSP_ITERATOR_ARRAY']:
                print (parGroup['grp_full_name'])
            nStart += nStep
            
        chunkAccessor.Release(strAccessor)