Skip to content
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
64 changes: 64 additions & 0 deletions docs/index.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ Please check out <<plugins-{type}s-{plugin}-obsolete-options>> for details.
| <<plugins-{type}s-{plugin}-ssl_keystore_password>> |<<password,password>>|No
| <<plugins-{type}s-{plugin}-ssl_keystore_path>> |<<path,path>>|No
| <<plugins-{type}s-{plugin}-ssl_keystore_type>> |<<string,string>>|No
| <<plugins-{type}s-{plugin}-ssl_peer_metadata>> |<<boolean,boolean>>|No
| <<plugins-{type}s-{plugin}-ssl_supported_protocols>> |<<array,array>>|No
| <<plugins-{type}s-{plugin}-ssl_truststore_password>> |<<password,password>>|No
| <<plugins-{type}s-{plugin}-ssl_truststore_path>> |<<path,path>>|No
Expand Down Expand Up @@ -427,6 +428,69 @@ The format of the keystore file. It must be either `jks` or `pkcs12`.

Set the JKS keystore password

[id="plugins-{type}s-{plugin}-ssl_peer_metadata"]
===== `ssl_peer_metadata`

* Value type is <<boolean,boolean>>
* Default value is `false`

When a client connects using mutual TLS, add the details of its certificate to the `[@metadata]` field of the events.
Requires <<plugins-{type}s-{plugin}-ssl_client_authentication>> to be `optional` or `required`.
The `tls_peer` entries mirror those of the {logstash-ref}/plugins-inputs-beats.html[beats input].

[cols="<l,<l,<e",options="header"]
|=======================================================================
|ECS `v1`, `v8` |ECS `disabled` |Description

|[@metadata][tls_peer][status]
|[@metadata][tls_peer][status]
|`verified` when the client presented a certificate (which was validated), `unverified` otherwise. The other entries are only available when `verified`.

|[@metadata][input][http][tls][client][subject]
|[@metadata][tls_peer][subject]
|Distinguished name of the certificate subject (RFC 2253), such as `CN=client,O=Logstash`

|[@metadata][input][http][tls][version_protocol]
|[@metadata][tls_peer][protocol]
|TLS version used, such as `TLSv1.3`

|[@metadata][input][http][tls][cipher]
|[@metadata][tls_peer][cipher_suite]
|Cipher suite used

|[@metadata][input][http][tls][client][x509][subject][common_name]
|[@metadata][tls_peer][subject_cn]
|Most specific common name of the subject, when present

|[@metadata][input][http][tls][client][issuer]
|[@metadata][tls_peer][issuer_dn]
|Distinguished name of the issuer (RFC 2253)

|[@metadata][input][http][tls][client][x509][serial_number]
|[@metadata][tls_peer][serial]
|Serial number, in lowercase hexadecimal

|[@metadata][input][http][tls][client][not_before]
|[@metadata][tls_peer][not_before]
|Start of the validity period, as an ISO-8601 timestamp

|[@metadata][input][http][tls][client][not_after]
|[@metadata][tls_peer][not_after]
|End of the validity period, as an ISO-8601 timestamp

|[@metadata][input][http][tls][client][hash][sha256]
|[@metadata][tls_peer][fingerprint_sha256]
|SHA-256 fingerprint of the certificate, in lowercase hexadecimal

|[@metadata][input][http][tls][client][x509][alternative_names]
|[@metadata][tls_peer][sans]
|Array of subject alternative names, formatted as `type:value` (types: `dns`, `email`, `uri`, `ip`, `dir`)
|=======================================================================

NOTE: Request headers whose name starts with `Tls-Peer-` are always discarded, so a client cannot forge these details.
The `[@metadata]` field is not persisted by outputs: copy what you need into regular fields with a filter, for example
`mutate { copy => { "[@metadata][tls_peer][subject_cn]" => "client_cn" } }`.

[id="plugins-{type}s-{plugin}-ssl_supported_protocols"]
===== `ssl_supported_protocols`

Expand Down
61 changes: 57 additions & 4 deletions lib/logstash/inputs/http.rb
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ class LogStash::Inputs::Http < LogStash::Inputs::Base
# target field for the client host of the http request
config :request_headers_target_field, :validate => :string

# when mutual TLS is in use, add the details of the client certificate to `[@metadata][tls_peer]`
config :ssl_peer_metadata, :validate => :boolean, :default => false

config :threads, :validate => :number, :required => false, :default => ::LogStash::Config::CpuCoreStrategy.maximum

