Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions dev.docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -131,11 +131,14 @@ services:
XI_NETWORK_SQL_HOST: database
XI_NETWORK_SQL_PORT: 3306
XI_NETWORK_ZMQ_IP: world
XI_NETWORK_TLS_KEY: /server/certs/login.key
XI_NETWORK_TLS_CERT: /server/certs/login.cert
ports:
- "54001:54001"
- "54230:54230"
- "54231:54231"
volumes:
- certs:/server/certs
- ${LOCAL_WORKSPACE_FOLDER:-./}/log:/server/log
depends_on:
database:
Expand Down Expand Up @@ -167,10 +170,13 @@ services:
<<: *dbcreds
XI_NETWORK_SQL_HOST: database
XI_NETWORK_SQL_PORT: 3306
XI_NETWORK_TLS_KEY: /server/certs/login.key
XI_NETWORK_TLS_CERT: /server/certs/login.cert
ports:
- "51220:51220"
- "51240:51240"
volumes:
- certs:/server/certs
- ${LOCAL_WORKSPACE_FOLDER:-./}/log:/server/log
depends_on:
database:
Expand Down Expand Up @@ -222,5 +228,6 @@ services:
condition: service_started

volumes:
certs:
navmeshes:
external: true
4 changes: 4 additions & 0 deletions docker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,11 @@ x-common: &common
XI_NETWORK_HTTP_HOST: 0.0.0.0
XI_NETWORK_ZMQ_IP: world
XI_NETWORK_SQL_HOST: database
XI_NETWORK_TLS_KEY: /server/certs/login.key
XI_NETWORK_TLS_CERT: /server/certs/login.cert
# XI_{file}_{setting}: value
volumes:
- certs:/server/certs
- navmeshes:/server/navmeshes
- ximeshes:/server/ximeshes
# - ./config.yaml:/server/tools/config.yaml
Expand Down Expand Up @@ -213,6 +216,7 @@ services:
condition: service_started

volumes:
certs:
database:
navmeshes:
external: true
Expand Down
1 change: 1 addition & 0 deletions docker/alpine.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ adduser --uid $UID $UNAME --ingroup $UGROUP --home /xiadmin --disabled-password
echo "$UNAME ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/$UNAME
chmod 0440 /etc/sudoers.d/$UNAME
chown $UNAME:$UGROUP /server
install -d -o $UNAME -g $UGROUP /server/certs
git config --system --add safe.directory /server
EOF

Expand Down
1 change: 1 addition & 0 deletions docker/ubuntu.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ useradd --uid $UID $UNAME --gid $UGROUP --home-dir /xiadmin --create-home
echo "$UNAME ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/$UNAME
chmod 0440 /etc/sudoers.d/$UNAME
chown $UNAME:$UGROUP /server
install -d -o $UNAME -g $UGROUP /server/certs
git config --system --add safe.directory /server
EOF

Expand Down
3 changes: 2 additions & 1 deletion docs/wiki/LetsEncrypt.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Make sure you replace any references to `/path/to/server/` with your own server'
<summary>Linux (Ubuntu 24.04)</summary>

