Opt-In Software Blog

Software, dvelopment, and practical insights

Using OpenRouter in the VS Code Agent without GitHub Copilot

Read in: English | Русский

Tested on VS Code 1.140 (Stable) and VS Code Insiders 1.141, October 2026.

I wanted to use OpenRouter models in the VS Code Agent without signing in to GitHub Copilot. VS Code can do this with custom language model providers, but on my machine it only worked in VS Code Insiders. This post shows the setup, how to tell whether you need Insiders, and an nginx reverse proxy for networks where OpenRouter is not reachable.

TL;DR

  1. Try the regular VS Code first. If you see the symptoms described below, switch to VS Code Insiders.
  2. Create chatLanguageModels.json with an OpenRouter provider (vendor: "customendpoint") and your models. Use the exact model ID from openrouter.ai.
  3. Set the API key with Manage Models → Update API Key. Don’t leave the raw key in the JSON: it didn’t work for me.
  4. Select the model in Models and switch to Agent.
  5. If OpenRouter is blocked in your country, see the proxy section below.

Prerequisites

  • An OpenRouter account with an API key and some credit. Free models come and go (see Troubleshooting).
  • A model that supports tool calling. Agent mode needs it.
  • VS Code Insiders, if the regular VS Code doesn’t work for you (see the next section).

Do you need VS Code Insiders?

Maybe not, so try the regular VS Code first. On my machine (Stable 1.140), it didn’t work:

  • With an empty chatLanguageModels.json there was no Manage Models button and no Chat: Manage Language Models command.
  • After I added a provider to the file by hand and restarted, the button and the command appeared, but the Language Models dialog showed only Copilot’s own models. My OpenRouter models were nowhere to be found, and I couldn’t select them in the chat.
  • Add Models → OpenRouter accepted an API key and wrote a group to chatLanguageModels.json, but the group never showed up in the dialog or in the model picker, even after a restart.

I didn’t dig into why. The official docs currently list the Custom endpoint provider as an Insiders feature, and in Insiders everything below worked. So if you see the same symptoms, install VS Code Insiders. It installs side by side with the regular VS Code and keeps its own settings.

Where is chatLanguageModels.json

The file lives in the user data folder of VS Code Insiders, which is separate from the regular VS Code (Code - Insiders, not Code):

  • Windows: press Win + R, enter %APPDATA%\Code - Insiders\User and press Enter.
  • macOS: in Finder press Cmd + Shift + G and go to ~/Library/Application Support/Code - Insiders/User.
  • Linux: go to ~/.config/Code - Insiders/User.

Note: the regular VS Code uses Code instead of Code - Insiders in these paths. You can edit the file there, but if the regular VS Code doesn’t show your models, editing it won’t help. Edit the Insiders copy.

Create the provider in chatLanguageModels.json

I didn’t add the provider through the Manage Models dialog. I wrote it in chatLanguageModels.json by hand and VS Code picked it up. This is the file I use:

[
	{
		"name": "OpenRouter",
		"vendor": "customendpoint",
		"apiKey": "${input:chat.lm.secret.-32b9a01a}",
		"apiType": "chat-completions",
		"models": [
			{
				"id": "qwen/qwen3.8-27b",
				"name": "Qwen3.8 27B",
				"url": "https://openrouter.ai/api/",
				"toolCalling": true,
				"vision": true,
				"maxInputTokens": 262000,
				"maxOutputTokens": 16000
			},
			{
				"id": "deepseek/deepseek-r1",
				"name": "DeepSeek R1",
				"url": "https://openrouter.ai/api/",
				"toolCalling": true,
				"vision": false,
				"maxInputTokens": 64000,
				"maxOutputTokens": 16000
			}
		]
	}
]

The apiKey value is what VS Code writes after the next step. Until then, don’t worry about it.

