Jump to content

0xcffaedfe

Members
  • Posts

    11
  • Joined

  • Last visited

    Never

Posts posted by 0xcffaedfe

  1. Hello everyone!!

     

    I come back on this topic because I was trying to use OpenApi to get some info on the devices managed by my KSC but I have problem calling login API.

    The error I get is 401 Unauthorized, that (reading the documentation available on the KSC) seems to be casued by a wrong formatted header.

     

    Here below I post my code (vb.net):

    WReq = CType(WebRequest.Create("https://" + ksc + ":13299/api/v1.0/login"), HttpWebRequest)

            ksc_u_b64 = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ksc_u)).ToString()
            ksc_p_b64 = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ksc_p)).ToString()
            ksc_h_b64 = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ksc_h)).ToString()

            WReq.Headers.Add("Authorization", "KSCBasic user=" + ksc_u_b64 + ", pass=" + ksc_p_b64)
            'WReq.Headers.Add("X-KSC-VServer", ksc_h_b64)

            WReq.Method = "POST"
            WReq.ProtocolVersion = HttpVersion.Version11
            WReq.ContentType = "application/json"
            'WReq.ContentLength = 2
            System.Net.ServicePointManager.Expect100Continue = False
            WReq.Timeout = 12000000

            Dim jsonBytes = Encoding.UTF8.GetBytes("{}")
            WReq.ContentLength = jsonBytes.Length
            Using reqStream = WReq.GetRequestStream()
                reqStream.Write(jsonBytes, 0, jsonBytes.Length)
            End Using

            WResp = CType(WReq.GetResponse(), HttpWebResponse)

     

    ksc = ip_address of my KSC

    ksc_u_b64 = user base64 encoded (I am using a domain admin user, in order to be sure to have the permission

    ksc_p_b64 = password base64 encoded

     

    I have also tried passiong user and password with “”, as well I have also tried passing the parameter internal="1"  (I have made a try with =”0” too) and tried also passing the parameter X-KSC-VServer (the variable ksc_h_b64 in my code) but with no luck :(

     

    Could you please help me out solving the problem? I have no idea where to turn my head.

     

    Thank you in advance

     

    Cheers

    Matteo

     

     

     

     

    1. Skip (CertificateValidation)!

         ServicePointManager.ServerCertificateValidationCallback = Function(se As Object, cert As X509Certificate,
            chain As X509Chain, sslerror As SslPolicyErrors) True

     


       2. Escape Double! (Name\Password hash must be quoted!)

    request.Headers.Add("Authorization", "KSCBasic user=""" + ksc_u_b64 + """, pass=""" + ksc_p_b64 + """")

  2. Скрипт на PowerShell 5.1

    $ksc_server = "https://server:13299"
    $url = $ksc_server + "/api/v1.0/login"
    $user = 'domain\user'
    $password = '******'
    $user = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($user))
    $password = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($password))

    $parameters = @{
        Uri         = $url
        Headers     = @{ 'Authorization' = 'KSCBasic user=$user, pass=$password' }
        Method      = 'POST'
        ContentType = 'application/json'
    }

    Invoke-RestMethod @parameters

    Выдает ошибку : 

    Invoke-RestMethod : Authentication header is invalid - не могу понять, в чем проблема ?

     

    Проблема в неправильном хедере логин и пасс передаются в кавычках:

        Headers     = @{ 'Authorization' = "KSCBasic user=`"$user`", pass=`"$password`"" }

     

    ну и на всякий скинуть проверку cерта: Invoke-RestMethod @parameters -SkipCertificateCheck 

  3.     Hello @ 0xcffaedfe   
       to do a quick test, I put the two curl calls one below the other, but the result hasn't changed.
       as a first answer I got:

    HTTP Status Code: 200 Response Body: {"strAccessor":"Lxt1En2LCqqa45K4X0WeD2","PxgRetVal":20}

     

     

    as a second answer I get:

     

    HTTP Status Code: 200 Response Body: {"PxgError":{"code":1186,"file":"c:\\a\\b\\a_32ba8ed2\\s\\csadminkit\\development2\\std\\tmstg\\timeoutstore.cpp","line":211,"message":"Object \"Lxt1En2LCqqa45K4X0WeD2\" is absent","module":"KLSTD"}}

     

     

        how can i keep the session open? i tried to increase LMaxLifeTime too, but the result hasn't changed

    :(

     

     

    think u should use another auth method.

    <?php

    // get cURL resource
    $ch = curl_init();

    // set url
    curl_setopt($ch, CURLOPT_URL, 'https://ip:13299/api/v1.0/Session.StartSession'); // <-!

    // set method
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

    // return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // set headers
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: KSCBasic user="login", pass="pass"',
    'X-KSC-VServer: x',
    'Content-Type: application/json; charset=utf-8',
    ]);

    // json body
    $json_array = [

    ];
    $body = json_encode($json_array);

    // set body
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

    // send the request and save response to $response
    $response = curl_exec($ch);

    // stop if fails
    if (!$response) {
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
    }

    echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
    echo 'Response Body: ' . $response . PHP_EOL;

    // close curl resource to free up system resources
    curl_close($ch);

     

    server response will be as example: {"PxgRetVal":"nngQKNEDkx9E6Pe63Be8eOQ=="}

    u should user this token in header with key:  X-KSC-Session

    <?php

    // get cURL resource
    $ch = curl_init();

    // set url
    curl_setopt($ch, CURLOPT_URL, 'https://ip:13299/api/v1.0/HostGroup.FindGroups');

    // set method
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

    // return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // set headers
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'X-KSC-VServer: x',
    'X-KSC-Session: n9M8NjkzZUADIgn5wnKCkZA==', // !< - Auth token received from Session.StartSession
    'Content-Type: application/json; charset=utf-8',
    ]);

    // json body
    $json_array = [
    'vecFieldsToOrder' => null,
    'pParams' => [
    'KLGRP_FIND_FROM_CUR_VS_ONLY' => true,
    'KLSRVH_SLAVE_REC_DEPTH' => 0
    ],
    'vecFieldsToReturn' => [
    'id',
    'name',
    'grp_full_name',
    'creationDate',
    'KLGRP_CHLDHST_CNT',
    'KLSRV_HSTSTAT_CRITICAL',
    'KLSRV_HSTSTAT_WARNING'
    ],
    'lMaxLifeTime' => 100,
    'wstrFilter' => '
    (&
    (!"KLGRP_CHLDHST_CNT" = 0)
    (!"grp_from_unassigned" = true)
    )'
    ];
    $body = json_encode($json_array);

    // set body
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

    // send the request and save response to $response
    $response = curl_exec($ch);

    // stop if fails
    if (!$response) {
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
    }

    echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
    echo 'Response Body: ' . $response . PHP_EOL;

    // close curl resource to free up system resources
    curl_close($ch);

     

     

    but this token expires in 3 minutes =)

  4. as one of the solutions you can create a category in gui ksc read it through api and see how the fields you need look like.

    working example below... 

    very simple example 

    {
    "pCategory" : {
    "CategoryType" : 0,
    "CustomCategoryCipCompatible" : false,
    "Md5WithoutSha256Exists" : false,
    "exclusions" : [],
    "fromMaster" : false,
    "inclusions" : [
    {
    "type" : "params",
    "value" : {
    "ex_type" : 0,
    "str" : "text",
    "str_op" : 3
    }
    }
    ],
    "name" : "test",
    "descr" : "test2",
    "version" : 65535
    }
    }

     

     

     

      client.FileCategorizer2.CreateCategory(ctx, kaspersky.CategoryParams{
    PCategory: &kaspersky.PCategory{
    CategoryType: 0,
    CustomCategoryCipCompatible: false,
    Md5WithoutSha256Exists: false,
    Exclusions: []kaspersky.Exclusions{},
    FromMaster: false,
    Inclusions: []kaspersky.Inclusion{
    {
    Type: "params",
    InclusionValue: &kaspersky.InclusionValue{
    ExType: 0,
    Str: "text",
    StrOp: 3,
    },
    },

    },
    Name: "test",
    Descr: "test2",
    Version: 65535,
    }})

     

     

  5.   Hello @0xcffaedfe  thank you for your answer, I understand where I went wrong.

    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: KSCBasic user="dfahdushasda=", pass="afdsaedafafa=", internal="1"']);

     

    I saw that no token is issued to me, so for further requests I used the session method with cookies

     

    adding these lines

    curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);  
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);

     

    I finally got the 200 code

     

     

    so I tried to make a new request, to get to know the groups

    -------------------------------------------------------------------------------------------------------------

    $url = $ksc_server."/api/v1.0/HostGroup.FindGroups";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);


    $data_string = '{"wstrFilter": "", "vecFieldsToReturn": ["id", "name"], "lMaxLifeTime": 1000}';


    curl_setopt($ch, CURLOPT_HTTPHEADER, ['"Content-Type": "application/json"']);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array());
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    echo $result=curl_exec($ch);
    echo "<br>status Code: ". curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($result === false) {
        die('Error fetching data: ' . curl_error($ch));
    }
    $array=json_decode($result);
    print_r($array);

    curl_close($ch);

    -------------------------------------------------------------------------------

     

     

    this is the result:

    status Code: 0

    Error fetching data: Empty reply from server

     

     

    what am i doing wrong now?

     

     

     

     

     

     

     

     

     

     

    I think this is superfluous:


    curl_setopt($ch, CURLOPT_HTTPHEADER, ['"Content-Type": "application/json"']);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array());

    working example below

     

    <?php

    // get cURL resource
    $ch = curl_init();

    // set url
    curl_setopt($ch, CURLOPT_URL, 'https://ksc_ip:13299/api/v1.0/HostGroup.FindGroups');

    // set method
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

    // return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // set headers
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: KSCBasic user="login_hash", pass="pass_hash"',
    'X-KSC-VServer: x',
    'Content-Type: application/json; charset=utf-8',
    ]);

    // json body
    $json_array = [
    'vecFieldsToOrder' => null,
    'pParams' => [
    'KLGRP_FIND_FROM_CUR_VS_ONLY' => true,
    'KLSRVH_SLAVE_REC_DEPTH' => 0
    ],
    'vecFieldsToReturn' => [
    'id',
    'name',
    'grp_full_name',
    'creationDate',
    'KLGRP_CHLDHST_CNT',
    'KLSRV_HSTSTAT_CRITICAL',
    'KLSRV_HSTSTAT_WARNING'
    ],
    'lMaxLifeTime' => 100,
    'wstrFilter' => '
    (&
    (!"KLGRP_CHLDHST_CNT" = 0)
    (!"grp_from_unassigned" = true)
    )'
    ];
    $body = json_encode($json_array);

    // set body
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);


    // send the request and save response to $response
    $response = curl_exec($ch);

    // stop if fails
    if (!$response) {
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
    }

    echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
    echo 'Response Body: ' . $response . PHP_EOL;

    // close curl resource to free up system resources
    curl_close($ch);

     

     

  6. <?php

    // get cURL resource
    $ch = curl_init();

    // set url
    curl_setopt($ch, CURLOPT_URL, 'https://you_ip:13299/api/v1.0/login');

    // set method
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

    // return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // set headers
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'Authorization: KSCBasic user="login", pass="pass"',
      ‘X-KSC-VServer: x',
    ]);

    $response = curl_exec($ch);

    // stop if fails
    if (!$response) {
      die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
    }

    echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
    echo 'Response Body: ' . $response . PHP_EOL;

    curl_close($ch);

     

    worked…

     

    also I`ll now writing client library for accessing the KSC, you can see how certain elements work.

    Here

×
×
  • Create New...