29 Commits

Author SHA1 Message Date
Ryan Smith
a9dcc759f7 build: update modules 2025-05-08 16:35:03 -07:00
Ryan Smith
f9d7b767bc refactor: switch from net.IP to netip.Addr
This change switches net.IP to netip.Addr added in Go 1.18. This results in slightly better performance and memory utilization for very large threat feeds (over 500,000 entries).
2025-05-08 16:26:33 -07:00
Ryan Smith
375da6eeac feat: log custom header as source IP if set
This change updates the logging behavior of the HTTP honeypot. If a custom custom source IP header is configured:
- The actual connecting IP is logged as `remote_ip`.
- The IP extracted from the header is logged as `source_ip`.
- Any problems extracting an IP from the header results in `source_ip` falling back to the actual connecting IP.
- A new `source_ip_parsed` field indicates whether an IP was extrracted from the header.
- If parsing fails, a `source_ip_error` field is included with the error message.

If no custom header is configured, logging behavior remains unchanged.

This change improves usability of the threat feed web interface when you have HTTP honeypots behind a proxy. By logging the original client IP as `source_ip`, the application now correctly displays the actual source of the connection, rather than your proxy's IP address.
2025-05-08 13:45:58 -07:00
Ryan Smith
dc06d64b5b build: prevent -dirty tag in Docker builds
Ensure Docker builds don't add a `-dirty` suffix to the version number.

When building for Docker, `make` is called which in turn calls `git describe` to get the version number. Sometimes this would append `-dirty` even when clean.

This change adds `git update-index -q --refresh` before calling `make` to ensure the version tag is returned correctly.
2025-04-16 15:34:47 -07:00
Ryan Smith
41345f04bd build: add Linux ARM64 build target 2025-04-16 10:34:48 -07:00
Ryan Smith
c0e6010143 build: replace amd64 with x64 in binary names
This change replaces 'amd64' with 'x64' in the file names of the output binaries.

The binary names are now set directly in each build target, rather than declared as variables.
2025-04-16 10:33:36 -07:00
Ryan Smith
2736c20158 feat(threatfeed): display TLS configuration 2025-04-16 08:51:08 -07:00
Ryan Smith
8ebec3a8c4 feat: add TLS support to threat feed server
This change adds optional support for running the threat feed server over HTTPS. This is controlled via the configuration file. Depending on the confgiuration, the threat feed may operate over either HTTP or HTTPS, but not both.

The following configuration options are added to the threat feed (the `<threatFeed>` section in the conffguration file):
- `<enableTLS>` - If `true`, the threat feed uses TLS. If `false` or if this is missing, use HTTP.
- `<certPath>` - Path to TLS cert in PEM format.
- `<keyPath>` - Path to private key in PEM format.

Default configuration files are updated to include the new settings. The TLS feature is off by default. Existing user configuration files only need to be updated if this feature is needed. Otherwise, existing configuration files start the threat feed using HTTP as before.

When the threat feed server starts in TLS mode, it automatically generates a self-signed cert if the cert and key files aen't found.
2025-04-16 08:33:36 -07:00
Ryan Smith
650489bd5c feat: add fixed delay to basic auth 2025-04-16 07:44:24 -07:00
Ryan Smith
da42f21f75 refactor: move cert generator to separate package 2025-04-16 07:43:15 -07:00
Ryan Smith
0a4d4536ba chore: revise error strings and comments 2025-04-16 07:35:58 -07:00
Ryan Smith
148d99876f build: update modules 2025-04-16 07:24:18 -07:00
Ryan Smith
90fbc24479 feat: controlled error responses for HTTP honeypot
Add `withCustomError` middleware that intercepts HTTP error responses and replaces them with a custom error response.

This is used when the HTTP honeypot is configured to serve content from a directory. It ensures that all error responses from http.FileServerFS are controlled and predicatable.
2025-04-15 14:44:26 -07:00
Ryan Smith
60fe095dff feat: disable directory listings when serving custom content
Add noDirectoryFS wrapper to disable directory listings from http.FileServerFS. This is used when the HTTP honeypot is configured to serve custom content from a specified directory.
2025-04-15 14:39:07 -07:00
Ryan Smith
40dbc05d6f feat: serve content from a directory in HTTP honeypot
Add support for serving static files from a directory specified via the existing `homePagePath` setting. When this setting points to a directory, the honeypot serves files rooted at that directory. The original behavior of serving a single file is still supported.

When serving from a directory, the honeypot may serve files from the directory root and from any subdirectories. Symbolic links are followed, provided they don't lead outside the specified root directory.

Main changes:
- Add `responseMode` type to represent how the honeypot serves content (built-in default, specific file, files from a directory).
- Add `responseConfig` struct to store the responseMode and related configuration.
- Add `determineConfig` function to construct a responseConfig when the honeypot starts.
- Update the honeypot request handler to serve content based on the response mode.
- Add `serveErrorPage` function to serve error responses as needed.
2025-04-15 12:48:58 -07:00
Ryan Smith
9e14d3886a Merge pull request #1 from eltociear/patch-1
docs: update README.md
2025-04-10 07:10:47 -07:00
Ikko Eltociear Ashimine
abaa098099 docs: update README.md
honeyot  -> honeypot
2025-04-10 14:51:00 +09:00
Ryan Smith
62b166c62a Update README.md
Update threat feed example output to show 'observations' count rather than 'threat_score'. The threat score feature was replaced with observation count in a previous change.
2025-04-08 11:10:18 -07:00
Ryan Smith
53fd03cd46 Revise screenshot 2025-04-08 10:37:21 -07:00
Ryan Smith
a1dfb7f648 threatfeed: Pre-parse and cache html templates
This change pre-parses all html templates from the `templates` directory and stores the results globally. With this change, http handlers no longer need to re-parse templates on every request.
2025-04-07 16:57:09 -07:00
Ryan Smith
540b0b940c threatfeed: Add honeypot log data statistics
This change adds the ability to view various statistics for honeypot log data. This includes views such as unique SSH usernames, unique HTTP paths, unique HTTP host headers, etc.

A new `/logs/{logtype}/{subtype}` route is added for rendering stats.
2025-04-07 16:40:18 -07:00
Ryan Smith
7bc73f6695 threatfeed: move nav bar to dedicated template
This change moves the nav bar for the threat feed web interface to a dedicated template defined in `nav.html`. HTTP handlers and existing HTML templates are updated to utilize the new template.
2025-04-06 22:44:27 -07:00
Ryan Smith
d0f046593e theatfeed: tooltips in live feed + style updates
This change adds tooltips to the live logs for HTTP log data. Hovering over an HTTP even reveals the full HTTP request details.

Updated style.css to support the new tooltips.

Other changes:
- Minor color changes applied to the web feed.
- Minor text revisions in `home.html` and `docs.html`.
2025-04-06 20:15:54 -07:00
Ryan Smith
444a446b0f webfeed: format dates and numbers via javascript
This change adjusts the webfeed.html template to return timestamps in ISO 8601 format in UTC and instead uses JavaScript to format and display using the user's local time.

JavaScript is also used to add a thousands seprator to values in the 'Observations' column.

When formatting the 'Added' column, the time is dropped and now displays as YYYY-MM-DD.
2025-04-06 14:55:18 -07:00
Ryan Smith
0462ed7b4c Explicitly ignore errors in WS handlers 2025-04-05 14:27:00 -07:00
Ryan Smith
ecbe1d4972 Append -dirty or -broken tag to version if local changes found 2025-04-05 14:26:10 -07:00
Ryan Smith
4eebe8029f Revise screenshots 2025-04-04 14:51:40 -07:00
Ryan Smith
0e66c52a16 Update README.md 2025-04-04 09:32:54 -07:00
Ryan Smith
7334aac745 Update screenshots 2025-04-04 08:30:35 -07:00
35 changed files with 1170 additions and 835 deletions

View File

@@ -2,6 +2,7 @@
FROM golang:latest AS build-stage
WORKDIR /build
COPY . .
RUN git update-index -q --refresh
RUN make
FROM alpine:latest

View File