What the fields mean:

  • vendor: "customendpoint" marks this as a custom model provider.
  • apiType: "chat-completions" makes VS Code use the Chat Completions API.
  • id is the model ID on OpenRouter. Copy it from the model’s page.
  • url is the base URL. VS Code builds the Chat Completions request from it (the request ends up at /v1/chat/completions), which is why it is .../api/ and not the full endpoint.
  • toolCalling enables tool calling. Without it the Agent can’t work.
  • vision says whether the model accepts images.
  • maxInputTokens and maxOutputTokens are the limits VS Code uses.

Choosing values for a model

Take toolCalling and vision from the model’s page on OpenRouter. For example, Qwen3.8 27B is a vision-language model that accepts tools, while DeepSeek R1 is text-only, so vision is false there.

Limits are less clear-cut. The context size can differ between providers and sources: for R1 I’ve seen 64K on the model page and 131K-164K elsewhere, and for Qwen3.8 27B 262K and 1M. I use the smaller figure, which is safe with any provider. Don’t set maxOutputTokens too low for reasoning models, because reasoning tokens count as output. 4096 is too small, since answers get cut off.

If you want a Claude model, the same block works with the slug from its OpenRouter page (for Sonnet 5 it is anthropic/claude-sonnet-5, with vision: true and toolCalling: true).

Set the API key (this step is not optional)

It might seem natural to write your OpenRouter key directly into apiKey:

"apiKey": "sk-or-v1-..."

That is what I did first, and it didn’t work. OpenRouter rejected every request with a 403. I checked the nginx log and found that the Authorization header contained just Bearer, with no token after it.

What fixed it: in Manage Models I selected the OpenRouter provider and chose Update API Key, then entered the key there. VS Code replaced the value in the file with a reference to a secret it stores itself:

"apiKey": "${input:chat.lm.secret.-32b9a01a}"

After that the header was passed correctly and requests went through. As a bonus, the key no longer sits in a file. The reference only works on the machine where you ran Update API Key, so don’t copy it to another machine. Run Update API Key there too.

VS Code replaced the raw key in the file with that reference on its own, so nothing else needs cleaning up.

Using the model

Go back to the Chat view, click Models, pick the OpenRouter model and switch to Agent. VS Code stays the interface and the agent, while OpenRouter provides the model, so you can swap models by editing one entry in the JSON.

If OpenRouter is not reachable from your country

If OpenRouter works for you, skip this section. Otherwise, you can route requests through an nginx reverse proxy on a VPS that can reach it:

VS Code → https://example.com/openrouter/api/ → nginx → https://openrouter.ai/api/v1/chat/completions

In the model config, change the URL:

"url": "https://example.com/openrouter/api/"

nginx configuration

This is the configuration that works for me (TLS for example.com is assumed to be configured already):

location /openrouter/api/v1/chat/completions {
    proxy_pass https://openrouter.ai/api/v1/chat/completions;
    proxy_ssl_server_name on;
    proxy_ssl_name openrouter.ai;
    proxy_ssl_protocols TLSv1.2 TLSv1.3;
    proxy_ssl_session_reuse on;
    proxy_set_header Host openrouter.ai;
    proxy_set_header Authorization $http_authorization;
    proxy_buffering off;
    proxy_cache off;
    chunked_transfer_encoding on;
    proxy_read_timeout 300s;
    proxy_connect_timeout 75s;
    proxy_send_timeout 300s;
    proxy_buffer_size 32k;
    proxy_buffers 8 32k;
    proxy_busy_buffers_size 64k;
}

Your OpenRouter key is passed through from the Authorization header sent by VS Code, so it is never stored on the server. The location covers only the Chat Completions path, so other endpoints, such as /v1/models, are not proxied. That’s fine here because the models are listed manually in the JSON.

Security notes

  • The proxy sees your API key and every prompt, including your project’s code. Only run it on a server you control.
  • A public proxy can be used by anyone who finds it. Restrict access, for example with allow/deny for your IP addresses and limit_req for rate limiting. Basic auth won’t work here, because it uses the same Authorization header that carries your OpenRouter key.
  • Check OpenRouter’s terms of service and any regional restrictions that apply to you before routing around network blocks.

Troubleshooting