config :max_pending_requests, :validate => :number, :required => false, :default => 200
Expand Down Expand Up @@ -155,6 +158,29 @@ class LogStash::Inputs::Http < LogStash::Inputs::Base
'cipher_suites',
].freeze

# Where the client certificate details are stored, by `ecs_compatibility`. Mirrors the `beats` input (`ssl_peer_metadata`),
# extended with details ECS has fields for (`tls.client.*`).
TLS_PEER_FIELDS = {
disabled: %w(status subject protocol cipher_suite subject_cn issuer_dn serial not_before not_after fingerprint_sha256 sans)
.map { |name| [name, "[@metadata][tls_peer][#{name}]"] }.to_h.freeze,
v1: {
'status' => '[@metadata][tls_peer][status]',
'subject' => '[@metadata][input][http][tls][client][subject]',
'protocol' => '[@metadata][input][http][tls][version_protocol]',
'cipher_suite' => '[@metadata][input][http][tls][cipher]',
'subject_cn' => '[@metadata][input][http][tls][client][x509][subject][common_name]',
'issuer_dn' => '[@metadata][input][http][tls][client][issuer]',
'serial' => '[@metadata][input][http][tls][client][x509][serial_number]',
'not_before' => '[@metadata][input][http][tls][client][not_before]',
'not_after' => '[@metadata][input][http][tls][client][not_after]',
'fingerprint_sha256' => '[@metadata][input][http][tls][client][hash][sha256]',
'sans' => '[@metadata][input][http][tls][client][x509][alternative_names]',
}.freeze
}.freeze

# Prefix of the pseudo request headers carrying the client certificate details (see `TlsPeerInfo.java`)
TLS_PEER_HEADER_PREFIX = 'tls_peer_'.freeze

SSL_CLIENT_AUTH_NONE = 'none'.freeze
SSL_CLIENT_AUTH_OPTIONAL = 'optional'.freeze
SSL_CLIENT_AUTH_REQUIRED = 'required'.freeze
Expand All @@ -165,6 +191,8 @@ class LogStash::Inputs::Http < LogStash::Inputs::Base
'force_peer' => SSL_CLIENT_AUTH_REQUIRED
}.freeze

private_constant :TLS_PEER_FIELDS
private_constant :TLS_PEER_HEADER_PREFIX
private_constant :SSL_CLIENT_AUTH_NONE
private_constant :SSL_CLIENT_AUTH_OPTIONAL
private_constant :SSL_CLIENT_AUTH_REQUIRED
Expand Down Expand Up @@ -202,6 +230,7 @@ def register

@remote_host_target_field ||= ecs_select[disabled: "host", v1: "[host][ip]"]
@request_headers_target_field ||= ecs_select[disabled: "headers", v1: "[@metadata][input][http][request][headers]"]
@tls_peer_fields = ecs_select[disabled: TLS_PEER_FIELDS[:disabled], v1: TLS_PEER_FIELDS[:v1]]
end # def register

def run(queue)
Expand All @@ -221,8 +250,9 @@ def close
def decode_body(headers, remote_address, body, default_codec, additional_codecs)
content_type = headers.fetch("content_type", "")
codec = additional_codecs.fetch(HttpUtil.getMimeType(content_type), default_codec)
codec.decode(body) { |event| push_decoded_event(headers, remote_address, event) }
codec.flush { |event| push_decoded_event(headers, remote_address, event) }
tls_peer = extract_tls_peer!(headers)
codec.decode(body) { |event| push_decoded_event(headers, remote_address, tls_peer, event) }
codec.flush { |event| push_decoded_event(headers, remote_address, tls_peer, event) }
true
rescue => e
@logger.error(
Expand All @@ -234,14 +264,33 @@ def decode_body(headers, remote_address, body, default_codec, additional_codecs)
false
end

def push_decoded_event(headers, remote_address, event)
# Moves the client certificate details out of the request headers.
# @return [Hash] the details without their prefix, empty unless the client presented a certificate
def extract_tls_peer!(headers)
headers.key_set.to_a.each_with_object({}) do |key, tls_peer|
next unless key.start_with?(TLS_PEER_HEADER_PREFIX)
name = key.delete_prefix(TLS_PEER_HEADER_PREFIX)
value = headers.remove(key)
tls_peer[name] = name == 'sans' ? value.split("\n") : value
end
end

def push_decoded_event(headers, remote_address, tls_peer, event)
add_ecs_fields(headers, event)
add_tls_peer_fields(tls_peer, event) if @ssl_peer_metadata
event.set(@request_headers_target_field, headers)
event.set(@remote_host_target_field, remote_address)
decorate(event)
@queue << event
end

def add_tls_peer_fields(tls_peer, event)
tls_peer.each do |name, value|
field = @tls_peer_fields[name]
event.set(field, value) if field
end
end

def add_ecs_fields(headers, event)
return if ecs_compatibility == :disabled

Expand Down Expand Up @@ -313,6 +362,10 @@ def validate_ssl_settings!
end

cli_auth_config_name, cli_auth_optional_val, cli_auth_required_val = provided_ssl_client_authentication_config([SSL_CLIENT_AUTH_OPTIONAL, SSL_CLIENT_AUTH_REQUIRED])
if @ssl_peer_metadata && !ssl_client_authentication_enabled?
raise LogStash::ConfigurationError, "Using `ssl_peer_metadata` requires setting `#{cli_auth_config_name}` to `#{cli_auth_optional_val}` or `#{cli_auth_required_val}`"
end

if ssl_client_authentication_enabled?
# Ensure any CA is configured. By default, the keystore can also be used as CA
unless ssl_certificate_authorities_configured? || ssl_truststore_configured? || ssl_keystore_configured?
Expand Down Expand Up @@ -340,7 +393,7 @@ def setup_ssl_params!
def create_http_server(message_handler)
org.logstash.plugins.inputs.http.NettyHttpServer.new(
@id, @host, @port, message_handler, build_ssl_params, @threads,
@max_pending_requests, @max_content_length, @response_code)
@max_pending_requests, @max_content_length, @response_code, @ssl_peer_metadata)
end

