# Remote Access for CanKingService

This document explains how to enable remote (network) access to `CanKingService` on Linux and Windows. It covers generating a TLS certificate, configuring `CanKingService` to use it, opening firewall ports, setting up clients, and verifying connectivity.

For a short step-by-step walkthrough, see [Remote Access — Quick Setup Guide](./REMOTE_ACCESS_QUICKSTART.md).

## Prerequisites

- `CanKingService` installed and running as a system service (the `canking` systemd unit on Linux, the `CanKing` Windows service on Windows).
- The `ck` CLI on the service host (used for the recommended `ck remote` setup).
- Optionally `openssl` (Linux/macOS) or PowerShell (Windows) if you want to create or inspect certificates manually.

## How remote access works

- Remote clients connect over HTTPS/HTTP/2 (gRPC) to a TCP port on the service host (default `36701`). Kestrel listens on all interfaces when remote connections are enabled.
- The listener requires a PKCS#12/PFX certificate. Without a certificate no TCP listener is started and only local IPC (named pipe on Windows, Unix socket on Linux) is available.
- **An API key is mandatory for remote access.** Every call over TCP must carry the shared secret in the `x-api-key` gRPC metadata header. If no API key is configured on the service, all remote calls are rejected with `Unauthenticated` ("Remote access is not available."). Local IPC connections never need a key.
- **Remote access can only be configured locally, by an administrator.** Enabling or disabling remote access and generating certificates (`ck remote enable`, `ck remote disable`, `ck remote generate-cert`) are accepted only over local IPC from root on Linux (run with `sudo`) or from an elevated Administrator prompt on Windows. They are refused for remote clients, whatever API key they supply.
- **Remote clients only reach files under `FileAccessRootPath`.** This applies to the file system browser and to every file a remote client makes the service read or write on the host: log files, log replay files, databases and extension packages. Paths outside it, including through symbolic links, are refused with `PermissionDenied`.

## Key configuration knobs

Configuration section: `CanKingService` in `appsettings.json` (see `CanKingServiceOptions.Section`).

| Option | Description |
| --- | --- |
| `EnableRemoteConnections` (bool) | Listen for remote connections on all interfaces. Default `false`. |
| `RemoteConnectionPort` (int) | Port for the remote HTTPS listener. Default `36701`. |
| `TlsCertPath` (string) | Path to the PKCS#12/PFX certificate file. |
| `TlsCertPassword` (string) | Password for the PFX file (optional). Prefer `CANKING_TLS_CERT_PASS`. |
| `RemoteApiKey` (string) | Shared secret remote clients must supply. Prefer `CANKING_REMOTE_API_KEY`. |
| `FileAccessRootPath` (string) | Restricts remote clients to this directory and its descendants: the file system browser and any file a remote client makes the service read or write. Defaults to `/usr/share/Kvaser/CanKing/shared-files` on Linux and `C:\ProgramData\Kvaser\CanKing\shared-files` on Windows. |

### Environment variables

The service reads these environment variables, which take precedence over the values in `appsettings.json`:

| Environment variable | Overrides |
| --- | --- |
| `CANKING_ENABLE_REMOTE` | `EnableRemoteConnections` |
| `CANKING_REMOTE_PORT` | `RemoteConnectionPort` |
| `CANKING_TLS_CERT_PATH` | `TlsCertPath` |
| `CANKING_TLS_CERT_PASS` | `TlsCertPassword` |
| `CANKING_REMOTE_API_KEY` | `RemoteApiKey` |

Because `CanKingService` is built on `WebApplication.CreateBuilder`, every `appsettings.json` key can also be overridden with the standard .NET form using `__` as the section separator, for example `CanKingService__FileAccessRootPath`. The `CANKING_*` aliases above always win over the `CanKingService__*` form.

> **Replace placeholder values before use.** The examples below use `YOUR_HOSTNAME`, `MySecret`, and `a-strong-secret` as placeholders. Substitute your actual hostname/IP, a strong unique PFX password, and a long random API key before running any command in a production or shared environment.

## Recommended setup using `ck remote` commands