The model doesn’t appear in the picker. First check that you are in VS Code Insiders and not in the regular VS Code, and that you edited the file in the Code - Insiders folder. Then check that the JSON is valid and that the provider has an API key set.

403, and the Authorization header contains only Bearer. I got this when I wrote the raw key into apiKey. Run Update API Key (see above) so that VS Code stores the key as a secret. If you use the nginx proxy, you can see what actually arrives by temporarily logging $http_authorization in your log format. Remove it afterwards, because it puts your key into the log.

404 — This model is unavailable for free. This is what I got when I tried a :free model:

{"message":"This model is unavailable for free. The paid version is available now - use this slug instead: deepseek/deepseek-r1","code":404}

Free variants of models get removed. The message contains the paid slug, so put it into id. The error also tells you that the request reached OpenRouter and the key was accepted, so the config and the proxy are fine.

401. The API key is missing or wrong. Run Update API Key again.

The Agent ignores tools or fails. The model, or the specific provider OpenRouter routes you to, may not support tool calling. Check the model’s page and try another model.

Responses hang or arrive all at once (when using the proxy). This is usually buffering. Make sure proxy_buffering off; is set.

A note on privacy

In Agent mode, parts of your project are sent to the model provider as prompts. OpenRouter forwards them to the provider that serves the model, so check the data policy of the models you use, especially the free ones.

Integrating Developer PowerShell into Visual Studio Code

Read in: English | Русский

To build projects using the MSVC compiler (cl.exe), CMake, and Ninja directly from the Visual Studio Code interface, you need to add the Visual Studio environment profiles to the built-in terminal.

Step-by-Step Instructions

  1. Open the settings.json configuration file:
    • Press Ctrl + Shift + P.
    • Type Preferences: Open User Settings (JSON) into the search bar and press Enter.
  2. Add the profile configuration:
    Insert the following block of settings inside the main curly braces { … } of your settings.json file:
"terminal.integrated.profiles.windows": {
    "Developer PowerShell (x64)": {
        "source": "PowerShell",
        "overrideName": true,
        "args": [
            "-NoExit",
            "-Command",
            "& { Import-Module 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\Tools\\Microsoft.VisualStudio.DevShell.dll'; Enter-VsDevShell 43240475 -SkipAutomaticLocation -DevCmdArguments '-arch=x64' }"
        ]
    },
    "Developer PowerShell (x86)": {
        "path": "C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe",
        "overrideName": true,
        "args": [
            "-NoExit",
            "-Command",
            "& { Import-Module 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\Tools\\Microsoft.VisualStudio.DevShell.dll'; Enter-VsDevShell 43240475 -SkipAutomaticLocation }"
        ]
    }
}

(Note: The paths are specified for a standard Visual Studio 2022 Community installation. If you are using Professional or Enterprise editions, replace Community in the paths with the corresponding name).

  1. Apply the settings:
    • Save the settings.json file.
    • Close active terminal sessions in VS Code using the trash can icon (Kill Terminal) in the terminal panel to refresh the profile list.
  2. Launch the terminals:
    • Click the arrow next to the “plus” sign in the upper-right corner of the terminal panel.
    • Select the required architecture from the dropdown list: Developer PowerShell (x64) or Developer PowerShell (x86).

BoringSSL on Top of Any Stream in .NET

Read in: English | Русский

The standard SslStream in .NET is good in every way except one: it doesn’t let you control what your ClientHello looks like. The set of ciphers, the order of extensions, GREASE, ALPS, post-quantum groups are determined by the platform (SChannel, OpenSSL) and are almost non-configurable. Usually this isn’t a problem. But if a client needs to look like Chrome in TLS fingerprints (JA3/JA4), SslStream won’t do.

Chrome has its own TLS stack, BoringSSL, Google’s fork of OpenSSL. I built a proof-of-concept BoringSslConsole: a .NET 8 console application and a BoringSslStream wrapper that exposes BoringSSL as an ordinary Stream.

Sources: https://github.com/optinsoft/BoringSslConsole

