diff --git a/docs/widgets/services/crowdsec.md b/docs/widgets/services/crowdsec.md index da4d5e090..608367dfd 100644 --- a/docs/widgets/services/crowdsec.md +++ b/docs/widgets/services/crowdsec.md @@ -5,13 +5,15 @@ description: Crowdsec Widget Configuration Learn more about [Crowdsec](https://crowdsec.net). -Get your API key by registering a bouncer with your instance, see the [Crowdsec docs](https://docs.crowdsec.net/docs/local_api/intro#bouncers). +See the [crowdsec docs](https://docs.crowdsec.net/docs/local_api/intro/#machines) for information about registering a machine, +in most instances you can use the default credentials (`/etc/crowdsec/local_api_credentials.yaml`). -Allowed fields: ["totalDecisions", "activeBans"] +Allowed fields: ["alerts", "bans"] ```yaml widget: type: crowdsec url: http://crowdsechostorip:port - key: yourcrowdsecbouncerkey + username: localhost # machine_id in crowdsec + passowrd: password ``` diff --git a/public/locales/en/common.json b/public/locales/en/common.json index 39cb3230d..98daae9e5 100644 --- a/public/locales/en/common.json +++ b/public/locales/en/common.json @@ -874,8 +874,7 @@ "totalValue": "Total Value" }, "crowdsec": { - "bans": "Bans", - "captchas": "Captchas", - "rateLimits": "Rate Limits" + "alerts": "Alerts", + "bans": "Bans" } } diff --git a/src/widgets/crowdsec/component.jsx b/src/widgets/crowdsec/component.jsx index 4e6c1babd..9565ee73f 100644 --- a/src/widgets/crowdsec/component.jsx +++ b/src/widgets/crowdsec/component.jsx @@ -9,31 +9,26 @@ export default function Component({ service }) { const { widget } = service; - const { data: bansData, error: bansError } = useWidgetAPI(widget, "bans"); - const { data: captchasData, error: captchasError } = useWidgetAPI(widget, "captchas"); - const { data: rateLimitsData, error: rateLimitsError } = useWidgetAPI(widget, "rateLimits"); + const { data: alerts, error: alertsError } = useWidgetAPI(widget, "alerts"); + const { data: bans, error: bansError } = useWidgetAPI(widget, "bans"); - if (bansError || captchasError || rateLimitsError) { - return ; + if (alertsError || bansError) { + return ; } - if (!bansData && !captchasData && !rateLimitsData) { + if (!alerts || !bans) { return ( + - - ); } - console.log(bansData); - return ( - - - + + ); } diff --git a/src/widgets/crowdsec/proxy.js b/src/widgets/crowdsec/proxy.js new file mode 100644 index 000000000..e5569ebaa --- /dev/null +++ b/src/widgets/crowdsec/proxy.js @@ -0,0 +1,91 @@ +import cache from "memory-cache"; + +import { httpProxy } from "utils/proxy/http"; +import { formatApiCall } from "utils/proxy/api-helpers"; +import getServiceWidget from "utils/config/service-helpers"; +import createLogger from "utils/logger"; +import widgets from "widgets/widgets"; +import { log } from "winston"; + +const proxyName = "crowdsecProxyHandler"; +const logger = createLogger(proxyName); +const sessionTokenCacheKey = `${proxyName}__sessionToken`; + +async function login(widget, service) { + const url = formatApiCall(widgets[widget.type].loginURL, widget); + const [status, , data] = await httpProxy(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + "User-Agent": "Mozilla/5.0", // Crowdsec requires a user-agent + }, + body: JSON.stringify({ + machine_id: widget.username, + password: widget.password, + scenarios: [], + }), + }); + + const dataParsed = JSON.parse(data); + + if (!(status === 200) || !dataParsed.token) { + logger.error("Failed to login to Crowdsec API, status: %d", status); + cache.del(`${sessionTokenCacheKey}.${service}`); + } + cache.put(`${sessionTokenCacheKey}.${service}`, dataParsed.token, new Date(dataParsed.expire) - new Date()); +} + +export default async function crowdsecProxyHandler(req, res) { + const { group, service, endpoint } = req.query; + + if (!group || !service) { + logger.error("Invalid or missing service '%s' or group '%s'", service, group); + return res.status(400).json({ error: "Invalid proxy service type" }); + } + + const widget = await getServiceWidget(group, service); + if (!widget || !widgets[widget.type].api) { + logger.error("Invalid or missing widget for service '%s' in group '%s'", service, group); + return res.status(400).json({ error: "Invalid widget configuration" }); + } + + if (!cache.get(`${sessionTokenCacheKey}.${service}`)) { + await login(widget, service); + } + + const token = cache.get(`${sessionTokenCacheKey}.${service}`); + if (!token) { + return res.status(500).json({ error: "Failed to authenticate with Crowdsec" }); + } + + const url = new URL(formatApiCall(widgets[widget.type].api, { endpoint, ...widget })); + + try { + const params = { + method: "GET", + headers: { + "User-Agent": "Mozilla/5.0", // Crowdsec requires a user-agent + "Content-Type": "application/json", + Authorization: `Bearer ${token}`, + }, + }; + + logger.debug("Calling Crowdsec API endpoint: %s", endpoint); + + if (endpoint.indexOf("decisions") === 0) { + delete params.headers["Authorization"]; + } + + const [status, , data] = await httpProxy(url, params); + + if (status !== 200) { + logger.error("Error calling Crowdsec API: %d. Data: %s", status, data); + return res.status(status).json({ error: "Crowdsec API Error", data }); + } + + return res.status(status).send(data); + } catch (error) { + logger.error("Exception calling Crowdsec API: %s", error.message); + return res.status(500).json({ error: "Crowdsec API Error", message: error.message }); + } +} diff --git a/src/widgets/crowdsec/widget.js b/src/widgets/crowdsec/widget.js index 80b510fbd..d29fa1f16 100644 --- a/src/widgets/crowdsec/widget.js +++ b/src/widgets/crowdsec/widget.js @@ -1,18 +1,16 @@ -import credentialedProxyHandler from "utils/proxy/handlers/credentialed"; +import crowdsecProxyHandler from "./proxy"; const widget = { api: "{url}/v1/{endpoint}", - proxyHandler: credentialedProxyHandler, + loginURL: "{url}/v1/watchers/login", + proxyHandler: crowdsecProxyHandler, mappings: { - bans: { - endpoint: "decisions?type=ban&origins=crowdsec", - }, - captchas: { - endpoint: "decisions?type=captcha&origins=crowdsec", + alerts: { + endpoint: "alerts", }, - rateLimits: { - endpoint: "decisions?type=rate-limit&origins=crowdsec", + bans: { + endpoint: "alerts?decision_type=ban&origin=crowdsec&has_active_decision=1", }, }, };