# TLS / SSL Encryption

RouterOS exposes an encrypted API endpoint on port **8729** (API-SSL).
Use `dial_tls()` to connect to it.

---

## Enable API-SSL on the RouterOS device

```
/ip service enable api-ssl
/certificate add name=api-ssl common-name=api-ssl key-usage=key-cert-sign,crl-sign
/certificate sign api-ssl
/ip service set api-ssl certificate=api-ssl
```

Or via Winbox: **IP → Services → api-ssl → enable**.

---

## Connecting with TLS (self-signed certificate)

RouterOS uses a **self-signed certificate** by default.
You must disable certificate verification or add the CA to the trust store.

```python
import ssl, routeros

# Option A: disable verification (simplest, for internal/lab use)
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

with routeros.dial_tls("192.168.1.1:8729", "admin", "", tls_context=ctx) as c:
    reply = c.run("/system/identity/print")
    print(reply.re[0].map["name"])
```

---

## Connecting with a trusted certificate

If you have exported the RouterOS CA certificate:

```python
import ssl, routeros

ctx = ssl.create_default_context()
ctx.load_verify_locations("routeros-ca.pem")   # exported from RouterOS

with routeros.dial_tls("192.168.1.1:8729", "admin", "", tls_context=ctx) as c:
    ...
```

### Export the RouterOS certificate

```
/certificate export-certificate api-ssl
```

Download the `.crt` file from RouterOS files and use it as `ca.pem`.

---

## Using system CA store

If the RouterOS certificate is signed by a public CA or added to your OS:

```python
import ssl, routeros

# Uses the OS CA bundle – no extra configuration needed
ctx = ssl.create_default_context()

with routeros.dial_tls("192.168.1.1:8729", "admin", "", tls_context=ctx) as c:
    ...
```

---

## Connection options

All options of `dial()` are also available on `dial_tls()`:

```python
routeros.dial_tls(
    "192.168.1.1:8729",
    "admin",
    "",
    tls_context=ctx,
    timeout=10.0,                      # socket timeout
    source_address=("10.0.0.5", 0),    # bind local interface
)
```

---

## Ports

| Protocol | Default port | RouterOS service name |
|---|---|---|
| Plain API | 8728 | `api` |
| API over TLS | 8729 | `api-ssl` |