### Backup Existing Cert
Chances are you already have a cert in your xi server directory. The connect server will automatically generate a self-signed certificate if it does not detect one. Its a good idea to back anything we are changing just in case.
Chances are you already have a cert in your xi server directory. `xi_connect` and `xi_profile` share `login.key` and `login.cert` (paths set by `TLS_KEY` and `TLS_CERT` in `settings/network.lua`), and generate a self-signed pair on first start if neither file exists. Its a good idea to back anything we are changing just in case.
```sh
cp /path/to/server/login.key /path/to/server/login.key.bak
cp /path/to/server/login.cert /path/to/server/login.cert.bak
Expand Down Expand Up @@ -96,6 +96,7 @@ cp /etc/letsencrypt/live/myserver.mydomain.com/privkey.pem /path/to/server/login
cp /etc/letsencrypt/live/myserver.mydomain.com/fullchain.pem /path/to/server/login.cert
chown xiuser:xiuser /path/to/server/login.key /path/to/server/login.cert
systemctl restart xi_connect.service
systemctl restart xi_profile.service
```
Make the post-renewal script executable and run it:
```sh
Expand Down
4 changes: 4 additions & 0 deletions settings/default/network.lua
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ xi.settings.network =

PROFILE_PORT = 51220,

-- Key and certificate shared by every TLS listener (xi_connect and xi_profile), generated on first start if neither exists
TLS_KEY = 'login.key',
TLS_CERT = 'login.cert',

-- DB queries will attempt each query once, and reconnect and retry up to `SQL_QUERY_RETRY_COUNT` times.
SQL_QUERY_RETRY_COUNT = 1,

Expand Down
170 changes: 103 additions & 67 deletions src/common/cert_helpers.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,79 +22,36 @@
#pragma once

#include "common/logging.h"
#include "common/settings.h"

#include <asio/ssl.hpp>
#include <chrono>
#include <filesystem>
#include <stdexcept>
#include <string>
#include <thread>

namespace certificateHelpers
{

// creates <name>.key and <name>.cert on first start
inline void generateSelfSignedCert(const std::string& name = "login", const bool ellipticCurve = false)
// creates the key and cert on first start; one pair serves every TLS listener (xi_connect auth/data/view, xi_profile)
inline void generateSelfSignedCert()
{
const auto keyFile = name + ".key";
const auto certFile = name + ".cert";
const auto keyFile = settings::get<std::string>("network.TLS_KEY");
const auto certFile = settings::get<std::string>("network.TLS_CERT");

if (std::filesystem::exists(keyFile))
{
FILE* fileHandle = fopen(keyFile.c_str(), "r");
if (fileHandle)
{
EVP_PKEY* pkey = PEM_read_PrivateKey(fileHandle, nullptr, nullptr, nullptr);
if (pkey)
{
ShowInfo(fmt::format("Found existing {}", keyFile));
}

EVP_PKEY_free(pkey);
fclose(fileHandle);
}
}

if (std::filesystem::exists(certFile))
// the key is created exclusively so concurrently starting servers generate a single pair
FILE* keyHandle = nullptr;
if (!std::filesystem::exists(keyFile) && !std::filesystem::exists(certFile))
{
FILE* fileHandle = fopen(certFile.c_str(), "r");
if (fileHandle)
{
X509* cert = PEM_read_X509(fileHandle, nullptr, nullptr, nullptr);
if (cert)
{
char cn[2048] = {};
int size = sizeof(cn);

X509_NAME_oneline(X509_get_subject_name(cert), cn, size);
X509_NAME_oneline(X509_get_issuer_name(cert), cn, size);

// This is internal, so we can trust it.
ShowInfo(fmt::format("Found existing {}: {}", certFile, asStringFromUntrustedSource(cn, sizeof(cn))));

// if current time not within the bounds of valid date, note it's expired
if (X509_cmp_time(X509_get_notAfter(cert), nullptr) != 1 || X509_cmp_time(X509_get_notBefore(cert), nullptr) != -1)
{
ShowWarning(fmt::format("Existing {} is not valid for the current time. Please regenerate or obtain a new certificate.", certFile));
}
}

X509_free(cert);
fclose(fileHandle);
}
keyHandle = fopen(keyFile.c_str(), "wx");
}

if (!std::filesystem::exists(keyFile) && !std::filesystem::exists(certFile))
if (keyHandle)
{
ShowInfo("Generating self-signed certificate");

EVP_PKEY* pkey = [&]()
{
if (ellipticCurve)
{
return EVP_EC_gen("P-256");
}

return EVP_RSA_gen(4096);
}();

EVP_PKEY* pkey = EVP_RSA_gen(4096);
if (pkey == nullptr)
{
ShowError("Failed to generate private key!");
Expand Down Expand Up @@ -123,8 +80,7 @@ inline void generateSelfSignedCert(const std::string& name = "login", const bool

authIpAddr.copy(reinterpret_cast<char*>(commonNameIpAddr), sizeof(commonNameIpAddr) - 1);

const auto organization = fmt::format("LSB self-signed certificate for {} server", name);
X509_NAME_add_entry_by_txt(subject, "O", MBSTRING_ASC, reinterpret_cast<const unsigned char*>(organization.c_str()), -1, -1, 0);
X509_NAME_add_entry_by_txt(subject, "O", MBSTRING_ASC, reinterpret_cast<const unsigned char*>("LSB self-signed certificate"), -1, -1, 0);
X509_NAME_add_entry_by_txt(subject, "CN", MBSTRING_ASC, commonNameIpAddr, -1, -1, 0);

X509_set_issuer_name(x509, subject);
Expand All @@ -134,28 +90,108 @@ inline void generateSelfSignedCert(const std::string& name = "login", const bool
ShowError("Failed to sign X509 cert!");
}

FILE* fileHandle = fopen(keyFile.c_str(), "wb");
if (fileHandle)
if (!PEM_write_PrivateKey(keyHandle, pkey, nullptr, nullptr, 0, nullptr, nullptr))
{
if (!PEM_write_PrivateKey(fileHandle, pkey, nullptr, nullptr, 0, nullptr, nullptr))
{
ShowError(fmt::format("Failed to write {}!", keyFile));
}
fclose(fileHandle);
ShowError(fmt::format("Failed to write {}!", keyFile));
}
fclose(keyHandle);

fileHandle = fopen(certFile.c_str(), "wb");
// the cert appears in one step, so its presence means the pair is complete
const auto certTemp = certFile + ".tmp";
FILE* fileHandle = fopen(certTemp.c_str(), "wb");
if (fileHandle)
{
if (!PEM_write_X509(fileHandle, x509))
{
ShowError(fmt::format("Failed to write {}!", certFile));
}
fclose(fileHandle);

std::error_code ec;
std::filesystem::rename(certTemp, certFile, ec);
if (ec)
{
ShowError(fmt::format("Failed to write {}! ({})", certFile, ec.message()));
}
}
EVP_PKEY_free(pkey);
X509_free(x509);
}

// another server may still be generating the pair
for (int attempt = 0; attempt < 300 && std::filesystem::exists(keyFile) && !std::filesystem::exists(certFile); ++attempt)
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

if (std::filesystem::exists(keyFile))
{
FILE* fileHandle = fopen(keyFile.c_str(), "r");
if (fileHandle)
{
EVP_PKEY* pkey = PEM_read_PrivateKey(fileHandle, nullptr, nullptr, nullptr);
if (pkey)
{
ShowInfo(fmt::format("Found existing {}", keyFile));
}

EVP_PKEY_free(pkey);
fclose(fileHandle);
}
}

if (std::filesystem::exists(certFile))
{
FILE* fileHandle = fopen(certFile.c_str(), "r");
if (fileHandle)
{
X509* cert = PEM_read_X509(fileHandle, nullptr, nullptr, nullptr);
if (cert)
{
char cn[2048] = {};
int size = sizeof(cn);

X509_NAME_oneline(X509_get_subject_name(cert), cn, size);
X509_NAME_oneline(X509_get_issuer_name(cert), cn, size);

// This is internal, so we can trust it.
ShowInfo(fmt::format("Found existing {}: {}", certFile, asStringFromUntrustedSource(cn, sizeof(cn))));

// if current time not within the bounds of valid date, note it's expired
if (X509_cmp_time(X509_get_notAfter(cert), nullptr) != 1 || X509_cmp_time(X509_get_notBefore(cert), nullptr) != -1)
{
ShowWarning(fmt::format("Existing {} is not valid for the current time. Please regenerate or obtain a new certificate.", certFile));
}
}

X509_free(cert);
fclose(fileHandle);
}
}
}

// TLS 1.3 server context loaded with the shared key and cert
inline auto serverContext() -> asio::ssl::context
{
const auto keyFile = settings::get<std::string>("network.TLS_KEY");
const auto certFile = settings::get<std::string>("network.TLS_CERT");

asio::ssl::context context(asio::ssl::context::tlsv13_server);
context.set_options(asio::ssl::context::default_workarounds);

asio::error_code ec;
context.use_certificate_chain_file(certFile, ec);
if (!ec)
{
context.use_private_key_file(keyFile, asio::ssl::context::file_format::pem, ec);
}

if (ec)
{
throw std::runtime_error(fmt::format("Cannot load {} and {} ({})", certFile, keyFile, ec.message()));
}

return context;
}

} // namespace certificateHelpers
Loading
Loading