The `ck remote` sub-commands configure everything in one go: certificate, `appsettings.json`, secrets, firewall, and service restart. They talk to the **local** `CanKingService`, so run them on the machine that hosts the service, as root on Linux (`sudo ck remote ...`) or from an elevated prompt (**Run as administrator**) on Windows. Otherwise the service answers `PermissionDenied`.

> **Note:** If `CANKING_REMOTE_URL` is set in your shell, `ck` sends the command to that host instead. Unset it, or add `--url localhost`, when you run `ck remote` commands.

### 1. Generate a self-signed TLS certificate

```bash
sudo ck remote generate-cert YOUR_HOSTNAME
```

| Option | Description |
| --- | --- |
| `HOSTNAME` (required) | DNS hostname or IP address the certificate is issued for. |
| `--ip <IP>` | Additional IP address SAN, useful if clients connect by IP as well as by name. |
| `--output <path>` / `-o` | Where the service saves the PFX. Defaults to `/usr/share/Kvaser/CanKing/ca-certificates` on Linux and `C:\ProgramData\Kvaser\CanKing\ca-certificates` on Windows. A path without a `.pfx` extension is treated as a directory and the file is named `<HOSTNAME>.pfx`. |
| `--pem-output <path>` | Where `ck` saves the public certificate. Defaults to `<HOSTNAME>.pem` in the current directory. A path without a `.pem` extension is treated as a directory. |
| `--password <pass>` / `-p` | Password protecting the PFX. If omitted, the PFX has no password. |
| `--days <n>` | Validity period in days. Default `730`. |

Examples:

```bash
# Minimal — hostname only
sudo ck remote generate-cert myserver.example.com

# With IP SAN, password and custom validity
sudo ck remote generate-cert myserver.example.com --ip 192.168.1.10 --password MySecret --days 365
```

The command produces two files:

- `<HOSTNAME>.pfx` — the server certificate with its private key. It stays on the server (on Linux it is created with mode `0600`).
- `<HOSTNAME>.pem` — the public certificate. Copy it to every client that should trust this server (see [Client-side setup](#client-side-setup)).

The generated certificate is a self-signed RSA 2048 / SHA-256 certificate marked as a CA, so it can be installed directly as a trusted root on clients.

### 2. Enable remote connections

```bash
sudo ck remote enable --cert-path /usr/share/Kvaser/CanKing/ca-certificates/myserver.example.com.pfx \
  --service-api-key a-strong-secret
```

| Option | Description |
| --- | --- |
| `--cert-path <path>` (required) | Path to the PFX file on the service host. The file must exist. |
| `--service-api-key <key>` (required) | Shared secret remote clients must supply in the `x-api-key` header. 1–256 printable ASCII characters, not including `"` `'` `\` `` ` `` `$` or `%`. |
| `--cert-password <pass>` | Password for the PFX, if one was set during generation. Same character rules as the API key. |
| `--port <n>` | Port for the remote HTTPS listener. Default `36701`. |
| `--filesystem-root <dir>` | Restrict the file system browser to this directory. Defaults to `/usr/share/Kvaser/CanKing/shared-files` on Linux and `C:\ProgramData\Kvaser\CanKing\shared-files` on Windows. |

Examples:

```bash
# Linux — with password, custom port and restricted file access
sudo ck remote enable --cert-path /usr/share/Kvaser/CanKing/ca-certificates/myserver.example.com.pfx \
  --cert-password MySecret --port 36701 \
  --service-api-key a-strong-secret --filesystem-root /srv/canking/data
```

```powershell
# Windows PowerShell — with password and API key
ck remote enable --cert-path "C:\ProgramData\Kvaser\CanKing\ca-certificates\myserver.example.com.pfx" `
  --cert-password MySecret --port 36701 --service-api-key a-strong-secret
```

What the command does on the service host:

1. Writes `EnableRemoteConnections`, `TlsCertPath`, `RemoteConnectionPort` and (if given) `FileAccessRootPath` to the service's `appsettings.json`. Any `RemoteApiKey` / `TlsCertPassword` entries are removed from the file.
2. Stores the secrets (`CANKING_REMOTE_API_KEY`, `CANKING_TLS_CERT_PASS`) in the service environment instead of in `appsettings.json`:
   - **Windows:** the `Environment` value of the service registry key `HKLM\SYSTEM\CurrentControlSet\Services\CanKing`.
   - **Linux:** the systemd drop-in `/etc/systemd/system/canking.service.d/secrets.conf` (mode `0600`), followed by `systemctl daemon-reload`.
3. Opens the port in the firewall:
   - **Windows:** a `netsh advfirewall` inbound rule named `CanKing Remote Access`.
   - **Linux:** the first available of `ufw`, `firewall-cmd` (firewalld) or `iptables`. Rules added with `iptables` are not persisted across reboots.
4. Restarts `CanKingService`.

If a step fails (for example because of missing permissions or no supported firewall tool), it is logged as a warning in the service log and you need to complete that step manually.

### 3. Disable remote connections

```bash
sudo ck remote disable
```

This sets `EnableRemoteConnections` to `false`, clears `TlsCertPath` and `FileAccessRootPath`, removes the stored secrets and the firewall rule, and restarts `CanKingService`.

---

## Manual setup (alternative)

Use the steps below if you need to integrate with an existing PKI, require CA-signed certificates, or want to manage the configuration yourself. Alternatively, create the PFX manually and then run `ck remote enable` to apply the configuration.

### Linux (OpenSSL)

1. Create a private key and a self-signed certificate with SANs. Replace `YOUR_HOSTNAME` and the IP:

```bash
openssl req -x509 -newkey rsa:2048 -nodes -sha256 -days 730 \
  -keyout canking.key -out canking.crt \
  -subj "/CN=YOUR_HOSTNAME" \
  -addext "subjectAltName = DNS:YOUR_HOSTNAME, IP:192.168.1.10" \
  -addext "extendedKeyUsage = serverAuth"
```

2. Create a PKCS#12 (PFX) file that Kestrel can load:

```bash
openssl pkcs12 -export -out canking.pfx -inkey canking.key -in canking.crt -passout pass:MySecret
```

3. Move the PFX to a secure location and protect it. `CanKingService` runs as root by default:

```bash
sudo mkdir -p /etc/canking
sudo mv canking.pfx /etc/canking/
sudo chown root:root /etc/canking/canking.pfx
sudo chmod 600 /etc/canking/canking.pfx
```

4. Configure the service. Put non-secret settings in `/opt/canking/service/appsettings.json`:

```json
"CanKingService": {
  "EnableRemoteConnections": true,
  "RemoteConnectionPort": 36701,
  "TlsCertPath": "/etc/canking/canking.pfx"
}
```

and the secrets in a systemd drop-in, for example `/etc/systemd/system/canking.service.d/secrets.conf` (mode `0600`):

```ini
[Service]
Environment="CANKING_REMOTE_API_KEY=a-strong-secret"
Environment="CANKING_TLS_CERT_PASS=MySecret"
```

5. Open the port in the firewall:

```bash
# ufw (Ubuntu/Debian)
sudo ufw allow 36701/tcp

# firewalld (RHEL/Fedora/SUSE)
sudo firewall-cmd --permanent --add-port=36701/tcp
sudo firewall-cmd --reload
```

6. Reload systemd and restart the service:

```bash
sudo systemctl daemon-reload
sudo systemctl restart canking
```

### Windows (PowerShell)

Option A — Generate and export a self-signed PFX:

```powershell
$cert = New-SelfSignedCertificate -DnsName "YOUR_HOSTNAME" -CertStoreLocation "Cert:\LocalMachine\My"
$pwd = ConvertTo-SecureString -String "MySecret" -Force -AsPlainText
Export-PfxCertificate -Cert $cert -FilePath "C:\ProgramData\Kvaser\CanKing\ca-certificates\canking.pfx" -Password $pwd
```

Option B — Use a certificate issued by your CA: import it into the computer certificate store and export a PFX including the private key.

Secure the PFX file with a filesystem ACL so only administrators and the service account (`LocalSystem` by default) can read it.

Configure the service. Put non-secret settings in `appsettings.json` next to `CanKingService.exe` (same `CanKingService` section as for Linux, with a Windows `TlsCertPath`), and store the secrets in the service's own environment so they are not visible to other processes (elevated PowerShell):

```powershell
$key = 'HKLM:\SYSTEM\CurrentControlSet\Services\CanKing'
Set-ItemProperty -Path $key -Name Environment -Type MultiString -Value @(
    'CANKING_REMOTE_API_KEY=a-strong-secret',
    'CANKING_TLS_CERT_PASS=MySecret'
)
```

Open the Windows firewall port:

```powershell
netsh advfirewall firewall add rule name="CanKing Remote Access" dir=in action=allow protocol=TCP localport=36701
```

Restart the service so the new configuration is picked up:

```powershell
Restart-Service -Name CanKing
```

## Running as a system service

### Linux — systemd

The `canking-service` Debian package installs the service under `/opt/canking/service`, installs the `canking.service` unit into `/etc/systemd/system/`, and enables and starts it. No manual installation is needed.

If you install from the tarball instead, follow the steps in [CanKingService/README.md](./CanKingService/README.md#linux).

Don't edit the installed unit file, since it is overwritten on upgrade. Add remote-access settings with a drop-in instead (`sudo systemctl edit canking` creates one for you):

```ini
# /etc/systemd/system/canking.service.d/remote.conf
[Service]
Environment="CANKING_ENABLE_REMOTE=true"
Environment="CANKING_REMOTE_PORT=36701"
Environment="CANKING_TLS_CERT_PATH=/etc/canking/canking.pfx"
EnvironmentFile=-/etc/canking/canking.env
```

Keep secrets in the referenced environment file (mode `0600`, not tracked by version control), or in the `secrets.conf` drop-in that `ck remote enable` manages. Then:

```bash
sudo systemctl daemon-reload
sudo systemctl restart canking
sudo systemctl status canking
```

### Windows — Windows Service

The service is registered under the name `CanKing`. If you install it manually, follow the steps in [CanKingService/README.md](./CanKingService/README.md#windows) (elevated prompt):

```powershell
sc.exe create CanKing start= auto binPath= "C:\Path\To\CanKingService.exe"
sc.exe failure CanKing actions= restart/10000/restart/30000// reset= 3600
sc.exe start CanKing
```

The failure actions matter: `ck remote enable` / `disable` restart the service by exiting with a non-zero code and rely on the Service Control Manager recovery actions to start it again.

Manage the service with:

```powershell
Get-Service     -Name CanKing
Restart-Service -Name CanKing
Stop-Service    -Name CanKing
```

## Notes about service behavior

- `CANKING_*` environment variables are read first; if absent the service falls back to the `CanKingService:*` values in `appsettings.json`.
- If a certificate path is configured, the service always starts an HTTPS listener: on all interfaces at `RemoteConnectionPort` when remote connections are enabled, otherwise on a random port bound to `localhost` only.
- If remote connections are enabled but no certificate path is configured, no HTTPS listener is started and the service prints: "Warning: TLS certificate not found. Remote connections will not be available."
- If a certificate path is configured but the file is missing, unreadable, or the password is wrong, loading the certificate fails. Check the service log.
- Remote connections need both `EnableRemoteConnections=true` (or `CANKING_ENABLE_REMOTE=true`), a valid certificate, and an API key.

## Client-side setup

This section describes what needs to be configured on the machine that connects to a remote `CanKingService` with `ck`, the CanKing GUI, or the CanKing MCP server.

### 1. Obtain the server certificate

You need the server's public certificate (`.pem` / `.crt`), never the PFX. Get it in one of these ways:

**Option A — Use the file from `ck remote generate-cert`.** The `<HOSTNAME>.pem` file was saved in the directory where the command was run (or at `--pem-output`). Copy it to the client with any file transfer method, for example:

```bash
scp user@server:~/myserver.example.com.pem .
```

**Option B — Extract it live with OpenSSL:**

```bash
openssl s_client -connect myserver.example.com:36701 -showcerts </dev/null 2>/dev/null \
  | openssl x509 -outform PEM -out myserver.example.com.pem
```

**Option C — Export from the Windows certificate store** (if the certificate was created with `New-SelfSignedCertificate`):

```powershell
$cert = Get-ChildItem Cert:\LocalMachine\My | Where-Object { $_.Subject -like "*YOUR_HOSTNAME*" }
Export-Certificate -Cert $cert -FilePath "canking.cer" -Type CERT
```

Verify you have the right certificate before trusting it, for example by comparing the fingerprint with the one on the server:

```bash
# Linux / macOS
openssl x509 -in myserver.example.com.pem -noout -subject -fingerprint -sha256
```

```powershell
# Windows PowerShell
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2(".\myserver.example.com.pem")
$cert.Subject
$cert.Thumbprint
```

### 2. Trust the server certificate

Either copy the certificate to CanKing's own trusted certificates folder, or install it in the operating system's trust store.

CanKing's folder is `/usr/share/Kvaser/CanKing/ca-certificates` on Linux and `C:\ProgramData\Kvaser\CanKing\ca-certificates` on Windows. Only administrators can add certificates to it, since every certificate in it is trusted by all users of the machine. A `.pfx` file in it, which holds a private key, is readable by administrators only.

**Linux (Debian/Ubuntu):**

```bash
sudo cp myserver.example.com.pem /usr/share/Kvaser/CanKing/ca-certificates/
```

-or-

```bash
sudo cp myserver.example.com.pem /usr/local/share/ca-certificates/myserver.example.com.crt
sudo update-ca-certificates
```

> **Note:** The file extension is changed from `.pem` to `.crt` since `update-ca-certificates` only processes `.crt` files.

**Linux (RHEL/Fedora/CentOS):**

```bash
sudo cp myserver.example.com.pem /usr/share/Kvaser/CanKing/ca-certificates/
```

-or-

```bash
sudo cp myserver.example.com.pem /etc/pki/ca-trust/source/anchors/myserver.example.com.crt
sudo update-ca-trust extract
```

**Windows (elevated PowerShell):**

```powershell
Copy-Item .\myserver.example.com.pem $env:ProgramData\Kvaser\CanKing\ca-certificates\
```

-or-

```powershell
# LocalMachine\Root: all users on this machine trust it (requires elevation)
Import-Certificate -FilePath ".\myserver.example.com.pem" -CertStoreLocation Cert:\LocalMachine\Root

# CurrentUser\Root: only the current user trusts it
Import-Certificate -FilePath ".\myserver.example.com.pem" -CertStoreLocation Cert:\CurrentUser\Root
```

### 3. Configure the URL and API key

The API key must match the one configured on the server (`--service-api-key` / `CANKING_REMOTE_API_KEY`). `ck` and the CanKing MCP server read these environment variables, so you don't have to pass `--url` and `--api-key` on every command and the key does not end up in your shell history:

| Environment variable | Command-line option | Description |
| --- | --- | --- |
| `CANKING_REMOTE_URL` | `--url` | Full HTTPS address of the remote service, e.g. `https://myserver.example.com:36701`. |
| `CANKING_REMOTE_API_KEY` | `--api-key` | Shared secret sent in the `x-api-key` header. |

```bash
# Linux / macOS — current shell session
export CANKING_REMOTE_URL="https://myserver.example.com:36701"
export CANKING_REMOTE_API_KEY="a-strong-secret"
```

```powershell
# Windows PowerShell — current session only
$env:CANKING_REMOTE_URL = 'https://myserver.example.com:36701'
$env:CANKING_REMOTE_API_KEY = 'a-strong-secret'

# Windows — persistent for the current user
[System.Environment]::SetEnvironmentVariable('CANKING_REMOTE_API_KEY', 'a-strong-secret', 'User')
```

Command-line options take precedence over the environment variables. Use `--url localhost` to target the local service even when `CANKING_REMOTE_URL` is set.

> **Note:** Don't set `CANKING_REMOTE_API_KEY` machine-wide on a host that also runs `CanKingService`, since the service reads the same variable as its own API key.

### 4. Verify the connection

```bash
ck get about --url https://myserver.example.com:36701 --api-key a-strong-secret
```

A successful response shows the remote service version. If you see a TLS or certificate error, revisit steps 1–2. If you see an `Unauthenticated` error, check the API key (step 3).

## Connecting clients

### CanKing CLI (`ck`)

Every `ck` command accepts `--url` and `--api-key`:

```bash
ck get about   --url https://myserver.example.com:36701 --api-key a-strong-secret
ck get devices --url https://myserver.example.com:36701 --api-key a-strong-secret
```

With `CANKING_REMOTE_URL` and `CANKING_REMOTE_API_KEY` set, plain commands go to the remote service:

```bash
ck get devices
```

Running `ck` without arguments starts interactive mode, which shows the address of the service it is connected to in the prompt.

### CanKing GUI

Click the `Remote Connection` button in the left-side navigation bar, enter the `Service URL` and the `API Key`, and click `Connect`. When connected, a green banner is shown in CanKing's title bar.

### CanKing MCP server

The MCP server accepts the same `--url` and `--api-key` arguments and falls back to `CANKING_REMOTE_URL` and `CANKING_REMOTE_API_KEY`.

### Other gRPC clients

Custom clients must send the API key base64-encoded (UTF-8) in the `x-api-key` metadata header on every call. The service does not expose gRPC server reflection, so tools such as `grpcurl` need the `.proto` files (`-import-path` / `-proto`) to call methods.

A quick check that the listener is reachable is a plain HTTPS GET on the root path, which returns a text message explaining that a gRPC client is required:

```bash
curl -k --http2 https://myserver.example.com:36701/
```

## Security recommendations

- Use a long, random API key and rotate it periodically (re-run `ck remote enable` with a new `--service-api-key`).
- Prefer CA-signed certificates in production. Self-signed certificates are fine for test and lab setups as long as clients verify the fingerprint before trusting them.
- Protect the PFX file with restrictive filesystem permissions and a strong password.
- Keep secrets out of `appsettings.json`. Use the service environment (registry `Environment` value on Windows, systemd drop-in or `EnvironmentFile` on Linux).
- Use `--filesystem-root` to limit which files remote clients can browse.
- Don't expose the port directly to the public internet. Use a VPN, or place the service behind a reverse proxy or load balancer that handles DDoS protection.

## Troubleshooting

- **No listener on the port:** check the service log for certificate load errors, and make sure the PFX path and password are correct and readable by the service account. Use `ss -ltnp` (Linux) or `netstat -ano` (Windows) to verify the port is listening.
- **`Unauthenticated: Remote access is not available.`:** no API key is configured on the server. Re-run `ck remote enable` with `--service-api-key`, or set `CANKING_REMOTE_API_KEY` for the service.
- **`Unauthenticated: Invalid or missing API key.`:** the client sent no key or the wrong one. Check `--api-key` / `CANKING_REMOTE_API_KEY` on the client.
- **`PermissionDenied: This operation requires root (Linux) or an elevated Administrator (Windows)...`:** `ck remote enable`, `disable` and `generate-cert` were run as a regular user. Run them with `sudo` on Linux, or from a prompt started with **Run as administrator** on Windows.
- **`PermissionDenied: Remote clients can only access files under the file access root ...`:** a remote client gave a log file, log replay file, database or extension path outside `FileAccessRootPath`. Use a path under it, or change `FileAccessRootPath` on the service host.
- **`PermissionDenied: This operation is only available locally on the service host.`:** the `ck remote` command was sent to a remote service (`--url` or `CANKING_REMOTE_URL` is set). Run it on the service host itself.
- **`InvalidArgument: The API key is not accepted...`:** the key or certificate password contains a character that cannot be stored safely in the service environment. Use 1–256 printable ASCII characters without `"` `'` `\` `` ` `` `$` or `%`.
- **TLS / certificate errors on the client:** make sure the client trusts the server certificate (see [Trust the server certificate](#2-trust-the-server-certificate)) and that the hostname or IP in the URL matches a SAN in the certificate. If clients connect by IP, generate the certificate with `--ip`.
- **Service does not come back after `ck remote enable` on Windows:** make sure the `CanKing` service has failure recovery actions configured (`sc.exe failure CanKing ...`).
- **Connection times out:** check firewall rules on the server and any network firewall in between, and SELinux/AppArmor restrictions on Linux. If the firewall rule could not be added automatically, a warning is written to the service log.