@@ -2,13 +2,10 @@
SOURCE := ./cmd/deceptifeed/
BIN_DIRECTORY := ./bin/
BIN_DEFAULT := deceptifeed
BIN_LINUX := $(BIN_DEFAULT)_linux_amd64
BIN_FREEBSD := $(BIN_DEFAULT)_freebsd_amd64
BIN_WINDOWS := $(BIN_DEFAULT)_windows_amd64.exe
BIN_DEFAULT := $(BIN_DIRECTORY)deceptifeed
INSTALL_SCRIPT := ./scripts/install.sh
UNINSTALL_SCRIPT := ./scripts/install.sh --uninstall
VERSION := $(shell git describe --tags)
VERSION := $(shell git describe --tags --dirty --broken)
BUILD_OPTIONS := -trimpath -ldflags="-s -w -X 'github.com/r-smith/deceptifeed/internal/config.Version=$(VERSION:v%=%)'"
GO := go
CGO_ENABLED := 0
@@ -17,39 +14,47 @@ CGO_ENABLED := 0
build:
@echo "Building for current operating system..."
@mkdir -p $(BIN_DIRECTORY)
CGO_ENABLED=$(CGO_ENABLED) $(GO) build $(BUILD_OPTIONS) -o $(BIN_DIRECTORY)$(BIN_DEFAULT) $(SOURCE)
@echo "Build complete: $(BIN_DIRECTORY)$(BIN_DEFAULT)"
CGO_ENABLED=$(CGO_ENABLED) $(GO) build $(BUILD_OPTIONS) -o $(BIN_DEFAULT) $(SOURCE)
@echo "Build complete: $(BIN_DEFAULT)"
@echo
.PHONY: all
all: build build-linux build-freebsd build-windows
all: build build-linux build-linux-arm build-freebsd build-windows
.PHONY: build-linux
build-linux:
@echo "Building for Linux..."
@mkdir -p $(BIN_DIRECTORY)
GOOS=linux GOARCH=amd64 CGO_ENABLED=$(CGO_ENABLED) $(GO) build $(BUILD_OPTIONS) -o $(BIN_DIRECTORY)$(BIN_LINUX) $(SOURCE)
@echo "Build complete: $(BIN_DIRECTORY)$(BIN_LINUX)"
GOOS=linux GOARCH=amd64 CGO_ENABLED=$(CGO_ENABLED) $(GO) build $(BUILD_OPTIONS) -o $(BIN_DEFAULT)_linux_x64 $(SOURCE)
@echo "Build complete: $(BIN_DEFAULT)_linux_x64"
@echo
.PHONY: build-linux-arm
build-linux-arm:
@echo "Building for Linux (ARM)..."
@mkdir -p $(BIN_DIRECTORY)
GOOS=linux GOARCH=arm64 CGO_ENABLED=$(CGO_ENABLED) $(GO) build $(BUILD_OPTIONS) -o $(BIN_DEFAULT)_linux_ARM64 $(SOURCE)
@echo "Build complete: $(BIN_DEFAULT)_linux_ARM64"
@echo
.PHONY: build-freebsd
build-freebsd:
@echo "Building for FreeBSD..."
@mkdir -p $(BIN_DIRECTORY)
GOOS=freebsd GOARCH=amd64 CGO_ENABLED=$(CGO_ENABLED) $(GO) build $(BUILD_OPTIONS) -o $(BIN_DIRECTORY)$(BIN_FREEBSD) $(SOURCE)
@echo "Build complete: $(BIN_DIRECTORY)$(BIN_FREEBSD)"
GOOS=freebsd GOARCH=amd64 CGO_ENABLED=$(CGO_ENABLED) $(GO) build $(BUILD_OPTIONS) -o $(BIN_DEFAULT)_freebsd_x64 $(SOURCE)
@echo "Build complete: $(BIN_DEFAULT)_freebsd_x64"
@echo
.PHONY: build-windows
build-windows:
@echo "Building for Windows..."
@mkdir -p $(BIN_DIRECTORY)
GOOS=windows GOARCH=amd64 CGO_ENABLED=$(CGO_ENABLED) $(GO) build $(BUILD_OPTIONS) -o $(BIN_DIRECTORY)$(BIN_WINDOWS) $(SOURCE)
@echo "Build complete: $(BIN_DIRECTORY)$(BIN_WINDOWS)"
GOOS=windows GOARCH=amd64 CGO_ENABLED=$(CGO_ENABLED) $(GO) build $(BUILD_OPTIONS) -o $(BIN_DEFAULT)_windows_x64.exe $(SOURCE)
@echo "Build complete: $(BIN_DEFAULT)_windows_x64.exe"
@echo
.PHONY: install
install: $(BIN_DIRECTORY)$(BIN_DEFAULT)
install: $(BIN_DEFAULT)
@bash $(INSTALL_SCRIPT)
.PHONY: uninstall

View File

