KSC Open API  13.0
Kaspersky Security Center API description
KlAkOAPI Python package

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

Installation

KlAkOAPI package is distributed along with this documentation as KlAkOAPI.tar.gz archive. The archive includes set of samples, i.e. python modules that use KlAkOAPI to perform some typical operations. Samples are supposed to be executed on machine where KSC server is installed. Connection to KSC server is performed by default with NTLM autentication.

To install KlAkOAPI package:

  1. (optional) Create python virtual environment and activate it. On Windows:

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

    on Unix or MacOS:

            >python3 -m venv klakoapi-env
            >source klakoapi-env/bin/activate
            

    Perform this step if you want to install KlAkOAPI package locally in virtual environmant 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 KlAkOAPI package system-wide.

  2. Install KlAkOAPI package:

            >pip install KlAkOAPI-1.0.0.0.tar.gz
            

    Dependency packages are to be installed automatically. However samples use additional packages to operate with AD. To install all the packages including ones used in samples:

            >pip install KlAkOAPI-1.0.0.0.tar.gz[samples]
            

  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 with use of KlAkOAPI package:
            >.\samples\sample_connect.py
            

Quick guide

Using KlAkOAPI package connection to KSC 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 KSC server is installed. If samples are executed on a machine where KSC server is installed, 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 KSC server. To execute samples the user should be created and granted with proper privileges in advance.
  • password - password to account used to connect to KSC server.
  • verify - path to KSC server's SSL certificate to verify connection. False can be used for unverified connection. Samples use "C:\\ProgramData\\KasperskyLab\\adminkit\\1093\\cert\\klserver.cer" that works on a machine with KSC server installed.
  • vserver - name of virtual server to connect. If vserver is None or empty strting, connection to main server is performed.

Using KlAkOAPI package connection to KSC 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 KSC server is installed. If samples are executed on a machine where KSC server is installed, 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 KSC server. To execute samples the user should be created and granted with proper privileges in advance.
  • password - password to account used to connect to KSC server.
  • verify - path to KSC server's SSL certificate to verify connection. False can be used for unverified connection. Samples use "C:\\ProgramData\\KasperskyLab\\adminkit\\1093\\cert\\klserver.cer" that works on a machine with KSC server installed.
  • vserver - name of virtual server to connect. If vserver is None or empty strting, connection to main server is performed.

Connection with token or web token authentication can be performed as well:

    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 KSC server is installed. If samples are executed on a machine where KSC server is installed, 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 KSC server's SSL certificate to verify connection. False can be used for unverified connection. Samples use "C:\\ProgramData\\KasperskyLab\\adminkit\\1093\\cert\\klserver.cer" that works on a machine with KSC server is installed.
  • vserver - name of virtual server to connect. If vserver is None or empty strting, connection to main server is performed.

To perform gateway connection refer to Creating gateway connections.

Further calls are performed with use of 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 has processed successfully, KLOAPI returns JSON object with Result. In KlAkOAPI package this object correspods to KlAkOAPI.KlAkBase.KlAkResponse object that has the following methods:

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

Otherwise if the requested method fails with some error, KLOAPI returns JSON object containing error description. KlAkOAPI package raises an exception of type KlAkOAPI.Error.KlAkError that has the following data members:

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

Params datatype of KLOAPI protocol corresponds to KlAkOAPI.Params.KlAkParams class. KlAkParams object can be composed either value 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 perfrom datatype casting from Python builtin datatypes into KLOAPI datatypes. However as far as Python can not distinguish int/long and double/float, explicit casting is needed sometimes. In the above sample paramLong converter is used explicitely to perfrom casting to paramLong KLOAPI datatype. Details about KLOAPI datatypes are described in KLOAPI types

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

  • data property contains a string with datatype issue description

Sample

Here is a sample of connection to KSC server installed on current machine and 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 KSC 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)