# Dynamic Connections

## Overview

Keeper Connection Manager can be configured to integrate with any custom software or 3rd party application using encrypted JSON files that simultaneously authenticate a user and grant them access to remote connections.

## Installation <a href="#id-.providingconnectiondatafromexternalapplicationsv2.x-installingsupportforencryptedjsonauthenticat" id="id-.providingconnectiondatafromexternalapplicationsv2.x-installingsupportforencryptedjsonauthenticat"></a>

The Dynamic Connections feature requires installation of the Encrypted JSON Authentication module for Keeper Connection Manager. To activate this feature, update the `JSON_*` parameters in the Docker Compose file in the [keeper/guacamole](https://docs.keeper.io/en/keeper-connection-manager/installation/docker-compose-install/keeper-guacamole) image.

`JSON_SECRET_KEY`

`JSON_TRUSTED_NETWORKS`

Activating these parameters loads an authentication extension for Keeper Connection Manager which authenticates users using JSON that have been signed using HMAC/SHA-256 and encrypted with AES-128 CBC. As this JSON contains all information describing the user being authenticated (including any connections they have access to), this extension can provide a simple means of integrating Keeper Connection Manager with external applications.

The `JSON_SECRET_KEY` must be 128 bits, specified as a 32-digit hexadecimal value, such as:

`4c0b569e4c96df157eee1b65dd0e4d41`

This key can be essentially anything as long as it is random. An easy way of generating such a key is to echo a passphrase through the "md5sum" utility. This is the technique OpenSSL itself uses to generate 128-bit keys from passphrases. For example:

```
echo -n "SomeRandomizedPassword" | md5sum
4c0b569e4c96df157eee1b65dd0e4d41
```

or using openssl directly ...

```
echo -n "SomeRandomizedPassword" | openssl md5
```

If encrypted JSON will only ever be received from a known set of machines or private subnets, you may wish to further restrict acceptance of received JSON to only those trusted machines using the `JSON_TRUSTED_NETWORKS` property. This field is a comma-separated list of trusted IP addresses and/or CIDR subnets. For example:

```
127.0.0.0/8, 10.0.0.0/8
```

### JSON format <a href="#id-.providingconnectiondatafromexternalapplicationsv2.x-jsonformat" id="id-.providingconnectiondatafromexternalapplicationsv2.x-jsonformat"></a>

The general format of the JSON (prior to being encrypted, signed, and sent to Keeper Connection Manager), is as follows:

```
{
    "username" : "someuser",
    "expires" : TIMESTAMP,
    "connections" : {
        "Connection Name" : {
            "protocol" : "PROTOCOL",
            "parameters" : {
                "name1" : "value1",
                "name2" : "value2",
                ...
            }
        },
        ...
    }
}
```

For example, if you want a JSON file that logs in as craig and instantly launches an SSH connection to a Linux server, the file might look like this:

{% code overflow="wrap" %}

```
{
    "username" : "craig",
    "expires" : "1740860895000",
    "connections" : {
        "Kali Linux Server" : {
            "protocol" : "ssh",
            "parameters" : {
                "hostname" : "192.168.1.2",
                "port" : "22",
                "username" : "kali",
                "private-key":"<contents of PEM encoded SSH key>"
            }
        }
    }
}
```

{% endcode %}

...where "expires" is a standard UNIX epoch timestamp with millisecond resolution (the number of milliseconds since midnight of January 1, 1970 UTC) and `PROTOCOL` is the internal name of any of Guacamole's supported protocols, such as `vnc`, `rdp`, or `ssh`.

As an example, to generate a timestamp that expires in 24 hours from now:

```
echo $(($(date -v+24H +%s) * 1000))
```

{% hint style="warning" %}
The JSON will cease to be accepted as valid after the server time passes the timestamp. If no timestamp is specified, the data will not expire. This can be desirable, but should only be done after careful consideration. In most cases, it is critical that a timestamp is specified, limiting the use of the encrypted JSON to some reasonable time interval and preventing replay attacks.
{% endhint %}

The top-level JSON object which must be submitted to Keeper Connection Manager has the following properties:

| Property name | Type     | Description                                                                                                                                                                                                                             |
| ------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `username`    | `string` | The unique username of the user authenticated by the JSON. If the user is anonymous, this should be the empty string (`""`).                                                                                                            |
| `expires`     | `number` | The absolute time after which the JSON should no longer be accepted, even if the signature is valid, as a standard UNIX epoch timestamp with millisecond resolution (the number of milliseconds since midnight of January 1, 1970 UTC). |
| `connections` | `object` | The set of connections which should be exposed to the user by their corresponding, unique names. If no connections will be exposed to the user, this can simply be an empty object (`{}`).                                              |

Each connection defined within each submitted JSON object has the following properties:

| Property name | Type     | Description                                                                                    |
| ------------- | -------- | ---------------------------------------------------------------------------------------------- |
| `protocol`    | `string` | The internal name of a supported protocol, such as `vnc`, `rdp`, `ssh,` etc.                   |
| `parameters`  | `object` | An object representing the connection parameter name/value pairs to apply to the connection \* |

(\*) A quick way to locate the name of a property is by inspecting the Keeper Connection Manager connection UI by right-clicking the field and inspecting the field DOM element "name":

<figure><img src="https://3357255970-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fb7weUpu7VBcMnESSH8vG%2Fuploads%2FKWC6TcQkrXUV1sZHe6lE%2FScreenshot%202025-02-28%20at%203.50.25%E2%80%AFPM.png?alt=media&#x26;token=b3ac9075-0b2a-48f0-9e67-38f03e327078" alt=""><figcaption><p>Inspecting the parameter names</p></figcaption></figure>

### Generating encrypted JSON <a href="#id-.providingconnectiondatafromexternalapplicationsv2.x-generatingencryptedjson" id="id-.providingconnectiondatafromexternalapplicationsv2.x-generatingencryptedjson"></a>

To authenticate a user with the above JSON format, the JSON must be both signed and encrypted using the same 128-bit secret key specified with the `JSON_SECRET_KEY` value in the Docker compose file.

1. Generate JSON in the format described above
2. Sign the JSON using the secret key (the same 128-bit key stored with the `JSON_SECRET_KEY` property) with HMAC/SHA-256. Prepend the binary result of the signing process to the plaintext JSON that was signed.
3. Encrypt the result of (2) above using AES in CBC mode, with the initial vector (IV) set to all zero bytes.
4. Encode the encrypted result using base64.
5. POST the encrypted result to the `/api/tokens` REST endpoint as the value of an HTTP parameter named `data` (or include it in the URL of any Keeper Connection Manager page as a query parameter named `data`).

For example, if Keeper is running on kcm.example.com and `BASE64_RESULT` is the result of the above process, the equivalent run of the "curl" utility would be:

{% code overflow="wrap" %}

```
$ curl --data-urlencode "data=BASE64_RESULT" https://kcm.example.com/api/tokens
```

{% endcode %}

{% hint style="warning" %}
Be sure to URL-encode the base64-encoded result prior to POSTing it to `/api/tokens` or including it in the URL. Base64 can contain both "+" and "=" characters, which have special meaning within URLs.
{% endhint %}

If the data is invalid in any way, if the signature does not match, if decryption or signature verification fails, or if the submitted data has expired, the REST service will return an invalid credentials error and fail without user-visible explanation. Details describing the error that occurred will be in the KCM logs.

### Reference implementation

The Apache Guacamole source code includes a shell script, [`doc/encrypt-json.sh`](https://raw.githubusercontent.com/apache/guacamole-client/master/extensions/guacamole-auth-json/doc/encrypt-json.sh), which uses the OpenSSL command-line utility to encrypt and sign JSON in the manner that guacamole-auth-json requires. It is thoroughly commented and should work well as a reference implementation, for testing, and as a point of comparison for development. The script is run as:

```
$ ./encrypt-json.sh <secret key> file-to-sign-and-encrypt.json
```

For example, if you have a file called `auth.json` containing the following:

```
{
    "username" : "test",
    "expires" : "1446323765000",
    "connections" : {
        "My Connection" : {
            "protocol" : "rdp",
            "parameters" : {
                "hostname" : "10.10.209.63",
                "port" : "3389",
                "ignore-cert": "true",
                "recording-path": "/recordings",
                "recording-name": "My-Connection-${GUAC_USERNAME}-${GUAC_DATE}-${GUAC_TIME}"
            }
        },
        "My OTHER Connection" : {
            "protocol" : "rdp",
            "parameters" : {
                "hostname" : "10.10.209.64",
                "port" : "3389",
                "ignore-cert": "true",
                "recording-path": "/recordings",
                "recording-name": "My-OTHER-Connection-${GUAC_USERNAME}-${GUAC_DATE}-${GUAC_TIME}"
            }
        }
    }
}
```

and you run:

```
$ ./encrypt-json.sh 4C0B569E4C96DF157EEE1B65DD0E4D41 auth.json
```

You will receive the following output:

```
A2Pf5Kpmm97I2DT1PifIrfU6q3yzoGcIbNXEd60WNangT8DAVjAl6luaqwhBJnCK
uqcf9ZZlRo3uDxTHvUM3eq1YvdghL0GbosOn8Mn38j2ydOMk+Cd15a8ggb4/ddt/
yIBK4DxrN7MNbouZ091KYtXC6m20E6sGzLy676BlMSg1cmsENRIihOynsSLSCvo0
diif6H7T+ZuIqF7B5SW+adGfMaHlfknlIvSpLGHhrIP4aMYE/ZU2vYNg8ez27sCS
wDBWu5lERtfCYFyU4ysjRU5Hyov+yKa+O7jcRYpw3N+fHbCg7/dxVNW07qNOKssv
pzUciGvDPUCPpa02WmPJNEBowwQireO1952/MNAI77cW2UepbljD/bwOiZl2THJz
LrENo7K5acimBa+EjWEesgn7lx/WTCF3zxR6TH1CWrQM8Et1aUK1Nf8K11xEQbTy
klyaNtCmTfyahRZ/fUPxDNrdJVpPOSELkf7RJO5tOdK/FFIFIbze3ZUyXgRq+pHY
owpgOmudDBTBlxhXiONdutRI/RZbFM/7GBMdmI8AR/401OCV3nsI4jLhukjMXH3V
f3pQg+xKMhi/QExHhDk8VTNYk7GurK4vgehn7HQ0oSGh8pGcmxB6W43cz+hyn6VQ
On6i90cSnIhRO8SysZt332LwJCDm7I+lBLaI8NVHU6bnAY1Axx5oH3YTKc4qzHls
HEAFYLkD6aHMvHkF3b798CMravjxiJV3m7hsXDbaFN6AFhn8GIkMRRrjuevfZ+q9
enWN14s24vt5OVg69DljzALobUNKUXFx69SR8EpSBvUcKq8s/OgbDpFvKbwsDY57
HGT4T0CuRIA0TGUI075uerKBNApVhuBA1BmWJIrI4JXw5MuX6pdBe+MYccO3vfo+
/frazj8rHdkDa/IbueMbvq+1ozV2+UuxrbaTrV2i4jSRgd74U0QzOh9e8Q0i7vOi
l3hnIfOfg+v1oULmZmJSeiAYWxeGvPptp+n7rNFqHGM=
```

{% hint style="info" %}
Don't include newlines when using this base64 blob...
{% endhint %}

The resulting base64 data above is the encrypted payload which will authenticate the user for the defined connections. If a single connection in the JSON is defined, the user will launch straight into the connection. If multiple connections are defined, or if the user is assigned connections, they will be provided with a list of choices.

There are two ways of launching into the connection manager using this encrypted base64 data.&#x20;

#### HTTP Post

If you are generating the request through an HTTP POST:

```
curl --data-urlencode "data=BASE64_RESULT" https://kcm.example.com/api/tokens
```

In Postman, you can test this through a POST request having `x-www-form-urlencoded` data:

<figure><img src="https://3357255970-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fb7weUpu7VBcMnESSH8vG%2Fuploads%2FmnmItFEfdiLbo4sElpkd%2FScreenshot%202025-02-28%20at%204.04.31%E2%80%AFPM.png?alt=media&#x26;token=35891831-4d20-4f95-b986-ca15ee6f4842" alt=""><figcaption><p>Testing with Postman</p></figcaption></figure>

#### HTTP Get

If you are trying to generate a URL for loading the connection in a browser through an HTTP GET request:

Strip the newlines and convert the base64 payload to a URL encoded string. The key transformations you need are:

* `+` becomes `%2B`
* `/` becomes `%2F`
* `=` becomes `%3D`

This can be converted through Python:

```
python3 -c "import urllib.parse; print(urllib.parse.quote('XXXX', safe=''))"
```

Then provide the URL encoded string as a `data` parameter in the URL for your server. For example:\
`https://my.kcmserver.com/?data=URL_ENCODED_BASE64_STRING`

When opening this in a browser, the connection is immediately authenticated and opened:

<figure><img src="https://3357255970-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fb7weUpu7VBcMnESSH8vG%2Fuploads%2FNaeWmR23SDye9uJXgsNe%2FScreenshot%202025-02-28%20at%204.13.43%E2%80%AFPM.png?alt=media&#x26;token=004bdc29-56ee-4ff1-97a2-46be31187b28" alt=""><figcaption><p>Dynamic Connection Opened</p></figcaption></figure>