@@ -6,14 +6,16 @@
</picture>
</p>
`Deceptifeed` is a honeypot and threat feed server. It runs multiple honeypots (deceptive network services), while the threat feed lists IP addresses that have interacted with the honeypots.
`Deceptifeed` is a honeypot and threat feed server. It runs multiple deceptive network services (honeypots), while the threat feed lists IP addresses that have interacted with the honeypots. Additionally, `Deceptifeed` provides real-time visibility into honeypot activity, allowing you to monitor logs and interactions as they occur.
If an IP address interacts with a fake server on your network, why should it be allowed to access your real servers? `Deceptifeed` helps you build an automated defense system to reduce such risks. In a typical deployment, it runs alongside your real servers. The honeypots are exposed to the internet, while the threat feed remains private for use with your internal tools.
When an IP address interacts with a fake server on your network, why should it be allowed to access your real servers? `Deceptifeed` helps you build an automated defense system to reduce such risks. In a typical deployment, it runs alongside your real servers. The honeypots are exposed to the internet, while the threat feed remains private for use with your internal tools.
Most enterprise firewalls support ingesting threat feeds. By pointing to `Deceptifeed`, your firewall can automatically block IP addresses that interact with the honeypots. For other security tools, the threat feed is available in several formats, including plain text, CSV, JSON, and TAXII 2.1.
Most enterprise firewalls support ingesting threat feeds. By pointing to `Deceptifeed`, your firewall can automatically block IP addresses that interact with the honeypots. For other security tools, the threat feed is available in several formats, including plain text, CSV, JSON, and TAXII.
## Deployment Diagram
## Visuals
*Deployment diagram*
<a href="assets/diagram-light.svg?raw=true">
<picture>
@@ -23,6 +25,14 @@ Most enterprise firewalls support ingesting threat feeds. By pointing to `Decept
</picture>
</a>
<br>
<br>
<img alt="Example of the threat feed web interface" src="assets/screenshot-webfeed.png" width="860" />
<br>
<img alt="Example showing real-time honeypot log monitoring" src="assets/screenshot-live.png" width="860" />
## Quick Start
This section guides you through trying Deceptifeed as quickly as possible. There are no dependencies, configuration, or installation required. Refer to the [Installation section](#installation) when you're ready to set up a production environment.
@@ -154,28 +164,36 @@ Here is a breakdown of the arguments:
## Features
- **Multiple Honeypot Servers:** Run any number of honeypot services simultaneously.
- **Threat Feed Server:** A real-time feed of IP addresses that have accessed your honeypots, delivered over HTTP. Available in plain text, CSV, JSON, STIX, and TAXII 2.1.
- **Rich Structured Logging:** Capture detailed logs of honeypot interactions in JSON format.
- **Secure:** The honeypot services never process or respond to client input; they only log the data received. Attackers are not given simulated or virtual environments.
- **Several Honeypot Types:**
- **SSH Honeyot:** Record login attempts to a fake SSH service.
- **HTTP/HTTPS Honeypot:** Record requested URLs and HTTP headers.
- **Generic TCP/UDP Services:** Record data sent by connecting clients.
- **Cross-platform:** Supports Linux, macOS, Windows, and *BSD.
- **Honeypot Servers:**
- Run any number of honeypot services simultaneously.
- Honeypots are low interaction (no simulated environments for attackers to access).
- **SSH honeypot:** Record and reject login attempts to a fake SSH service.
- **HTTP/HTTPS honeypot:** Record requested URLs and HTTP headers.
- **Generic TCP/UDP services:** Record data sent by connecting clients.
- **Threat Feed Server:**
- A feed of IP addresses that have accessed your honeypots, delivered over HTTP.
- Available in plain text, CSV, JSON, STIX, and TAXII.
- Includes a friendly web interface for browsing feed and honeypot data.
- **Rich Structured Logging:**
- Honeypot interactions are logged in a structured JSON format.
- Logs can be optionally forwarded to the SIEM of your choice.
- Automatic log file rollover ensures the system is self-managing.
- **Security:**
- The honeypot services never process or respond to client input.
- Attackers are not given simulated or virtual environments.
- Deceptifeed is self-contained and does **not** use any external libraries, frameworks, plugins, third-party modules, or GitHub actions.
- **Cross-platform:**
- Supports Linux, macOS, Windows, and *BSD.
- Available as a Docker container.
## Threat Feed
The threat feed provides a real-time list of IP addresses that have interacted with your honeypot services. It is delivered over HTTP for easy integration with firewalls. Most enterprise firewalls support ingesting custom threat feeds, allowing them to automatically block communication with the listed IP addresses.
The threat feed provides a list of IP addresses that have interacted with your honeypot services. It is delivered over HTTP for easy integration with firewalls. Most enterprise firewalls support ingesting custom threat feeds, allowing them to automatically block communication with the listed IP addresses.
Configure your firewall to use Deceptifeed as a custom threat feed and set your blocking rules accordingly. Ideally, exclude your honeypot services from any automatic blocking rules.
The threat feed is available in plain text, CSV, JSON, STIX, and TAXII 2.1.
**_Sample threat feed web interface_**
<img alt="Threat Feed Web Interface" src="assets/threatfeed-web-screenshot.png" width="881" />
The threat feed is available in plain text, CSV, JSON, STIX, and TAXII.
**_Sample threat feed in plain text_**
@@ -210,15 +228,15 @@ $ curl http://threatfeed.example.com:9000/json
"threat_feed": [
{
"ip": "10.32.16.110",
"added": "2024-11-12T16:18:36-08:00",
"last_seen": "2024-11-15T04:27:59-08:00",
"threat_score": 27
"added": "2025-02-12T16:18:36-08:00",
"last_seen": "2025-03-15T04:27:59-08:00",
"observations": 27
},
{
"ip": "192.168.2.21",
"added": "2024-11-14T23:09:11-08:00",
"last_seen": "2024-11-17T00:40:51-08:00",
"threat_score": 51
"added": "2025-04-02T23:09:11-08:00",
"last_seen": "2025-04-08T00:40:51-08:00",
"observations": 51
}
]
}

BIN
assets/screenshot-live.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

View File

@@ -14,6 +14,9 @@
<threatExpiryHours>336</threatExpiryHours>
<includePrivateIPs>false</includePrivateIPs>
<excludeListPath></excludeListPath>
<enableTLS>false</enableTLS>
<certPath>/opt/deceptifeed/certs/threatfeed-cert.pem</certPath>
<keyPath>/opt/deceptifeed/certs/threatfeed-key.pem</keyPath>
</threatFeed>
<!-- Honeypot Server Configuration -->

View File

@@ -14,6 +14,9 @@
<threatExpiryHours>336</threatExpiryHours>
<includePrivateIPs>false</includePrivateIPs>
<excludeListPath></excludeListPath>
<enableTLS>false</enableTLS>
<certPath>key-threatfeed-public.pem</certPath>
<keyPath>key-threatfeed-private.pem</keyPath>
</threatFeed>
<!-- Honeypot Server Configuration -->

6
go.mod
View File

@@ -3,8 +3,8 @@ module github.com/r-smith/deceptifeed
go 1.24
require (
golang.org/x/crypto v0.36.0
golang.org/x/net v0.38.0
golang.org/x/crypto v0.38.0
golang.org/x/net v0.40.0
)
require golang.org/x/sys v0.31.0 // indirect
require golang.org/x/sys v0.33.0 // indirect

16
go.sum
View File

@@ -1,8 +1,8 @@
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.30.0 h1:PQ39fJZ+mfadBm0y5WlL4vlM7Sx1Hgf13sMIY2+QS9Y=
golang.org/x/term v0.30.0/go.mod h1:NYYFdzHoI5wRh/h5tDMdMqCqPJZEuNqVR5xJLd/n67g=
golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=
golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=
golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=
golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.32.0 h1:DR4lr0TjUs3epypdhTOkMmuF5CDFJ/8pOnbzMZPQ7bg=
golang.org/x/term v0.32.0/go.mod h1:uZG1FhGx848Sqfsq4/DlJr3xGGsYMu/L5GW4abiaEPQ=

View File

@@ -0,0 +1,95 @@
package certutil
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"os"
"time"
)
// GenerateSelfSigned creates a self-signed certificate and returns it as a
// tls.Certificate. If certPath and keyPath are provided, the generated
// certificate and private key are saved to disk.
func GenerateSelfSigned(certPath string, keyPath string) (tls.Certificate, error) {
// Generate 2048-bit RSA private key.
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return tls.Certificate{}, fmt.Errorf("failed to generate private key: %w", err)
}
// Set the certificate validity period to 10 years.
notBefore := time.Now()
notAfter := notBefore.AddDate(10, 0, 0)
// Generate a random certificate serial number.
serialNumber := make([]byte, 16)
_, err = rand.Read(serialNumber)
if err != nil {
return tls.Certificate{}, fmt.Errorf("failed to generate certificate serial number: %w", err)
}
// Configure the certificate template.
template := x509.Certificate{
SerialNumber: new(big.Int).SetBytes(serialNumber),
Subject: pkix.Name{CommonName: "localhost"},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
// Create the certificate.
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
if err != nil {
return tls.Certificate{}, fmt.Errorf("failed to create certificate: %w", err)
}
certPEM := &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}
keyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
// Save the certificate and key to disk.
if len(certPath) > 0 && len(keyPath) > 0 {
// Silently ignore any potential errors and continue.
_ = writeCertAndKey(certPEM, keyPEM, certPath, keyPath)
}
return tls.X509KeyPair(pem.EncodeToMemory(certPEM), pem.EncodeToMemory(keyPEM))
}
// writeCertAndKey saves the public certificate and private key in PEM format
// to the specified paths.
func writeCertAndKey(cert *pem.Block, key *pem.Block, certPath string, keyPath string) error {
// Save the certificate file to disk.
certFile, err := os.Create(certPath)
if err != nil {
return err
}
defer certFile.Close()
if err := pem.Encode(certFile, cert); err != nil {
return err
}
// Save the private key file to disk.
keyFile, err := os.Create(keyPath)
if err != nil {
return err
}
defer keyFile.Close()
// Limit key access to the owner only.
_ = keyFile.Chmod(0600)
if err := pem.Encode(keyFile, key); err != nil {
return err
}
return nil
}

View File

@@ -145,6 +145,9 @@ type ThreatFeed struct {
ExpiryHours int `xml:"threatExpiryHours"`
IsPrivateIncluded bool `xml:"includePrivateIPs"`
ExcludeListPath string `xml:"excludeListPath"`
EnableTLS bool `xml:"enableTLS"`
CertPath string `xml:"certPath"`
KeyPath string `xml:"keyPath"`
}
// Load reads an optional XML configuration file and unmarshals its contents

29
internal/httpserver/fs.go Normal file
View File

@@ -0,0 +1,29 @@
package httpserver
import "io/fs"
// noDirectoryFS is a wrapper around fs.FS that disables directory listings.
type noDirectoryFS struct {
fs fs.FS
}
// Open opens the named file from the underlying fs.FS. The file is wrapped in
// a noReadDirFile to disable directory listings.
func (fs noDirectoryFS) Open(name string) (fs.File, error) {
f, err := fs.fs.Open(name)
if err != nil {
return nil, err
}
return noReadDirFile{f}, nil
}
// noReadDirFile wraps fs.File and overrides ReadDir to disable directory
// listings.
type noReadDirFile struct {
fs.File
}
// ReadDir always returns an error to disable directory listings.
func (noReadDirFile) ReadDir(int) ([]fs.DirEntry, error) {
return nil, fs.ErrInvalid
}

View File

@@ -2,46 +2,98 @@ package httpserver
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"io"
"io/fs"
"log"
"log/slog"
"math/big"
"net"
"net/http"
"net/netip"
"os"
"regexp"
"strings"
"time"
"github.com/r-smith/deceptifeed/internal/certutil"
"github.com/r-smith/deceptifeed/internal/config"
"github.com/r-smith/deceptifeed/internal/threatfeed"
)
// Start initializes and starts an HTTP or HTTPS honeypot server. The server
// is a simple HTTP server designed to log all details from incoming requests.
// Optionally, a single static HTML file can be served as the homepage,
// otherwise, the server will return only HTTP status codes to clients.
// Interactions with the HTTP server are sent to the threat feed.
// responseMode represents the HTTP response behavior for the honeypot.
// Depending on the configuration, the honeypot can serve a built-in default
// response, serve a specific file, or serve files from a specified directory.
type responseMode int
const (
modeDefault responseMode = iota // Serve the built-in default response.
modeFile // Serve a specific file.
modeDirectory // Serve files from a specified directory.
)
// responseConfig defines how the honeypot serves HTTP responses. It includes
// the response mode (default, file, or directory) and, for directory mode, an
// http.FileServer and file descriptor to the directory.
type responseConfig struct {
mode responseMode
fsRoot *os.Root
fsHandler http.Handler
}
// determineConfig reads the given configuration and returns a responseConfig,
// selecting the honeypot's response mode based on whether the HomePagePath
// setting is empty, a file, or a directory.
func determineConfig(cfg *config.Server) *responseConfig {
if len(cfg.HomePagePath) == 0 {
return &responseConfig{mode: modeDefault}
}
info, err := os.Stat(cfg.HomePagePath)
if err != nil {
return &responseConfig{mode: modeDefault}
}
if info.IsDir() {
root, err := os.OpenRoot(cfg.HomePagePath)
if err != nil {
return &responseConfig{mode: modeDefault}
}
return &responseConfig{
mode: modeDirectory,
fsRoot: root,
fsHandler: withCustomError(http.FileServerFS(noDirectoryFS{root.FS()}), cfg.ErrorPagePath),
}
}
return &responseConfig{
mode: modeFile,
}
}
// Start initializes and starts an HTTP or HTTPS honeypot server. It logs all
// request details and updates the threat feed as needed. If a filesystem path
// is specified in the configuration, the honeypot serves static content from
// the path.
func Start(cfg *config.Server) {
response := determineConfig(cfg)
if response.mode == modeDirectory {
defer response.fsRoot.Close()
}
switch cfg.Type {
case config.HTTP:
listenHTTP(cfg)
listenHTTP(cfg, response)
case config.HTTPS:
listenHTTPS(cfg)
listenHTTPS(cfg, response)
}
}
// listenHTTP initializes and starts an HTTP (plaintext) honeypot server.
func listenHTTP(cfg *config.Server) {
func listenHTTP(cfg *config.Server, response *responseConfig) {
mux := http.NewServeMux()
mux.HandleFunc("/", handleConnection(cfg, parseCustomHeaders(cfg.Headers)))
mux.HandleFunc("/", handleConnection(cfg, parseCustomHeaders(cfg.Headers), response))
srv := &http.Server{
Addr: ":" + cfg.Port,
Handler: mux,
@@ -58,10 +110,10 @@ func listenHTTP(cfg *config.Server) {
}
}
// listenHTTP initializes and starts an HTTPS (encrypted) honeypot server.
func listenHTTPS(cfg *config.Server) {
// listenHTTPS initializes and starts an HTTPS (encrypted) honeypot server.
func listenHTTPS(cfg *config.Server, response *responseConfig) {
mux := http.NewServeMux()
mux.HandleFunc("/", handleConnection(cfg, parseCustomHeaders(cfg.Headers)))
mux.HandleFunc("/", handleConnection(cfg, parseCustomHeaders(cfg.Headers), response))
srv := &http.Server{
Addr: ":" + cfg.Port,
Handler: mux,
@@ -72,10 +124,9 @@ func listenHTTPS(cfg *config.Server) {
}
// If the cert and key aren't found, generate a self-signed certificate.
if _, err := os.Stat(cfg.CertPath); os.IsNotExist(err) {
if _, err := os.Stat(cfg.KeyPath); os.IsNotExist(err) {
// Generate a self-signed certificate.
cert, err := generateSelfSignedCert(cfg.CertPath, cfg.KeyPath)
if _, err := os.Stat(cfg.CertPath); errors.Is(err, fs.ErrNotExist) {
if _, err := os.Stat(cfg.KeyPath); errors.Is(err, fs.ErrNotExist) {
cert, err := certutil.GenerateSelfSigned(cfg.CertPath, cfg.KeyPath)
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to generate HTTPS certificate:", err)
return
@@ -93,104 +144,150 @@ func listenHTTPS(cfg *config.Server) {
}
}
// handleConnection is the handler for incoming HTTP and HTTPS client requests.
// It logs the details of each request and generates responses based on the
// requested URL. When the root or index.html is requested, it serves either an
// HTML file specified in the configuration or a default page prompting for
// basic HTTP authentication. Requests for any other URLs will return a 404
// error to the client.
func handleConnection(cfg *config.Server, customHeaders map[string]string) http.HandlerFunc {
// handleConnection processes incoming HTTP and HTTPS client requests. It logs
// the details of each request, updates the threat feed, and serves responses
// based on the honeypot configuration.
func handleConnection(cfg *config.Server, customHeaders map[string]string, response *responseConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Log details of the incoming HTTP request.
// Log connection details. The log fields and format differ based on
// whether a custom source IP header is configured.
dst_ip, dst_port := getLocalAddr(r)
src_ip, _, _ := net.SplitHostPort(r.RemoteAddr)
username, password, isAuth := r.BasicAuth()
if isAuth {
cfg.Logger.LogAttrs(context.Background(), slog.LevelInfo, "",
logData := []slog.Attr{}
if len(cfg.SourceIPHeader) > 0 {
// A custom source IP header is configured. Set rem_ip to the
// original connecting IP and src_ip to the IP from the header. If
// the header is missing, invalid, contains multiple IPs, or if
// there a multiple headers with the same name, parsing will fail,
// and src_ip will fallback to the original connecting IP.
rem_ip := src_ip
header := r.Header[cfg.SourceIPHeader]
parsed := false
errMsg := ""
switch len(header) {
case 0:
errMsg = "Missing header " + cfg.SourceIPHeader
case 1:
v := header[0]
if _, err := netip.ParseAddr(v); err != nil {
if strings.Contains(v, ",") {
errMsg = "Multiple values in header " + cfg.SourceIPHeader
} else {
errMsg = "Invalid IP in header " + cfg.SourceIPHeader
}
} else {
parsed = true
src_ip = v
}
default:
errMsg = "Multiple instances of header " + cfg.SourceIPHeader
}
logData = append(logData,
slog.String("event_type", "http"),
slog.String("remote_ip", rem_ip),
slog.String("source_ip", src_ip),
slog.Bool("source_ip_parsed", parsed),
)
if !parsed {
logData = append(logData, slog.String("source_ip_error", errMsg))
}
logData = append(logData,
slog.String("server_ip", dst_ip),
slog.String("server_port", dst_port),
slog.String("server_name", config.GetHostname()),
slog.Group("event_details",
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.String("query", r.URL.RawQuery),
slog.String("user_agent", r.UserAgent()),
slog.String("protocol", r.Proto),
slog.String("host", r.Host),
slog.Group("basic_auth",
slog.String("username", username),
slog.String("password", password),
),
slog.Any("headers", flattenHeaders(r.Header)),
),
)
} else {
cfg.Logger.LogAttrs(context.Background(), slog.LevelInfo, "",
// No custom source IP header is configured. Log the standard
// connection details, keeping src_ip as the remote connecting IP.
logData = append(logData,
slog.String("event_type", "http"),
slog.String("source_ip", src_ip),
slog.String("server_ip", dst_ip),
slog.String("server_port", dst_port),
slog.String("server_name", config.GetHostname()),
slog.Group("event_details",
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.String("query", r.URL.RawQuery),
slog.String("user_agent", r.UserAgent()),
slog.String("protocol", r.Proto),
slog.String("host", r.Host),
slog.Any("headers", flattenHeaders(r.Header)),
)
}
// Log standard HTTP request information.
eventDetails := []any{
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.String("query", r.URL.RawQuery),
slog.String("user_agent", r.UserAgent()),
slog.String("protocol", r.Proto),
slog.String("host", r.Host),
slog.Any("headers", flattenHeaders(r.Header)),
}
// If the request includes a "basic" Authorization header, decode and
// log the credentials.
if username, password, ok := r.BasicAuth(); ok {
eventDetails = append(eventDetails,
slog.Group("basic_auth",
slog.String("username", username),
slog.String("password", password),
),
)
}
// Combine log data and write the final log entry.
logData = append(logData, slog.Group("event_details", eventDetails...))
cfg.Logger.LogAttrs(context.Background(), slog.LevelInfo, "", logData...)
// Print a simplified version of the request to the console.
fmt.Printf("[HTTP] %s %s %s %s\n", src_ip, r.Method, r.URL.Path, r.URL.RawQuery)
// Update the threat feed with the source IP address from the request.
// If the configuration specifies an HTTP header to be used for the
// source IP, retrieve the header value and use it instead of the
// connecting IP.
// Update the threat feed using the source IP address (src_ip). If a
// custom header is configured, src_ip contains the IP extracted from
// the header. Otherwise, it contains the remote connecting IP.
if shouldUpdateThreatFeed(cfg, r) {
src := src_ip
if len(cfg.SourceIPHeader) > 0 {
if header := r.Header.Get(cfg.SourceIPHeader); len(header) > 0 {
src = header
}
}
threatfeed.Update(src)
threatfeed.Update(src_ip)
}
// Apply any custom HTTP response headers.
// Apply optional custom HTTP response headers.
for header, value := range customHeaders {
w.Header().Set(header, value)
}
// Serve a response based on the requested URL. If the root URL or
// /index.html is requested, serve the homepage. For all other
// requests, serve the error page with a 404 Not Found response.
// Optionally, a single static HTML file may be specified for both the
// homepage and the error page. If no custom files are provided,
// default minimal responses will be served.
if r.URL.Path == "/" || r.URL.Path == "/index.html" {
// Serve the homepage response.
if len(cfg.HomePagePath) > 0 {
http.ServeFile(w, r, cfg.HomePagePath)
} else {
// Serve a response based on the honeypot configuration.
switch response.mode {
case modeDefault:
// Built-in default response.
if r.URL.Path == "/" || r.URL.Path == "/index.html" {
if _, _, ok := r.BasicAuth(); ok {
time.Sleep(2 * time.Second)
}
w.Header()["WWW-Authenticate"] = []string{"Basic"}
w.WriteHeader(http.StatusUnauthorized)
} else {
serveErrorPage(w, r, cfg.ErrorPagePath)
}
} else {
// Serve the error page response.
w.WriteHeader(http.StatusNotFound)
if len(cfg.ErrorPagePath) > 0 {
http.ServeFile(w, r, cfg.ErrorPagePath)
case modeFile:
// Serve a single file.
if r.URL.Path == "/" || r.URL.Path == "/index.html" {
http.ServeFile(w, r, cfg.HomePagePath)
} else {
serveErrorPage(w, r, cfg.ErrorPagePath)
}
case modeDirectory:
// Serve files from a directory.
response.fsHandler.ServeHTTP(w, r)
}
}
}
// serveErrorPage serves an error HTTP response code and optional html page.
func serveErrorPage(w http.ResponseWriter, r *http.Request, path string) {
if len(path) == 0 {
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
http.ServeFile(w, r, path)
}
// shouldUpdateThreatFeed determines if the threat feed should be updated based
// on the server's configured rules.
func shouldUpdateThreatFeed(cfg *config.Server, r *http.Request) bool {
@@ -295,91 +392,3 @@ func getLocalAddr(r *http.Request) (ip string, port string) {
}
return ip, port
}
// generateSelfSignedCert creates a self-signed TLS certificate and private key
// and returns the resulting tls.Certificate. If file paths are provided, the
// certificate and key are also saved to disk.
func generateSelfSignedCert(certPath string, keyPath string) (tls.Certificate, error) {
// Generate 2048-bit RSA private key.
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return tls.Certificate{}, fmt.Errorf("failed to generate private key: %w", err)
}
// Set the certificate validity period to 10 years.
notBefore := time.Now()
notAfter := notBefore.AddDate(10, 0, 0)
// Generate a random serial number for the certificate.
serialNumber := make([]byte, 16)
_, err = rand.Read(serialNumber)
if err != nil {
return tls.Certificate{}, fmt.Errorf("failed to generate certificate serial number: %w", err)
}
// Set up the template for creating the certificate.
template := x509.Certificate{
SerialNumber: new(big.Int).SetBytes(serialNumber),
Subject: pkix.Name{CommonName: "localhost"},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
BasicConstraintsValid: true,
}
// Use the template to create a self-signed X.509 certificate.
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
if err != nil {
return tls.Certificate{}, fmt.Errorf("failed to create certificate: %w", err)
}
certPEM := &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}
keyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
// Save the certificate and key to disk.
if len(certPath) > 0 && len(keyPath) > 0 {
_ = writeCertAndKey(certPEM, keyPEM, certPath, keyPath)
// If saving fails, ignore the errors and use the in-memory
// certificate.
}
// Parse the public certificate and private key bytes into a tls.Certificate.
cert, err := tls.X509KeyPair(pem.EncodeToMemory(certPEM), pem.EncodeToMemory(keyPEM))
if err != nil {
return tls.Certificate{}, fmt.Errorf("failed to load certificate and private key: %w", err)
}
// Return the tls.Certificate.
return cert, nil
}
// writeCertAndKey saves the public certificate and private key in PEM format
// to the specified file paths.
func writeCertAndKey(cert *pem.Block, key *pem.Block, certPath string, keyPath string) error {
// Save the certificate file to disk.
certFile, err := os.Create(certPath)
if err != nil {
return err
}
defer certFile.Close()
if err := pem.Encode(certFile, cert); err != nil {
return err
}
// Save the private key file to disk.
keyFile, err := os.Create(keyPath)
if err != nil {
return err
}
defer keyFile.Close()
// Limit key access to the owner only.
_ = keyFile.Chmod(0600)
if err := pem.Encode(keyFile, key); err != nil {
return err
}
return nil
}

View File

@@ -0,0 +1,48 @@
package httpserver
import (
"net/http"
)
// withCustomError is a middleware that intercepts 4xx/5xx HTTP error responses
// and replaces them with a custom error response.
func withCustomError(next http.Handler, errorPath string) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
e := &errorInterceptor{origWriter: w, origRequest: r, errorPath: errorPath}
next.ServeHTTP(e, r)
})
}
// errorInterceptor intercepts HTTP responses to override error status codes
// and to serve a custom error response.
type errorInterceptor struct {
origWriter http.ResponseWriter
origRequest *http.Request
overridden bool
errorPath string
}
// WriteHeader intercepts error response codes (4xx or 5xx) to serve a custom
// error response.
func (e *errorInterceptor) WriteHeader(statusCode int) {
if statusCode >= 400 && statusCode <= 599 {
e.overridden = true
serveErrorPage(e.origWriter, e.origRequest, e.errorPath)
return
}
e.origWriter.WriteHeader(statusCode)
}
// Write writes the response body only if the response code was not overridden.
// Otherwise, the body is discarded.
func (e *errorInterceptor) Write(b []byte) (int, error) {
if !e.overridden {
return e.origWriter.Write(b)
}
return 0, nil
}
// Header returns the response headers from the original ResponseWriter.
func (e *errorInterceptor) Header() http.Header {
return e.origWriter.Header()
}

View File

@@ -139,7 +139,7 @@ func loadOrGeneratePrivateKey(path string) (ssh.Signer, error) {
// Load the specified file and return the parsed private key.
privateKey, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read private key from '%s': %w", path, err)
return nil, fmt.Errorf("failed to read private key '%s': %w", path, err)
}
signer, err := ssh.ParsePrivateKey(privateKey)
if err != nil {
@@ -150,20 +150,19 @@ func loadOrGeneratePrivateKey(path string) (ssh.Signer, error) {
// Generate and return a new private key.
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, fmt.Errorf("failed to generate RSA private key: %w", err)
return nil, fmt.Errorf("failed to generate private key: %w", err)
}
// Save the private key to disk.
if len(path) > 0 {
// Silently ignore any potential errors and continue.
_ = writePrivateKey(path, privateKey)
// If saving fails, ignore the errors and use the in-memory private
// key.
}
// Convert the key to ssh.Signer.
signer, err := ssh.NewSignerFromKey(privateKey)
if err != nil {
return nil, fmt.Errorf("failed to convert RSA key to SSH signer: %w", err)
return nil, fmt.Errorf("failed to convert key to SSH signer: %w", err)
}
return signer, nil
} else {
@@ -171,8 +170,7 @@ func loadOrGeneratePrivateKey(path string) (ssh.Signer, error) {
}
}
// writePrivateKey saves a private key in PEM format to the specified file
// path.
// writePrivateKey saves a private key in PEM format to the specified path.
func writePrivateKey(path string, privateKey *rsa.PrivateKey) error {
privBytes := x509.MarshalPKCS1PrivateKey(privateKey)
privPem := &pem.Block{

View File

@@ -5,7 +5,7 @@ import (
"encoding/csv"
"errors"
"fmt"
"net"
"net/netip"
"os"
"strconv"
"strings"
@@ -65,11 +65,8 @@ var (
func Update(ip string) {
// Check if the given IP string is a private address. The threat feed may
// be configured to include or exclude private IPs.
netIP := net.ParseIP(ip)
if netIP == nil || netIP.IsLoopback() {
return
}
if !cfg.ThreatFeed.IsPrivateIncluded && netIP.IsPrivate() {
parsedIP, err := netip.ParseAddr(ip)
if err != nil || parsedIP.IsLoopback() || (!cfg.ThreatFeed.IsPrivateIncluded && parsedIP.IsPrivate()) {
return
}

View File

@@ -2,10 +2,9 @@ package threatfeed
import (
"bufio"
"bytes"
"cmp"
"fmt"
"net"
"net/netip"
"os"
"slices"
"strings"
@@ -16,11 +15,11 @@ import (
// feedEntry represents an individual entry in the threat feed.
type feedEntry struct {
IP string `json:"ip"`
IPBytes net.IP `json:"-"`
Added time.Time `json:"added"`
LastSeen time.Time `json:"last_seen"`
Observations int `json:"observations"`
IP string `json:"ip"`
IPBytes netip.Addr `json:"-"`
Added time.Time `json:"added"`
LastSeen time.Time `json:"last_seen"`
Observations int `json:"observations"`
}
// feedEntries is a slice of feedEntry structs. It represents the threat feed
@@ -86,13 +85,13 @@ loop:
continue
}
parsedIP := net.ParseIP(ip)
if parsedIP == nil || (parsedIP.IsPrivate() && !cfg.ThreatFeed.IsPrivateIncluded) {
parsedIP, err := netip.ParseAddr(ip)
if err != nil || (parsedIP.IsPrivate() && !cfg.ThreatFeed.IsPrivateIncluded) {
continue
}
for _, ipnet := range excludedCIDR {
if ipnet.Contains(parsedIP) {
for _, prefix := range excludedCIDR {
if prefix.Contains(parsedIP) {
continue loop
}
}
@@ -120,9 +119,9 @@ loop:
// should contain an IP address or CIDR. It returns a map of the unique IPs and
// a slice of the CIDR ranges found in the file. The file may include comments
// using "#". The "#" symbol on a line and everything after is ignored.
func parseExcludeList(filepath string) (map[string]struct{}, []*net.IPNet, error) {
func parseExcludeList(filepath string) (map[string]struct{}, []netip.Prefix, error) {
if len(filepath) == 0 {
return map[string]struct{}{}, []*net.IPNet{}, nil
return nil, nil, nil
}
f, err := os.Open(filepath)
@@ -134,22 +133,24 @@ func parseExcludeList(filepath string) (map[string]struct{}, []*net.IPNet, error
// `ips` stores individual IPs to exclude, and `cidr` stores CIDR networks
// to exclude.
ips := make(map[string]struct{})
cidr := []*net.IPNet{}
cidr := []netip.Prefix{}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
line := scanner.Text()
// Remove comments from text.
if i := strings.Index(line, "#"); i != -1 {
line = strings.TrimSpace(line[:i])
// Remove comments and trim.
if i := strings.IndexByte(line, '#'); i != -1 {
line = line[:i]
}
line = strings.TrimSpace(line)
if len(line) == 0 {
continue
}
if len(line) > 0 {
if _, ipnet, err := net.ParseCIDR(line); err == nil {
cidr = append(cidr, ipnet)
} else {
ips[line] = struct{}{}
}
if prefix, err := netip.ParsePrefix(line); err == nil {
cidr = append(cidr, prefix)
} else {
ips[line] = struct{}{}
}
}
if err := scanner.Err(); err != nil {
@@ -164,13 +165,13 @@ func (f feedEntries) applySort(method sortMethod, direction sortDirection) {
switch method {
case byIP:
slices.SortFunc(f, func(a, b feedEntry) int {
return bytes.Compare(a.IPBytes, b.IPBytes)
return a.IPBytes.Compare(b.IPBytes)
})
case byLastSeen:
slices.SortFunc(f, func(a, b feedEntry) int {
t := a.LastSeen.Compare(b.LastSeen)
if t == 0 {
return bytes.Compare(a.IPBytes, b.IPBytes)
return a.IPBytes.Compare(b.IPBytes)
}
return t
})
@@ -178,7 +179,7 @@ func (f feedEntries) applySort(method sortMethod, direction sortDirection) {
slices.SortFunc(f, func(a, b feedEntry) int {
t := a.Added.Compare(b.Added)
if t == 0 {
return bytes.Compare(a.IPBytes, b.IPBytes)
return a.IPBytes.Compare(b.IPBytes)
}
return t
})
@@ -186,7 +187,7 @@ func (f feedEntries) applySort(method sortMethod, direction sortDirection) {
slices.SortFunc(f, func(a, b feedEntry) int {
t := cmp.Compare(a.Observations, b.Observations)
if t == 0 {
return bytes.Compare(a.IPBytes, b.IPBytes)
return a.IPBytes.Compare(b.IPBytes)
}
return t
})

View File

@@ -1,8 +1,8 @@
package threatfeed
import (
"cmp"
"encoding/json"
"html/template"
"io"
"net/http"
"os"
@@ -13,8 +13,7 @@ import (
// handleLogsMain serves a static page listing honeypot logs available for
// viewing.
func handleLogsMain(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFS(templates, "templates/logs.html"))
_ = tmpl.Execute(w, nil)
_ = parsedTemplates.ExecuteTemplate(w, "logs.html", "logs")
}
// handleLogs directs the request to the appropriate log parser based on the
@@ -22,14 +21,51 @@ func handleLogsMain(w http.ResponseWriter, r *http.Request) {
func handleLogs(w http.ResponseWriter, r *http.Request) {
switch r.PathValue("logtype") {
case "http":
handleLogHTTP(w)
switch r.PathValue("subtype") {
case "":
handleLogHTTP(w)
case "ip":
displayStats(w, httpIPStats{})
case "useragent":
displayStats(w, httpUserAgentStats{})
case "path":
displayStats(w, httpPathStats{})
case "query":
displayStats(w, httpQueryStats{})
case "method":
displayStats(w, httpMethodStats{})
case "host":
displayStats(w, httpHostStats{})
default:
handleNotFound(w, r)
}
case "ssh":
handleLogSSH(w)
switch r.PathValue("subtype") {
case "":
handleLogSSH(w)
case "ip":
displayStats(w, sshIPStats{})
case "client":
displayStats(w, sshClientStats{})
case "username":
displayStats(w, sshUsernameStats{})
case "password":
displayStats(w, sshPasswordStats{})
default:
handleNotFound(w, r)
}
default:
handleNotFound(w, r)
}
}
// displayLogErrorPage servers an error page when there is a problem parsing
// log files.
func displayLogErrorPage(w http.ResponseWriter, err error) {
w.WriteHeader(http.StatusInternalServerError)
_ = parsedTemplates.ExecuteTemplate(w, "logs-error.html", map[string]any{"Error": err, "NavData": "logs"})
}
// handleLogSSH serves the SSH honeypot logs as a web page. It opens the
// honeypot log files, parses the data to JSON, and passes the result to an
// HTML template for rendering.
@@ -37,9 +73,7 @@ func handleLogSSH(w http.ResponseWriter) {
l := logFiles{}
reader, err := l.open()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
tmpl := template.Must(template.ParseFS(templates, "templates/logs-error.html"))
_ = tmpl.Execute(w, err)
displayLogErrorPage(w, err)
return
}
defer l.close()
@@ -59,20 +93,18 @@ func handleLogSSH(w http.ResponseWriter) {
data := make([]Log, 0, maxResults+1)
for d.More() {
var entry Log
if err := d.Decode(&entry); err != nil {
err := d.Decode(&entry)
if err != nil || entry.EventType != "ssh" {
continue
}
if entry.EventType == "ssh" {
data = append(data, entry)
if len(data) > maxResults {
data = data[1:]
}
data = append(data, entry)
if len(data) > maxResults {
data = data[1:]
}
}
slices.Reverse(data)
tmpl := template.Must(template.ParseFS(templates, "templates/logs-ssh.html"))
_ = tmpl.Execute(w, data)
_ = parsedTemplates.ExecuteTemplate(w, "logs-ssh.html", map[string]any{"Data": data, "NavData": "logs"})
}
// handleLogHTTP serves the HTTP honeypot logs as a web page. It opens the
@@ -82,9 +114,7 @@ func handleLogHTTP(w http.ResponseWriter) {
l := logFiles{}
reader, err := l.open()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
tmpl := template.Must(template.ParseFS(templates, "templates/logs-error.html"))
_ = tmpl.Execute(w, err)
displayLogErrorPage(w, err)
return
}
defer l.close()
@@ -104,20 +134,303 @@ func handleLogHTTP(w http.ResponseWriter) {
data := make([]Log, 0, maxResults+1)
for d.More() {
var entry Log
if err := d.Decode(&entry); err != nil {
err := d.Decode(&entry)
if err != nil || entry.EventType != "http" {
continue
}
if entry.EventType == "http" {
data = append(data, entry)
if len(data) > maxResults {
data = data[1:]
}
data = append(data, entry)
if len(data) > maxResults {
data = data[1:]
}
}
slices.Reverse(data)
tmpl := template.Must(template.ParseFS(templates, "templates/logs-http.html"))
_ = tmpl.Execute(w, data)
_ = parsedTemplates.ExecuteTemplate(w, "logs-http.html", map[string]any{"Data": data, "NavData": "logs"})
}
// displayStats handles the processing and rendering of statistics for a given
// field. It reads honeypot log data, counts the occurrences of `field` and
// displays the results.
func displayStats(w http.ResponseWriter, field fieldCounter) {
l := logFiles{}
reader, err := l.open()
if err != nil {
displayLogErrorPage(w, err)
return
}
defer l.close()
fieldCounts := field.count(reader)
results := []statsResult{}
for k, v := range fieldCounts {
results = append(results, statsResult{Field: k, Count: v})
}
slices.SortFunc(results, func(a, b statsResult) int {
return cmp.Or(
-cmp.Compare(a.Count, b.Count),
cmp.Compare(a.Field, b.Field),
)
})
_ = parsedTemplates.ExecuteTemplate(
w,
"logs-stats.html",
map[string]any{
"Data": results,
"Header": field.fieldName(),
"NavData": "logs",
},
)
}
// statsResult holds a specific value for field and its associated count.
type statsResult struct {
Field string
Count int
}
// fieldCounter is an interface that defines methods for counting occurrences
// of specific fields.
type fieldCounter interface {
count(io.Reader) map[string]int
fieldName() string
}
// sshIPStats is the log structure for extracting SSH IP data.
type sshIPStats struct {
EventType string `json:"event_type"`
SourceIP string `json:"source_ip"`
}
func (sshIPStats) fieldName() string { return "Source IP" }
func (sshIPStats) count(r io.Reader) map[string]int {
fieldCounts := map[string]int{}
d := json.NewDecoder(r)
for d.More() {
var entry sshIPStats
err := d.Decode(&entry)
if err != nil || entry.EventType != "ssh" {
continue
}
fieldCounts[entry.SourceIP]++
}
return fieldCounts
}
// sshClientStats is the log structure for extracting SSH client data.
type sshClientStats struct {
EventType string `json:"event_type"`
Details struct {
Client string `json:"ssh_client"`
} `json:"event_details"`
}
func (sshClientStats) fieldName() string { return "SSH Client" }
func (sshClientStats) count(r io.Reader) map[string]int {
fieldCounts := map[string]int{}
d := json.NewDecoder(r)
for d.More() {
var entry sshClientStats
err := d.Decode(&entry)
if err != nil || entry.EventType != "ssh" {
continue
}
fieldCounts[entry.Details.Client]++
}
return fieldCounts
}
// sshUsernameStats is the log structure for extracting SSH username data.
type sshUsernameStats struct {
EventType string `json:"event_type"`
Details struct {
Username string `json:"username"`
} `json:"event_details"`
}
func (sshUsernameStats) fieldName() string { return "Username" }
func (sshUsernameStats) count(r io.Reader) map[string]int {
fieldCounts := map[string]int{}
d := json.NewDecoder(r)
for d.More() {
var entry sshUsernameStats
err := d.Decode(&entry)
if err != nil || entry.EventType != "ssh" {
continue
}
fieldCounts[entry.Details.Username]++
}
return fieldCounts
}
// sshPasswordStats is the log structure for extracting SSH password data.
type sshPasswordStats struct {
EventType string `json:"event_type"`
Details struct {
Password string `json:"password"`
} `json:"event_details"`
}
func (sshPasswordStats) fieldName() string { return "Password" }
func (sshPasswordStats) count(r io.Reader) map[string]int {
fieldCounts := map[string]int{}
d := json.NewDecoder(r)
for d.More() {
var entry sshPasswordStats
err := d.Decode(&entry)
if err != nil || entry.EventType != "ssh" {
continue
}
fieldCounts[entry.Details.Password]++
}
return fieldCounts
}
// httpIPStats is the log structure for extracting HTTP IP data.
type httpIPStats struct {
EventType string `json:"event_type"`
SourceIP string `json:"source_ip"`
}
func (httpIPStats) fieldName() string { return "Source IP" }
func (httpIPStats) count(r io.Reader) map[string]int {
fieldCounts := map[string]int{}
d := json.NewDecoder(r)
for d.More() {
var entry httpIPStats
err := d.Decode(&entry)
if err != nil || entry.EventType != "http" {
continue
}
fieldCounts[entry.SourceIP]++
}
return fieldCounts
}
// httpUserAgentStats is the log structure for extracting HTTP user-agent data.
type httpUserAgentStats struct {
EventType string `json:"event_type"`
Details struct {
UserAgent string `json:"user_agent"`
} `json:"event_details"`
}
func (httpUserAgentStats) fieldName() string { return "User-Agent" }
func (httpUserAgentStats) count(r io.Reader) map[string]int {
fieldCounts := map[string]int{}
d := json.NewDecoder(r)
for d.More() {
var entry httpUserAgentStats
err := d.Decode(&entry)
if err != nil || entry.EventType != "http" {
continue
}
fieldCounts[entry.Details.UserAgent]++
}
return fieldCounts
}
// httpPathStats is the log structure for extracting HTTP path data.
type httpPathStats struct {
EventType string `json:"event_type"`
Details struct {
Path string `json:"path"`
} `json:"event_details"`
}
func (httpPathStats) fieldName() string { return "Path" }
func (httpPathStats) count(r io.Reader) map[string]int {
fieldCounts := map[string]int{}
d := json.NewDecoder(r)
for d.More() {
var entry httpPathStats
err := d.Decode(&entry)
if err != nil || entry.EventType != "http" {
continue
}
fieldCounts[entry.Details.Path]++
}
return fieldCounts
}
// httpQueryStats is the log structure for extracting HTTP query string data.
type httpQueryStats struct {
EventType string `json:"event_type"`
Details struct {
Query string `json:"query"`
} `json:"event_details"`
}
func (httpQueryStats) fieldName() string { return "Query String" }
func (httpQueryStats) count(r io.Reader) map[string]int {
fieldCounts := map[string]int{}
d := json.NewDecoder(r)
for d.More() {
var entry httpQueryStats
err := d.Decode(&entry)
if err != nil || entry.EventType != "http" {
continue
}
fieldCounts[entry.Details.Query]++
}
return fieldCounts
}
// httpMethodStats is the log structure for extracting HTTP method data.
type httpMethodStats struct {
EventType string `json:"event_type"`
Details struct {
Method string `json:"method"`
} `json:"event_details"`
}
func (httpMethodStats) fieldName() string { return "HTTP Method" }
func (httpMethodStats) count(r io.Reader) map[string]int {
fieldCounts := map[string]int{}
d := json.NewDecoder(r)
for d.More() {
var entry httpMethodStats
err := d.Decode(&entry)
if err != nil || entry.EventType != "http" {
continue
}
fieldCounts[entry.Details.Method]++
}
return fieldCounts
}
// httpHostStats is the log structure for extracting HTTP host header data.
type httpHostStats struct {
EventType string `json:"event_type"`
Details struct {
Host string `json:"host"`
} `json:"event_details"`
}
func (httpHostStats) fieldName() string { return "Host Header" }
func (httpHostStats) count(r io.Reader) map[string]int {
fieldCounts := map[string]int{}
d := json.NewDecoder(r)
for d.More() {
var entry httpHostStats
err := d.Decode(&entry)
if err != nil || entry.EventType != "http" {
continue
}
fieldCounts[entry.Details.Host]++
}
return fieldCounts
}
// logFiles represents open honeypot log files and their associate io.Reader.

View File

@@ -2,9 +2,9 @@ package threatfeed
import (
"fmt"
"html/template"
"net"
"net/http"
"net/netip"
"sync"
"golang.org/x/net/websocket"
@@ -29,8 +29,7 @@ var (
// handleLiveIndex serves a web page that displays honeypot log data in
// real-time through a WebSocket connection.
func handleLiveIndex(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFS(templates, "templates/live.html"))
_ = tmpl.Execute(w, nil)
_ = parsedTemplates.ExecuteTemplate(w, "live.html", "live")
}
// broadcastLogsToClients receives honeypot log data through a byte channel
@@ -59,7 +58,7 @@ func handleWebSocket(ws *websocket.Conn) {
muWSClients.Lock()
delete(wsClients, ws)
muWSClients.Unlock()
ws.Close()
_ = ws.Close()
}()
// Enforce private IPs.
@@ -67,7 +66,7 @@ func handleWebSocket(ws *websocket.Conn) {
if err != nil {
return
}
if netIP := net.ParseIP(ip); !netIP.IsPrivate() && !netIP.IsLoopback() {
if parsedIP, err := netip.ParseAddr(ip); err != nil || (!parsedIP.IsPrivate() && !parsedIP.IsLoopback()) {
return
}
fmt.Println("[Threat Feed]", ip, "established WebSocket connection")
@@ -79,11 +78,11 @@ func handleWebSocket(ws *websocket.Conn) {
// Send the cache of recent log messages to the new client.
for _, msg := range wsRecentMessages {
websocket.Message.Send(ws, msg)
_ = websocket.Message.Send(ws, msg)
}
// Send a message informing the client that we're done sending the initial
// cache of log messages.
websocket.Message.Send(ws, "---end---")
_ = websocket.Message.Send(ws, "---end---")
// Keep WebSocket open.
var message string

View File

@@ -22,6 +22,11 @@ import (
//go:embed templates
var templates embed.FS
// parsedTemplates pre-parses and caches all HTML templates when the threat
// feed server starts. This eliminates the need for HTTP handlers to re-parse
// templates on each request.
var parsedTemplates = template.Must(template.ParseFS(templates, "templates/*.html"))
// handlePlain handles HTTP requests to serve the threat feed in plain text. It
// returns a list of IP addresses that interacted with the honeypot servers.
func handlePlain(w http.ResponseWriter, r *http.Request) {
@@ -281,19 +286,13 @@ func handleTAXIIObjects(w http.ResponseWriter, r *http.Request) {
// delivers a static HTML document with information on accessing the threat
// feed.
func handleHome(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFS(templates, "templates/home.html"))
err := tmpl.Execute(w, nil)
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to parse template 'home.html':", err)
return
}
_ = parsedTemplates.ExecuteTemplate(w, "home.html", "home")
}
// handleDocs serves a static page with documentation for accessing the threat
// feed.
func handleDocs(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFS(templates, "templates/docs.html"))
_ = tmpl.Execute(w, nil)
_ = parsedTemplates.ExecuteTemplate(w, "docs.html", "docs")
}
// handleCSS serves a CSS stylesheet for styling HTML templates.
@@ -304,7 +303,7 @@ func handleCSS(w http.ResponseWriter, r *http.Request) {
fmt.Println(err)
return
}
w.Write(data)
_, _ = w.Write(data)
}
// handleConfig serves a page that displays the Deceptifeed configuration.
@@ -312,10 +311,10 @@ func handleConfig(w http.ResponseWriter, r *http.Request) {
type templateData struct {
C config.Config
Version string
NavData string
}
d := templateData{C: cfg, Version: config.Version}
tmpl := template.Must(template.ParseFS(templates, "templates/config.html"))
_ = tmpl.Execute(w, d)
d := templateData{C: cfg, Version: config.Version, NavData: "config"}
_ = parsedTemplates.ExecuteTemplate(w, "config.html", d)
}
// handleHTML returns the threat feed as a web page for viewing in a browser.
@@ -350,12 +349,11 @@ func handleHTML(w http.ResponseWriter, r *http.Request) {
m = "observations"
}
tmpl := template.Must(template.ParseFS(templates, "templates/webfeed.html"))
err = tmpl.Execute(w, map[string]any{"Data": prepareFeed(opt), "SortDirection": d, "SortMethod": m})
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to encode threat feed to HTML:", err)
return
}
_ = parsedTemplates.ExecuteTemplate(
w,
"webfeed.html",
map[string]any{"Data": prepareFeed(opt), "SortDirection": d, "SortMethod": m, "NavData": "webfeed"},
)
}
// paginate returns a slice of stix.Objects for the requested page, based on
@@ -462,6 +460,5 @@ func parseParams(r *http.Request) (feedOptions, error) {
// response when a request is made to an undefined path.
func handleNotFound(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
tmpl := template.Must(template.ParseFS(templates, "templates/404.html"))
_ = tmpl.Execute(w, nil)
_ = parsedTemplates.ExecuteTemplate(w, "404.html", nil)
}

View File

@@ -3,6 +3,7 @@ package threatfeed
import (
"net"
"net/http"
"net/netip"
)
// enforcePrivateIP is a middleware that restricts access to the HTTP server
@@ -12,11 +13,11 @@ func enforcePrivateIP(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
http.Error(w, "Could not get IP", http.StatusInternalServerError)
http.Error(w, "", http.StatusForbidden)
return
}
if netIP := net.ParseIP(ip); !netIP.IsPrivate() && !netIP.IsLoopback() {
if parsedIP, err := netip.ParseAddr(ip); err != nil || (!parsedIP.IsPrivate() && !parsedIP.IsLoopback()) {
http.Error(w, "", http.StatusForbidden)
return
}

View File

@@ -1,11 +1,15 @@
package threatfeed
import (
"crypto/tls"
"errors"
"fmt"
"io/fs"
"net/http"
"os"
"time"
"github.com/r-smith/deceptifeed/internal/certutil"
"github.com/r-smith/deceptifeed/internal/config"
"golang.org/x/net/websocket"
)
@@ -81,6 +85,7 @@ func Start(c *config.Config) {
// Honeypot log handlers.
mux.HandleFunc("GET /logs", enforcePrivateIP(handleLogsMain))
mux.HandleFunc("GET /logs/{logtype}", enforcePrivateIP(handleLogs))
mux.HandleFunc("GET /logs/{logtype}/{subtype}", enforcePrivateIP(handleLogs))
srv := &http.Server{
Addr: ":" + c.ThreatFeed.Port,
@@ -90,9 +95,32 @@ func Start(c *config.Config) {
IdleTimeout: 0,
}
// Start the threat feed HTTP server.
fmt.Printf("Starting Threat Feed server on port: %s\n", c.ThreatFeed.Port)
if err := srv.ListenAndServe(); err != nil {
fmt.Fprintln(os.Stderr, "The Threat Feed server has stopped:", err)
// Start the threat feed (HTTP) server if TLS is not enabled.
if !c.ThreatFeed.EnableTLS {
fmt.Printf("Starting threat feed (HTTP) on port: %s\n", c.ThreatFeed.Port)
if err := srv.ListenAndServe(); err != nil {
fmt.Fprintln(os.Stderr, "The threat feed server has stopped:", err)
}
return
}
// Generate a self-signed cert if the provided key and cert aren't found.
if _, err := os.Stat(c.ThreatFeed.CertPath); errors.Is(err, fs.ErrNotExist) {
if _, err := os.Stat(c.ThreatFeed.KeyPath); errors.Is(err, fs.ErrNotExist) {
cert, err := certutil.GenerateSelfSigned(c.ThreatFeed.CertPath, c.ThreatFeed.KeyPath)
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to generate threat feed TLS certificate:", err)
return
}
// Add cert to server config.
srv.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cert}}
}
}
// Start the threat feed (HTTPS) server.
fmt.Printf("Starting threat feed (HTTPS) on port: %s\n", c.ThreatFeed.Port)
if err := srv.ListenAndServeTLS(c.ThreatFeed.CertPath, c.ThreatFeed.KeyPath); err != nil {
fmt.Fprintln(os.Stderr, "The threat feed server has stopped:", err)
}
}

File diff suppressed because one or more lines are too long

View File

@@ -239,11 +239,11 @@ ul.no-bullets {
}
ul.log-list {
font-family: 'Menlo', 'Consolas', 'Monaco', 'Liberation Mono', 'Lucida Console', monospace;
font-size: 1.1rem;
line-height: 2.5rem;
line-height: 1.75rem;
list-style-type: none;
margin-bottom: 0.3rem;
padding-left: 0;
padding: 0;
}
/* ======= */
@@ -280,7 +280,8 @@ thead th a {
thead th a:hover {
color: #fb0;
text-decoration: underline;
text-underline-offset: .1875rem;
text-decoration-thickness: 1px;
text-underline-offset: .25rem;
}
thead th a:active {
@@ -293,29 +294,15 @@ thead th a:active {
color: #9cf;
text-decoration: none;
text-underline-offset: 0.3rem;
padding: 0.75rem 0.8rem;
min-width: 100rem;
border-radius: 8px;
}
.log-list .icon {
margin-right: 0.6rem;
vertical-align: middle;
padding-bottom: 0.3rem;
color: #aab;
padding: 0.3rem 0;
}
.log-list a:hover {
outline: 2px solid #7de;
color: #fb0;
}
.log-list a:hover .icon {
color: #fff;
text-decoration: underline;
}
.log-list a:active {
background-color: #112;
text-decoration: none;
}
/* ===== */
@@ -453,7 +440,7 @@ table.docs-table {
table.webfeed,
table.logs {
background: black;
border-bottom: 1px solid #8e6eff;
border-bottom: 1px solid #a6f;
border-collapse: separate;
border-spacing: 0;
margin: 0 auto;
@@ -473,7 +460,7 @@ table.logs {
.webfeed th,
.logs th {
border-bottom: 1px solid #8e6eff;
border-bottom: 1px solid #a6f;
padding: 0.7rem 1.25rem;
}
@@ -485,7 +472,7 @@ table.logs {
.logs td {
font-family: 'Menlo', 'Consolas', 'Monaco', 'Liberation Mono', 'Lucida Console', monospace;
font-size: 1.1rem;
padding: 0.6rem 1.25rem;
padding: 0.75rem 1.25rem;
}
.logs td {
@@ -496,7 +483,7 @@ table.logs {
.webfeed tbody tr:hover,
.logs tbody tr:hover {
background-color: #1a1d22;
background-color: #0c0e1e;
}
table.server-info {
@@ -559,12 +546,12 @@ table.config-info tbody tr:not(:last-child) td {
}
.asc::after {
color: #8e6eff;
color: #a6f;
content: '▲';
}
.desc::after {
color: #8e6eff;
color: #a6f;
content: '▼';
}
@@ -632,45 +619,98 @@ table.live-logs {
overflow-wrap: anywhere;
}
.tooltip {
position: relative;
}
pre.tooltip-content {
background-color: #224;
border: 1px solid #cdf;
border-radius: 10px;
color: #cdf !important;
display: none;
font-family: 'Menlo', 'Consolas', 'Monaco', 'Liberation Mono', 'Lucida Console', monospace;
font-size: 0.875rem;
left: 0;
margin: 0;
max-width: 25rem;
min-width: 5rem;
overflow-x: auto;
overflow-wrap: unset;
padding: 1rem;
position: absolute;
text-align: left;
text-wrap-mode: nowrap;
top: 2.5rem;
z-index: 1;
}
table.live-logs td.tooltip:hover pre.tooltip-content {
display: block;
}
/* ======== */
/* Web Feed */
/* ======== */
/* IP */
.webfeed tbody td:nth-child(1) {
color: #48e3ff;
color: #1ee;
overflow-wrap: anywhere;
}
.webfeed tbody tr:nth-child(odd) td:nth-child(1) {
color: #aaffff;
color: #5ff;
}
/* Added */
.webfeed tbody td:nth-child(2) {
color: #8b949e;
color: #556;
}
.webfeed tbody tr:nth-child(odd) td:nth-child(2) {
color: #ccc;
color: #667;
}
/* Last Seen */
.webfeed tbody td:nth-child(3) {
color: #b8c1ff;
color: #ccd;
}
.webfeed tbody tr:nth-child(odd) td:nth-child(3) {
color: #c8e1ff;
color: #dde;
}
/* Threat Score */
.webfeed tbody td:nth-child(4) {
color: #ffff55;
color: #ee6;
text-align: right
}
.webfeed tbody tr:nth-child(odd) td:nth-child(4) {
color: #eedc82;
color: #ff5;
}
/* ===== */
/* Stats */
/* ===== */
/* Count */
.logs-stats tbody td:nth-child(1) {
color: #ee6;
text-align: right;
}
.logs-stats tbody tr:nth-child(odd) td:nth-child(1) {
color: #ff5;
}
/* Value */
.logs-stats tbody td:nth-child(2) {
color: #1ee;
overflow-wrap: anywhere;
}
.logs-stats tbody tr:nth-child(odd) td:nth-child(2) {
color: #5ff;
}
/* ======== */
@@ -678,41 +718,41 @@ table.live-logs {
/* ======== */
/* Time */
.logs-ssh tbody td:nth-child(1) {
color: #8b949e;
color: #778;
white-space: nowrap;
}
.logs-ssh tbody tr:nth-child(odd) td:nth-child(1) {
color: #ccc;
color: #99a;
}
/* Source IP */
.logs-ssh tbody td:nth-child(2) {
color: #48e3ff;
color: #1ee;
}
.logs-ssh tbody tr:nth-child(odd) td:nth-child(2) {
color: #aaffff;
color: #5ff;
}
/* Username */
.logs-ssh tbody td:nth-child(3) {
color: #b8c1ff;
color: #ed7;
overflow-wrap: anywhere;
}
.logs-ssh tbody tr:nth-child(odd) td:nth-child(3) {
color: #c8e1ff;
color: #ff5;
}
/* Password */
.logs-ssh tbody td:nth-child(4) {
color: #ffff55;
color: #8bf;
overflow-wrap: anywhere;
}
.logs-ssh tbody tr:nth-child(odd) td:nth-child(4) {
color: #eedc82;
color: #69e;
}
/* ========= */
@@ -720,40 +760,40 @@ table.live-logs {
/* ========= */
/* Time */
.logs-http tbody td:nth-child(1) {
color: #8b949e;
color: #778;
white-space: nowrap;
}
.logs-http tbody tr:nth-child(odd) td:nth-child(1) {
color: #ccc;
color: #99a;
}
/* Source IP */
.logs-http tbody td:nth-child(2) {
color: #48e3ff;
color: #1ee;
}
.logs-http tbody tr:nth-child(odd) td:nth-child(2) {
color: #aaffff;
color: #5ff;
}
/* Method */
.logs-http tbody td:nth-child(3) {
color: #b8c1ff;
color: #8bf;
}
.logs-http tbody tr:nth-child(odd) td:nth-child(3) {
color: #c8e1ff;
color: #69e;
}
/* Path */
.logs-http tbody td:nth-child(4) {
color: #ffff55;
color: #ed7;
overflow-wrap: anywhere;
}
.logs-http tbody tr:nth-child(odd) td:nth-child(4) {
color: #eedc82;
color: #ff5;
}
/* ============= */
@@ -853,10 +893,6 @@ table.live-logs {
table.live-logs {
margin: 1.5rem;
}
h2.live-logs {
display: none;
}
}
@media (max-width: 700px) {
@@ -938,6 +974,10 @@ table.live-logs {
.live-logs td:nth-child(3) {
margin-bottom: 2rem;
}
pre.tooltip-content {
top: 0;
}
}
@media (max-width: 550px) {

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,47 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Deceptifeed</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body class="full-width">
<header>
{{template "nav" .NavData}}
</header>
<main class="full-width">
{{if .Data}}
<table id="stats" class="logs logs-stats">
<thead>
<tr>
<th onclick="sortTable(0)">Count
<th onclick="sortTable(1)">{{.Header}}
</tr>
</thead>
<tbody>
{{range .Data}}<tr><td>{{.Count}}<td>{{.Field}}</tr>
{{end}}
</tbody>
</table>
{{else}}
<p class="no-results">No log data found</p>
{{end}}
</main>
<script>
function applyNumberSeparator() {
// Format 'Count' with a thousands separator based on user's locale.
const numberFormat = new Intl.NumberFormat();
document.querySelectorAll("#stats tbody tr").forEach(row => {
const observationCount = parseInt(row.cells[0].textContent, 10);
if (!isNaN(observationCount)) {
row.cells[0].textContent = numberFormat.format(observationCount);
}
});
}
applyNumberSeparator();
</script>
</body>
</html>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long