The main architectural requirement for the wrapper is this: BoringSSL must not perform any network operations. All I/O goes through the managed innerStream. Below I’ll explain why this is needed and how it’s structured.

Why a “networkless” BoringSSL

BoringSSL can work with the network itself: it has socket and file BIOs (BIO_new_socket, BIO_new_fd). If I had used them, the library would drive data through the socket itself, and there would be no way to implement asynchrony or substitute my own transport.

I needed something different: for the TLS layer to work on top of any Stream. This could be a NetworkStream, a tunnel through a proxy (CONNECT, SOCKS), a MemoryStream in tests, or another layer on top of TLS. Therefore the native part is responsible only for TLS state: handshake, encryption, and decryption of records. And C# moves the bytes to and from the network.

Architecture

TcpClient
   |
NetworkStream  (innerStream)
   |
BoringSslStream (C#): pumps bytes between the stream and the buffers
   |
BoringSSL, memory BIO (pure TLS state, no network)
   |
HTTP/1.1 or HTTP/2

Between C# and BoringSSL there are two in-memory buffers (BIO_s_mem):

  • input: C# puts bytes read from innerStream here (pms_ssl_feed_read);
  • output: C# takes bytes from here that need to be sent to innerStream (pms_ssl_take_write, the size can be queried via pms_ssl_pending_write).

The native DLL (proxymap_boringssl.dll) exports a small flat C API: pms_ssl_create, pms_ssl_connect, pms_ssl_read, pms_ssl_write, plus buffer-pumping functions and a few getters (protocol version, cipher, selected ALPN, server DER certificate, last error). All ClientHello parameters are passed from C# as strings and numbers.

BoringSslStream inherits from Stream, so it can be substituted anywhere an ordinary stream is expected. Everything is fully asynchronous, with CancellationToken.

The main loop: pumping bytes

The whole mechanism fits into a single pattern. We call a BoringSSL operation, flush the accumulated output to the network, and if the library asks for data, we read it from the network and feed it back. Here is the handshake:

while (true)
{
    int result = Native.pms_ssl_connect(_connection);

    await FlushWriteBioAsync(cancellationToken);

    switch (result)
    {
        case Native.PMS_SSL_OK:
            ValidateServerCertificate(_hostname);
            _authenticated = true;
            return;

        case Native.PMS_SSL_WANT_READ:
            await ReadFromNetworkAsync(cancellationToken);
            break;

        case Native.PMS_SSL_WANT_WRITE:
            break; // output has already been flushed to the network
    }
}

FlushWriteBioAsync takes everything accumulated in the output buffer and writes it to innerStream. ReadFromNetworkAsync reads from innerStream and feeds the bytes to the input buffer. The same loop is repeated in ReadAsync and WriteAsync.

The output must be flushed after every BoringSSL call, not just during the handshake: even SSL_read can itself generate TLS records (for example, KeyUpdate or alerts).

Buffers are taken from ArrayPool<byte>, and pointers are passed to native code via Memory<T>.Pin(), without unnecessary copies.

Synchronization

The class has four SemaphoreSlims: _readLock and _writeLock serialize reads and writes respectively, while _networkReadLock and _networkWriteLock protect the exchange with innerStream. Thanks to this, concurrent ReadAsync and WriteAsync calls don’t break each other’s work with the stream and buffers. The handshake takes both outer locks at once.

A caveat: this is sufficient for a PoC, but a full-fledged full-duplex over a single SSL* requires care on the native library side as well, not just in C#. I’ll mention this again in the limitations.

The “like Chrome” preset

The BoringSslStream constructor accepts a set of parameters, filled by default with Chrome’s values:

  • cipher list: ECDHE variants of AES-GCM and ChaCha20-Poly1305, plus a legacy tail;
  • GREASE and ECH GREASE;
  • ALPN h2:http/1.1 and ALPS h2;
  • signature algorithms, including post-quantum ML-DSA-44/65/87;
  • SCT, status_request, Brotli certificate compression;
  • trust_anchors as a hex string.

The fine-grained work with extensions (reordering, dynamic formation of ALPN/ALPS, padding of status_request) is done on the C++ side. Brotli is linked statically so that everything builds into a single self-contained DLL and there’s no DllNotFoundException at runtime.

On tls.peet.ws the JA4 fingerprint matched Chrome. But JA3 does not match, and that’s how it should be. Starting with Chrome 110, the browser randomly shuffles the order of TLS extensions in ClientHello on every connection. JA3 is built from the lists of ciphers, extensions, groups, and point formats in the order they arrived, so a real Chrome’s JA3 hash is different every time, and comparing it to some “reference” is meaningless. Our client does the same: the native layer shuffles extensions, and JA3 changes from connection to connection, just like in the browser.

JA4 is structured differently: before hashing, it sorts ciphers and extensions (and discards GREASE), so shuffling doesn’t affect it. That’s exactly why JA4 is stable and suitable for verification: if it matches, then the set of ciphers, extensions, signature algorithms, and ALPN is the same as Chrome’s.

Certificate verification

Here BoringSSL only negotiates the channel, while the trust decision is made by .NET. Immediately after a successful handshake, the native layer returns the server’s DER certificate, and then:

using var certificate = new X509Certificate2(memory.Span);
using var chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.1")); // Server Auth

if (!chain.Build(certificate))
    throw new AuthenticationException(...);

if (!certificate.MatchesHostname(hostname))
    throw new AuthenticationException(...);

The system root certificate store is used, online revocation checking is enabled, and the hostname is verified via MatchesHostname (available in .NET 8, takes SAN and wildcard rules into account).

It’s easy to test on badssl.com: expired.badssl.com fails on chain building, untrusted-root.badssl.com on an unknown root, revoked.badssl.com on revocation checking. The relevant hosts are commented out in Program.cs; just change one constant.

HTTP/2 by hand

Since ALPN negotiates h2, I had to write a minimal HTTP/2 client right in Program.cs, without third-party libraries.

Sending. First a 24-byte connection preface, then an empty SETTINGS. Then the headers: a tiny HpackEncoder writes indexed fields from the static table (:method: GET is index 2, :scheme: https is 7) and literals without indexing for :authority, :path, and the rest. The block is wrapped in a 9-byte HEADERS frame header with flags END_STREAM | END_HEADERS on stream 1.

Receiving. We read strictly 9 bytes of frame header, parse the length (24 bits), type, flags, and stream id, then read exactly that many bytes of payload. Then we parse by type:

  • DATA is written to a file and to the console, and on END_STREAM we exit;
  • HEADERS prints the status (see below) and also checks for END_STREAM;
  • SETTINGS without the ACK flag is acknowledged with SETTINGS ACK, as RFC requires;
  • RST_STREAM and GOAWAY are printed with a decoded error code;
  • WINDOW_UPDATE is ignored.

There’s no full HPACK decoder, so the response status is determined by a heuristic: we look in the block for bytes 0x88–0x8E, corresponding to indexed statuses from the static table (0x88 is 200, 0x8D is 404). For a demo this is enough, but it’s precisely a hack.

If ALPN returns http/1.1, everything is simpler: an ordinary text request with Connection: close goes out, and the response is read until the stream closes.

Running

git clone --recursive https://github.com/optinsoft/BoringSslConsole.git

cd Native
cmake -G Ninja -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build

cd ..
dotnet run --project BoringSslConsole

To build on Windows you need the .NET 8 SDK, Visual Studio 2022 with C++ tools, CMake 3.22+, Ninja, Git, NASM, and Go (the last two are required by BoringSSL itself). BoringSSL and Brotli are included as git submodules; after building, the DLL is copied to the .NET output directory. The response is printed to the console and saved to ./output/<host>.txt.

Results and limitations

The result is a compact asynchronous Stream with a Chrome-like TLS stack inside, with real certificate verification, while the network is entirely in .NET’s hands. On top of it you can build proxies, an HTTP client, or testing tools, and the transport can be swapped without touching the TLS layer.

An honest list of what’s missing here:

  • HTTP/2 is minimal: no HPACK decoder, no CONTINUATION, no flow control, no multiplexing.
  • The TLS fingerprint matches, not the whole client. HTTP/2 has its own fingerprint (SETTINGS values, WINDOW_UPDATE, pseudo-header order), and here it differs from Chrome’s.
  • Thread safety needs separate verification. The locks in C# separate reads, writes, and network operations, but the safety of concurrent SSL_read and SSL_write on a single SSL* also depends on the native layer. Freeing the SSL* in Dispose should also be synchronized with in-flight operations.
  • Chain validation: only the leaf certificate is taken from the native layer, so chain building may depend on AIA fetching of intermediates, and online revocation checking blocks the thread inside async code.
  • Platform: building requires a heavy toolchain, and the native part is currently Windows x64 only.

This is a PoC, but the architectural idea — “BoringSSL as a pure TLS machine, with I/O outside” — turned out well, in my opinion, and easily transfers to other transports.

The project on GitHub: optinsoft/BoringSslConsole

Configure SPF, DKIM, and DMARC for a Linux Mail Server

Read in: English | Русский

If you need to send email from your own domain without using third-party SMTP services, you can rent a Linux VPS. Postfix or Exim are commonly used as the mail transfer agent (MTA).

Before buying a VPS, contact the hosting provider and ask: “Is outbound SMTP port 25 open?” Many hosting providers block it by default to prevent spam. If the port is blocked, sending email directly to remote mail servers may not be possible.


1. Preparation: Network and DNS Settings

To make sure your mail is delivered correctly, you need to configure several basic DNS records for your domain:

  1. Hostname. Set the server hostname to something like mail.yourdomain.com.

  2. A record. Point mail.yourdomain.com to the IP address of your VPS.

  3. MX record. Specify which server handles email for your domain. The record looks like this:

    @ MX 10 mail.yourdomain.com.
  4. PTR record (Reverse DNS). Maps the server’s IP address back to its hostname. It is configured in your VPS provider’s control panel rather than at your domain registrar.

    A PTR record is important for email delivery. Many mail servers check the reverse DNS record of the sending IP address, and a missing or inconsistent PTR record can result in messages being rejected or sent to spam.

    It is recommended to keep the forward and reverse DNS records consistent:

    1.2.3.4 → mail.yourdomain.com
    mail.yourdomain.com → 1.2.3.4

2. Configuring SPF

SPF is a DNS record that specifies which servers are authorized to send email on behalf of your domain.

Create a TXT record:

  • Record type: TXT

  • Host/Name: @ (or leave it empty, depending on your DNS provider)

  • Value:

    v=spf1 ip4:1.2.3.4 ~all

    Replace 1.2.3.4 with the IP address of your server.

What does ~all mean?

~all means SoftFail: messages sent from IP addresses not listed in the SPF record receive a soft-failure result. The receiving server decides how to handle such messages.

After testing your configuration, you can use -all if all legitimate sources that send email for your domain are listed in the SPF record.


3. Generating DKIM Keys with OpenSSL

DKIM is a digital signature mechanism that helps verify the authenticity of the sender and the integrity of an email. The server signs the message with a private key, and the recipient verifies the signature using the public key published in DNS.

To generate a key pair, connect to the server over SSH and run the following commands.

3.1. Generate a 2048-bit private key

openssl genrsa -out dkim.private 2048

3.2. Generate the public key

openssl rsa -in dkim.private -pubout -out dkim.public

3.3. Display the public key

cat dkim.public

The terminal will display something like:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A...
-----END PUBLIC KEY-----

For the DNS record, take only the Base64-encoded content between the headers and combine it into a single line without spaces or line breaks.

Then create a TXT record named dkim._domainkey (dkim is the selector name).

  • Record type: TXT

  • Host/Name: dkim._domainkey

  • Value:

    v=DKIM1; k=rsa; p=YOUR_COPIED_PUBLIC_KEY

If your DNS provider supports splitting long TXT records into multiple strings, use that option for keys that do not fit into a single string.


4. Connecting DKIM to the Mail Server

4.1 Option A: If You Use Exim

In the Exim configuration file (the exact path depends on the distribution and installation method), find the transport responsible for sending mail to external servers. It is usually called remote_smtp.

Example configuration:

remote_smtp:
  driver = smtp
  dkim_domain = yourdomain.com
  dkim_selector = dkim
  dkim_private_key = /etc/exim/dkim.private
  dkim_canon = relaxed

Copy the private key to the location specified in the Exim configuration:

cp dkim.private /etc/exim/dkim.private

Give the user running Exim permission to read the private key. The username depends on the distribution. For example, some systems use exim, while Debian may use Debian-exim.

Example for a system using the exim user:

chown exim:exim /etc/exim/dkim.private
chmod 600 /etc/exim/dkim.private

Restart the service:

systemctl restart exim4
# or
systemctl restart exim

Make sure that the Exim user actually has access to the private key.


4.2 Option B: If You Use Postfix

Postfix uses the external OpenDKIM utility to add DKIM signatures to outgoing messages.

4.2.1. Install the packages

apt install opendkim opendkim-tools

4.2.2. Configure OpenDKIM

Open /etc/opendkim.conf and add or configure the following settings:

Syslog                 yes
RequiredHeaders        yes
Mode                   sv
SubDomains             no
Socket                 inet:8891@localhost
KeyTable               /etc/opendkim/KeyTable
SigningTable           /etc/opendkim/SigningTable
ExternalIgnoreList     /etc/opendkim/TrustedHosts
InternalHosts          /etc/opendkim/TrustedHosts

4.2.3. Connect OpenDKIM to Postfix

Add the following lines to the end of the main Postfix configuration file, /etc/postfix/main.cf:

milter_protocol = 6
milter_default_action = accept
smtpd_milters = inet:localhost:8891
non_smtpd_milters = inet:localhost:8891

4.2.4. Configure the OpenDKIM tables

This example uses a single domain and a single DKIM key. The key name in KeyTable is dkim._domainkey.yourdomain.com.

/etc/opendkim/KeyTable

This file maps the key name to the domain, selector, and private key path:

dkim._domainkey.yourdomain.com yourdomain.com:dkim:/etc/opendkim/keys/dkim.private

Here:

  • dkim._domainkey.yourdomain.com — the key name in the table.
  • yourdomain.com — the domain that will appear in the DKIM signature (d=).
  • dkim — the selector (s=).
  • /etc/opendkim/keys/dkim.private — the path to the private key.

/etc/opendkim/SigningTable

This file maps the sender domain to the key name from KeyTable:

yourdomain.com dkim._domainkey.yourdomain.com

If you need to use a pattern for sender addresses from the domain, you can specify:

*@yourdomain.com dkim._domainkey.yourdomain.com

The wildcard form requires the corresponding refile: table type to be configured in the SigningTable directive. This guide uses the simple domain-based mapping without refile.

/etc/opendkim/TrustedHosts

Add localhost and the IP address of your server:

127.0.0.1
localhost
1.2.3.4

4.2.5. Move the private key and restart the services

Create the directory for the keys:

mkdir -p /etc/opendkim/keys/

Move the private key:

mv dkim.private /etc/opendkim/keys/

Set the owner and permissions:

chown opendkim:opendkim /etc/opendkim/keys
chmod 700 /etc/opendkim/keys

chown opendkim:opendkim /etc/opendkim/keys/dkim.private
chmod 600 /etc/opendkim/keys/dkim.private

Restart the services:

systemctl restart opendkim postfix

Check their status:

systemctl status opendkim
systemctl status postfix

If necessary, check the OpenDKIM log:

journalctl -u opendkim -n 50 --no-pager

5. Configuring DMARC

DMARC is a mechanism that allows a domain to tell receiving mail servers how to handle messages that fail the required SPF and DKIM checks, including the alignment of the domains involved with the domain in the From header.

Create a TXT record:

  • Record type: TXT

  • Host/Name: _dmarc

  • Initial value:

    v=DMARC1; p=none; rua=mailto:admin@yourdomain.com

What does this mean?

  • p=none — monitoring mode. The domain asks the receiving server not to apply a special action to messages that fail DMARC. You can monitor the results and collect reports.
  • rua=mailto:... — the address to which mail services can send aggregate reports about authentication checks.
  • p=quarantine — asks the receiving server to treat messages that fail DMARC as suspicious, for example by placing them in the spam folder.
  • p=reject — asks the receiving server to reject messages that fail DMARC. The actual action is determined by the receiving server.

After testing and fixing the configuration, you can change the policy from p=none to p=quarantine or p=reject.


6. How to Check DNS Records from the Terminal

You can check whether the DNS settings have been updated using dig or nslookup.

Check SPF

dig yourdomain.com TXT +short

Or:

nslookup -type=TXT yourdomain.com

Check DKIM

The query uses the name of your selector:

dig dkim._domainkey.yourdomain.com TXT +short

Or:

nslookup -type=TXT dkim._domainkey.yourdomain.com

Check DMARC

dig _dmarc.yourdomain.com TXT +short

Or:

nslookup -type=TXT _dmarc.yourdomain.com

Check PTR (Reverse DNS)

dig -x 1.2.3.4 +short

Or:

nslookup 1.2.3.4

Check the server hostname:

hostname -f

Make sure that the hostname is consistent with the A and PTR records.

The recommended setup is:

Hostname: mail.yourdomain.com
A:        mail.yourdomain.com → 1.2.3.4
PTR:      1.2.3.4 → mail.yourdomain.com

The hostname used by the server and the reverse DNS record should be configured consistently.

How Windows OpenSSH Broke My Brain

Read in: English | Русский

There are errors you can fix with a two-second Google search, and then there are those that drain your time. A prime example is an SSH connection failure to a Windows Server, where the OpenSSH service drops the following logs into the Event Viewer:

sshd: error: get_user_token - unable to generate token on 2nd attempt for user administrator
sshd: fatal: ga_init, unable to resolve user administrator

These messages indicate that the Windows authentication subsystem either cannot recognize the user at the OS level or is unable to generate a security token for them. Everything seems properly configured, yet the server persistently drops the connection.

Where the Time Goes (False Trails)

If you start googling this error, 90% of the online advice will lead you down two main paths:

  1. Key File Permissions: You will be told to configure ACLs via icacls for the administrators_authorized_keys file located in C:\ProgramData\ssh, disable inheritance, and restrict access exclusively to SYSTEM and Administrators.
  2. The sshd_config File: You will be advised to comment out the Match Group administrators block at the very bottom of the config to force OpenSSH to read keys from the standard user profile (.ssh/authorized_keys).

I tried everything on that list. Permissions and configs were verified, services were restarted—yet the result was zero. The server stubbornly terminated the session immediately after successfully validating the key.

The Unobvious Answer

The root cause turned out to be trivial, yet hidden behind the specifics of how OpenSSH operates on Windows.
How does SSH work in Linux? If the key matches, you are in.
How does SSH work in Windows? Even if the key matches, the OpenSSH service (running under the SYSTEM account) needs to establish a fully functional Windows workspace session and generate a user security token using the system API (LsaLogonUser).
And that is exactly where Windows denies the request.
I ran a quick check in the server console:

net user Administrator

And there it was: Account Active: Locked.
As it turned out, the Administrator account was locked out! This was likely caused by routine brute-force attempts—bots kept hammering port 22, triggering the Windows password lockout policy, which “froze” the account. Meanwhile, the SSH server successfully verified and confirmed the key (since the file exists on the disk), but the Windows OS refused to generate a token for a locked user. Hence the completely cryptic log about being unable to generate token.

The 5-Second Fix

If you have run into the same issue, the solution is straightforward. Log into the server using another admin account (or log in locally) and unlock the Administrator.

Via PowerShell:

Unlock-LocalUser -Name "Administrator"

Via the good old CMD:

net user Administrator /active:yes

Immediately after, the connection issues disappear, and the client successfully gains SSH access to the server.

Search