def build_ssl_params
Expand Down
87 changes: 87 additions & 0 deletions spec/inputs/http_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,77 @@
expect(event.get("message")).to eq("Hello")
end

context 'client certificate details' do
let(:config) { super().merge 'request_headers_target_field' => 'headers' }
let(:forged_headers) { { 'Tls-Peer-Subject-Cn' => 'forged', 'Tls-Peer-Subject-Dn' => 'CN=forged' } }
let(:response) { client.post(url, :body => { "message" => "Hello" }.to_json, :headers => forged_headers).call }
let(:event) { expect(response.code).to eq(200); logstash_queue.pop }

context 'by default' do
it "does not add them to the event" do
expect(event.get('[@metadata][tls_peer]')).to be_nil
expect(event.get('[@metadata][input][http][tls]')).to be_nil
end

it "does not leak them (nor the forged ones) in the request headers" do
expect(event.get('headers').keys.grep(/^tls_peer_/)).to be_empty
end
end

tls_peer_fields = {
'disabled' => Hash.new { |_, name| "[@metadata][tls_peer][#{name}]" },
'v1' => {
'status' => '[@metadata][tls_peer][status]',
'subject' => '[@metadata][input][http][tls][client][subject]',
'protocol' => '[@metadata][input][http][tls][version_protocol]',
'cipher_suite' => '[@metadata][input][http][tls][cipher]',
'subject_cn' => '[@metadata][input][http][tls][client][x509][subject][common_name]',
'issuer_dn' => '[@metadata][input][http][tls][client][issuer]',
'serial' => '[@metadata][input][http][tls][client][x509][serial_number]',
'not_before' => '[@metadata][input][http][tls][client][not_before]',
'not_after' => '[@metadata][input][http][tls][client][not_after]',
'fingerprint_sha256' => '[@metadata][input][http][tls][client][hash][sha256]',
'sans' => '[@metadata][input][http][tls][client][x509][alternative_names]',
}
}

tls_peer_fields.each do |ecs_mode, fields|
context "with ssl_peer_metadata enabled and `ecs_compatibility => #{ecs_mode}`" do
let(:config) { super().merge 'ssl_peer_metadata' => true, 'ecs_compatibility' => ecs_mode }

it "adds the details of the client certificate to the metadata" do
expect(event.get(fields['status'])).to eq('verified')
expect(event.get(fields['subject'])).to eq('CN=client,O=Logstash,L=Http Input,ST=NA,C=LS')
expect(event.get(fields['subject_cn'])).to eq('client')
expect(event.get(fields['issuer_dn'])).to eq('CN=root,O=Logstash,L=Http Input,ST=NA,C=LS')
expect(event.get(fields['serial'])).to eq('4')
expect(event.get(fields['not_before'])).to match(/\A\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z\z/)
expect(event.get(fields['not_after'])).to match(/\A\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z\z/)
expect(event.get(fields['fingerprint_sha256'])).to match(/\A\h{64}\z/)
expect(event.get(fields['sans'])).to contain_exactly('dns:localhost', 'ip:127.0.0.1')
expect(event.get(fields['protocol'])).to match(/\ATLSv1\.[23]\z/)
expect(event.get(fields['cipher_suite'])).to start_with('TLS_')
end

