OpenAPI

Warning

KlAkOAPI Python Package is a wrapper over the regular REST API calls. I do NOT recommend its’ usage, because it does not cover all classes, parameters and attributes available.

Articles

Config / Auth

Access with OpenAPI requires 2 auth elements:

  • Local technical user account login/password (Basic Auth method)
  • KSC Server certificate verification (optional)

For KSC for Windows, server certificate is located at path: %ProgramData%\KasperskyLab\adminkit\1093\cert\klserver.cer Certificate needs to be copied to the machine, from which a script is run.

Login example

REST API Classic login:

import requests
import base64
import json
import urllib3
from pprint import pprint

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

ksc_server = "https://ksmm.demo.local:13299"
url = ksc_server + "/api/v1.0/login"
user = "user_api"
password = "P@ssw0rd"
data = {}

user = base64.b64encode(user.encode('utf-8')).decode("utf-8")
password = base64.b64encode(password.encode('utf-8')).decode("utf-8")
session = requests.Session()

auth_headers = {
    'Authorization': 'KSCBasic user="' + user + '", pass="' + password + '", internal="1"',
    'Content-Type': 'application/json',
}

response = session.post(url=url, headers=auth_headers, data=data, verify=False)
print(f'Server response = {response.status_code}')

KlAkOAPI Python Package Login:

import socket
import uuid
import datetime
from sys import platform
from KlAkOAPI.Params import KlAkArray, paramBinary, strToBin, dateTimeToStr
from KlAkOAPI.AdmServer import KlAkAdmServer

def GetServer():
    server_address = 'ksmm.demo.local'
    server_port = 13299
    server_url = 'https://' + server_address + ':' + str(server_port)
    
    username = 'user_api'
    password = 'P@ssw0rd'
    SSLVerifyCert = 'C:\\Lab\\klserver.cer'

    server = KlAkAdmServer.Create(server_url, username, password, verify = SSLVerifyCert)
    return server

# Call server login function:
server = GetServer()

Subsections of OpenAPI

OpenAPI - Certificates

Send a certificate created on KSC

This is a programmatic way to do Create Certificate -> Mail or VPN certificate (placed in User Certificate Store) -> Self-Signed Certificate from KSC. The certificate is generated on the KSC and send to a user and his device - to the device, where the specific user is the owner. User is chosen by his unique ID, ul_binId parameter. See List Users page for details on how to get unique user IDs.

userID = 'YbTpoXJ4XkSxzy5hcXm75w=='

url = ksc_server + "/api/v1.0/MdmCertCtrlApi.SetCertificateAsync2"
# "NSDomain" - Domain Auth 
# "CPKES" - certificate for OS Android
# "CTMail" - Mail certificate type
# "ul_binId" - paramBinary complex data with base64-encoded unique user ID

data = {'pAuthType':{'NSDomain': True},'pCertificate':{'CPKES':True, 'CTMail':True}, "pRecipient":{"ul_binId":{"type":"binary","value":userID}}}

response = session.post(url=url, headers=common_headers, data=json.dumps(data), verify=False)
wstrIteratorId = json.loads(response.text)

paramBinary

This is a complex data type with base64 encoded string data. Example:

import base64
paramBinary = {"type": "binary", "value": "c29tZXRleHQ="}
print(base64.b64decode("c29tZXRleHQ=")) # b'sometext'

This paramBinary type is used for transferring certificate PEM data, certificate password data etc. Note: although PFX container is supported in documentation, using it raises “cannot be JSON serialised” errors.

OpenAPI - List Data

List Data

SrvView Class, ResetIterator function is used to query and list inventory elements from KSC:

  • Choose a “view” type = which data to query (SrvView Views list link above). “GlobalUsersListSrvViewName” was chosen in the code below to query users and their unique IDs;
  • Choose which fields should be shown for the chosen View (for “GlobalUsersListSrvViewName”, available fields are listed in Users and groups list section). Display names (ul_wstrDisplayName) and unique IDs (ul_binId) are chosen fotr the example;
  • Get the record count - how many records are there to show. Use SrvView Class, GetRecordCount function for this;
  • Get the records themselves: Use SrvView Class, GetRecordRange function to provide the final records counting from the first record to the last, which was provided in the previous step.
data = {}

# CHOOSE VIEW TYPE, DATA FILEDS
url = ksc_server + "/api/v1.0/SrvView.ResetIterator"
data = {"wstrViewName": "GlobalUsersListSrvViewName", "vecFieldsToReturn": ["ul_wstrDisplayName","ul_binId"], "lifetimeSec": 3600}
response = session.post(url=url, headers=common_headers, data=json.dumps(data), verify=False)
wstrIteratorId = json.loads(response.text)['wstrIteratorId']

# FIGURE OUT THE NUMBER OF RECORDS AVAILABLE IN THE DATABASE
url = ksc_server + "/api/v1.0/SrvView.GetRecordCount"
data = {"wstrIteratorId": wstrIteratorId}
response = session.post(url=url, headers=common_headers, data=json.dumps(data), verify=False)
count = json.loads(response.text)
NUMBER_OF_RECORDS = int(count['PxgRetVal'])

# GET THE DATA ITSELF WITH ALL THE RESTRICTIONS PROVIDED EARLIER
url = ksc_server + "/api/v1.0/SrvView.GetRecordRange"
data = {"wstrIteratorId": wstrIteratorId, "nStart": 0, "nEnd": NUMBER_OF_RECORDS}
response = session.post(url=url, headers=common_headers, data=json.dumps(data), verify=False)
pRecords = json.loads(response.text)['pRecords']['KLCSP_ITERATOR_ARRAY']

# LIST THE DATA, FILTERING OUT EXTRA SYNTAX
for record in pRecords:
    print(f"{record['value']['ul_wstrDisplayName']} : {record['value']['ul_binId']['value']}" )