Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/tls 49 #51

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@ In your Package Manager settings add the following package source for developmen
cappedCollectionSize="Long"
cappedCollectionMaxItems="Long"
databaseName="String"
includeDefaults="Boolean">
includeDefaults="Boolean"
useTls="Boolean"
clientCertificate="String"
clientCertificatePassword="String">

<!-- repeated -->
<field name="String" layout="Layout" bsonType="Boolean|DateTime|Double|Int32|Int64|String" />
Expand All @@ -65,6 +68,12 @@ _connectionString_ - Connection string. When provided, it overrides the values s

_databaseName_ - The name of the database, overrides connection string database.

_useTls_ - If a Tls connection should be established.

_clientCertificate_ - The certificate to use when establishing a Tls connection.

_clientCertificatePassword- - The certificate's password.

### Collection Options
_collectionName_ - The name of the MongoDB collection to write logs to.

Expand Down
12 changes: 12 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
version: '3.1'

services:

mongo:
image: mongo
restart: always
volumes:
- ./tls/:/etc/tls
ports:
- "27017"
command: --tlsMode requireTLS --tlsCertificateKeyFile /etc/tls/mongodb.pem
42 changes: 41 additions & 1 deletion src/NLog.Mongo/MongoTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Reflection;
using System.Runtime.InteropServices;
using MongoDB.Bson;
Expand Down Expand Up @@ -161,6 +163,26 @@ public string CollectionName
/// </summary>
public bool IncludeEventProperties { get; set; }

/// <summary>
/// Gets or sets if TLS should be used when connecting to MongoDB
/// </summary>
public bool UseTls { get; set; }

/// <summary>
/// Gets or sets the client certificate to use when connecting to MongoDB
/// </summary>
public string ClientCertificate { get; set; }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recommended to use NLog Layout instead of string. If ClientCertificate is a file-path, then maybe include that in the property-name.


/// <summary>
/// Gets or sets the client certificate password to use when connecting to MongoDB
/// </summary>
public string ClientCertificatePassword { get; set; }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recommended to use NLog Layout instead of string.


/// <summary>
/// Gets or sets the Check Certificate Revocation when connecting to MongoDB
/// </summary>
public bool? CheckCertificateRevocation { get; set; }

/// <summary>
/// Initializes the target. Can be used by inheriting classes
/// to initialize logging.
Expand Down Expand Up @@ -404,8 +426,26 @@ private IMongoCollection<BsonDocument> GetCollection()
databaseName = !string.IsNullOrEmpty(databaseName) ? databaseName : (mongoUrl.DatabaseName ?? "NLog");
collectionName = !string.IsNullOrEmpty(collectionName) ? collectionName : "Log";
InternalLogger.Info("Connecting to MongoDB collection {0} in database {1}", collectionName, databaseName);

var settings = MongoClientSettings.FromUrl(mongoUrl);

if (UseTls)
{
var cert = new X509Certificate2(ClientCertificate, ClientCertificatePassword);

if (cert == null)
{
throw new InvalidOperationException("Unable to load certificate");
}

settings.SslSettings = new SslSettings
{
ClientCertificates = new[] { cert },
};
UseTls = true;
}

var client = new MongoClient(mongoUrl);
var client = new MongoClient(settings);

// Database name overrides connection string
var database = client.GetDatabase(databaseName);
Expand Down
17 changes: 13 additions & 4 deletions test/NLog.Mongo.ConsoleTest/NLog.config
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
<target xsi:type="Mongo"
connectionString="mongodb://localhost/Logging"
collectionName="DefaultLog"
cappedCollectionSize="26214400">
cappedCollectionSize="26214400"
useTls="true"
clientCertificate="/home/administrator/src/github/NLog.Mongo/src/tls/mongodb.pem"
clientCertificatePassword="mongo">
<property name="ThreadID" layout="${threadid}" bsonType="Int32" />
<property name="ThreadName" layout="${threadname}" />
<property name="ProcessID" layout="${processid}" bsonType="Int32" />
Expand All @@ -27,21 +30,27 @@
connectionString="mongodb://localhost"
databaseName="CustomLogging"
collectionName="DefaultLog"
cappedCollectionSize="26214400">
cappedCollectionSize="26214400"
useTls="true"
clientCertificate="/home/administrator/src/github/NLog.Mongo/src/tls/mongodb.pem"
clientCertificatePassword="mongo">
<property name="ThreadID" layout="${threadid}" bsonType="Int32" />
<property name="ThreadName" layout="${threadname}" />
<property name="ProcessID" layout="${processid}" bsonType="Int32" />
<property name="ProcessName" layout="${processname:fullName=true}" />
<property name="UserName" layout="${windows-identity}" />
</target>
</target>
</target>

<target xsi:type="Mongo"
name="mongoCustom"
includeDefaults="false"
connectionString="mongodb://localhost/Logging"
collectionName="CustomLog"
cappedCollectionSize="26214400">
cappedCollectionSize="26214400"
useTls="true"
clientCertificate="/home/administrator/src/github/NLog.Mongo/src/tls/mongodb.pem"
clientCertificatePassword="mongo">

<field name="Date" layout="${date}" bsonType="DateTime" />
<field name="Level" layout="${level}"/>
Expand Down
17 changes: 17 additions & 0 deletions tls/create-cert.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# https://medium.com/@rajanmaharjan/secure-your-mongodb-connections-ssl-tls-92e2addb3c89

# root ca
openssl genrsa -out rootCA.key 2048
openssl genrsa -des3 -out rootCA.key 2048 # password is mongo
openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem

# per device
openssl genrsa -out mongodb.key 2048
# Whatever you see in the address field in your browser when you go to your device
# must be what you put under common name, even if it’s an IP address.
openssl req -new -key mongodb.key -out mongodb.csr # answer Common Name (eg, YOUR name) []: localhost

openssl x509 -req -in mongodb.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out mongodb.crt -days 500 -sha256
cat mongodb.key mongodb.crt > mongodb.pem

# run mongo using docker-compose or the following command: mongod --tlsMode requireTLS --tlsCertificateKeyFile tls/mongodb.pem