it "ignores the headers forged by the client" do
expect(event.get(fields['subject_cn'])).to eq('client')
expect(event.get('headers').keys.grep(/^tls_peer_/)).to be_empty
end

context 'when the client does not present a certificate' do
let(:client_options) { super().merge ssl: { verify: false, ca_file: certificate_path('root.crt') } }

it "only flags the peer as unverified, and does not trust forged headers" do
expect(event.get(fields['status'])).to eq('unverified')
expect(event.get(fields['subject'])).to be_nil
expect(event.get(fields['subject_cn'])).to be_nil
expect(event.get('headers').keys.grep(/^tls_peer_/)).to be_empty
end
end
end
end
end

TLS13_ENABLED_BY_DEFAULT = begin
context = javax.net.ssl.SSLContext.getInstance('TLS')
context.init nil, nil, nil
Expand Down Expand Up @@ -687,6 +758,22 @@ def setup_server_client(url = self.url)
end
end

context "with ssl_peer_metadata" do
let(:config) { super().merge("ssl_peer_metadata" => true) }

it "should raise a configuration error without client authentication" do
expect { subject.register }.to raise_error LogStash::ConfigurationError, /ssl_peer_metadata.*requires/
end

context "and optional client authentication" do
let(:config) { super().merge("ssl_client_authentication" => "optional", "ssl_certificate_authorities" => [ssl_certificate.path]) }

it "should not raise exception" do
expect { subject.register }.to_not raise_exception
end
end
end

context "with ssl_verify_mode = none" do
subject { LogStash::Inputs::Http.new(config.merge("ssl_client_authentication" => "none")) }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
public class HttpInitializer extends ChannelInitializer<SocketChannel> {
private final IMessageHandler messageHandler;
private SslHandlerProvider sslHandlerProvider;
private boolean exposeTlsPeerInfo = false;
private final int maxContentLength;
private final HttpResponseStatus responseStatus;
private final ThreadPoolExecutor executorGroup;
Expand Down Expand Up @@ -52,7 +53,12 @@ protected void initChannel(SocketChannel socketChannel) throws Exception {
pipeline.addLast(new RejectWhenBlockedInboundHandler(executionObserver, Duration.ofSeconds(10)));
pipeline.addLast(new HttpContentDecompressor());
pipeline.addLast(new HttpObjectAggregator(maxContentLength));
pipeline.addLast(new HttpServerHandler(messageHandler.copy(), executorGroup, responseStatus));
pipeline.addLast(new HttpServerHandler(messageHandler.copy(), executorGroup, responseStatus, exposeTlsPeerInfo));
}

/** Makes the details of the client certificate available to the message handler (requires SSL). */
public void enableTlsPeerInfo() {
this.exposeTlsPeerInfo = true;
}

public void enableSSL(SslHandlerProvider sslHandlerProvider) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

import org.logstash.plugins.inputs.http.util.TlsPeerInfo;

import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

import static io.netty.buffer.Unpooled.copiedBuffer;
Expand All @@ -23,19 +27,27 @@ public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpReque
private final IMessageHandler messageHandler;
private final ThreadPoolExecutor executorGroup;
private final HttpResponseStatus responseStatus;
private final boolean exposeTlsPeerInfo;

public HttpServerHandler(IMessageHandler messageHandler, ThreadPoolExecutor executorGroup,
HttpResponseStatus responseStatus) {
this(messageHandler, executorGroup, responseStatus, false);
}

public HttpServerHandler(IMessageHandler messageHandler, ThreadPoolExecutor executorGroup,
HttpResponseStatus responseStatus, boolean exposeTlsPeerInfo) {
this.messageHandler = messageHandler;
this.executorGroup = executorGroup;
this.responseStatus = responseStatus;
this.exposeTlsPeerInfo = exposeTlsPeerInfo;
}

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) {
final String remoteAddress = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
msg.retain();
final MessageProcessor messageProcessor = new MessageProcessor(ctx, msg, remoteAddress, messageHandler, responseStatus);
final Map<String, String> tlsPeerInfo = exposeTlsPeerInfo ? TlsPeerInfo.of(ctx) : Collections.emptyMap();
final MessageProcessor messageProcessor = new MessageProcessor(ctx, msg, remoteAddress, tlsPeerInfo, messageHandler, responseStatus);
executorGroup.execute(messageProcessor);
}

Expand Down
Loading
Loading