mirror of
https://github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin.git
synced 2026-09-02 20:28:50 +02:00
Compare commits
10
Commits
v1.1.8-beta1
...
v1.1.11
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1fcd4f4e2f | ||
|
|
39fcc38980 | ||
|
|
dd322a966a | ||
|
|
f0bb140596 | ||
|
|
46e581eca2 | ||
|
|
50690d1ac7 | ||
|
|
b079073ff6 | ||
|
|
976cbb7d1f | ||
|
|
80726df450 | ||
|
|
4132445a79 |
@@ -30,4 +30,6 @@ Steps to reproduce the behavior:
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
<!---
|
||||
If you like the plugin, please consider starring it, so you can get updates and we get some more visibility ✨
|
||||
-->
|
||||
|
||||
@@ -16,4 +16,6 @@ A clear and concise description of what you want to happen.
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
|
||||
<!---
|
||||
If you like the plugin, please consider starring it, so you can get updates and we get some more visibility ✨
|
||||
-->
|
||||
|
||||
@@ -103,6 +103,10 @@ make run
|
||||
- string
|
||||
- default: "redis:6379"
|
||||
- hostname and port for the Redis service
|
||||
- RedisCachePassword
|
||||
- string
|
||||
- default: ""
|
||||
- Password for the Redis service
|
||||
- UpdateIntervalSeconds
|
||||
- int64
|
||||
- default: 60
|
||||
@@ -110,7 +114,7 @@ make run
|
||||
- DefaultDecisionSeconds
|
||||
- int64
|
||||
- default: 60
|
||||
- Used only in `live` mode, decision duration of accepted IPs
|
||||
- Used only in `live` mode, maximum decision duration
|
||||
- CrowdsecCapiMachineId
|
||||
- string
|
||||
- Used only in `alone` mode, login for Crowdsec CAPI
|
||||
@@ -183,6 +187,7 @@ http:
|
||||
forwardedHeadersCustomName: X-Custom-Header
|
||||
redisCacheEnabled: false
|
||||
redisCacheHost: "redis:6379"
|
||||
redisCachePassword: password
|
||||
crowdsecLapiTLSCertificateAuthority: |-
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIEBzCCAu+gAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwgZQxCzAJBgNVBAYTAlVT
|
||||
|
||||
+38
-23
@@ -15,8 +15,6 @@ import (
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
simpleredis "github.com/maxlerebourg/simpleredis"
|
||||
|
||||
cache "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/cache"
|
||||
configuration "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/configuration"
|
||||
ip "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/ip"
|
||||
@@ -35,6 +33,7 @@ const (
|
||||
|
||||
//nolint:gochecknoglobals
|
||||
var (
|
||||
isStartup = true
|
||||
isCrowdsecStreamHealthy = true
|
||||
ticker chan bool
|
||||
)
|
||||
@@ -85,7 +84,7 @@ func New(ctx context.Context, next http.Handler, config *configuration.Config, n
|
||||
crowdsecStreamRoute := ""
|
||||
crowdsecHeader := ""
|
||||
if config.CrowdsecMode == configuration.AloneMode {
|
||||
config.CrowdsecCapiMachineID, _ = configuration.GetVariable(config, "CrowdsecCapiMachineId")
|
||||
config.CrowdsecCapiMachineID, _ = configuration.GetVariable(config, "CrowdsecCapiMachineID")
|
||||
config.CrowdsecCapiPassword, _ = configuration.GetVariable(config, "CrowdsecCapiPassword")
|
||||
config.CrowdsecLapiHost = "api.crowdsec.net"
|
||||
config.CrowdsecLapiScheme = "https"
|
||||
@@ -142,20 +141,21 @@ func New(ctx context.Context, next http.Handler, config *configuration.Config, n
|
||||
},
|
||||
cacheClient: &cache.Client{},
|
||||
}
|
||||
bouncer.cacheClient.New(config.RedisCacheEnabled, config.RedisCacheHost)
|
||||
config.RedisCachePassword, _ = configuration.GetVariable(config, "RedisCachePassword")
|
||||
bouncer.cacheClient.New(config.RedisCacheEnabled, config.RedisCacheHost, config.RedisCachePassword)
|
||||
|
||||
if (config.CrowdsecMode == configuration.StreamMode || config.CrowdsecMode == configuration.AloneMode) && ticker == nil {
|
||||
if config.CrowdsecMode == configuration.AloneMode {
|
||||
err = getToken(bouncer)
|
||||
if err != nil {
|
||||
if err := getToken(bouncer); err != nil {
|
||||
logger.Error(fmt.Sprintf("New:getToken %s", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
handleStreamTicker(bouncer)
|
||||
isStartup = false
|
||||
ticker = startTicker(config, func() {
|
||||
handleStreamCache(bouncer)
|
||||
handleStreamTicker(bouncer)
|
||||
})
|
||||
go handleStreamCache(bouncer)
|
||||
}
|
||||
logger.Debug(fmt.Sprintf("New initialized mode:%s", config.CrowdsecMode))
|
||||
|
||||
@@ -193,10 +193,12 @@ func (bouncer *Bouncer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
|
||||
// TODO This should be simplified
|
||||
if bouncer.crowdsecMode != configuration.NoneMode {
|
||||
isBanned, erro := bouncer.cacheClient.GetDecision(remoteIP)
|
||||
if erro != nil {
|
||||
logger.Debug(fmt.Sprintf("ServeHTTP:getDecision ip:%s isBanned:true %s", remoteIP, erro.Error()))
|
||||
if erro.Error() == simpleredis.RedisUnreachable {
|
||||
isBanned, cacheErr := bouncer.cacheClient.GetDecision(remoteIP)
|
||||
if cacheErr != nil {
|
||||
errString := cacheErr.Error()
|
||||
logger.Debug(fmt.Sprintf("ServeHTTP:getDecision ip:%s isBanned:false %s", remoteIP, errString))
|
||||
if errString != cache.CacheMiss {
|
||||
logger.Error(fmt.Sprintf("ServeHTTP:getDecision ip:%s %s", remoteIP, errString))
|
||||
rw.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
@@ -216,7 +218,7 @@ func (bouncer *Bouncer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
if isCrowdsecStreamHealthy {
|
||||
bouncer.next.ServeHTTP(rw, req)
|
||||
} else {
|
||||
logger.Error(fmt.Sprintf("ServeHTTP isCrowdsecStreamHealthy:false ip:%s", remoteIP))
|
||||
logger.Debug(fmt.Sprintf("ServeHTTP isCrowdsecStreamHealthy:false ip:%s", remoteIP))
|
||||
rw.WriteHeader(http.StatusForbidden)
|
||||
}
|
||||
} else {
|
||||
@@ -259,6 +261,15 @@ type Login struct {
|
||||
Expire string `json:"expire"`
|
||||
}
|
||||
|
||||
func handleStreamTicker(bouncer *Bouncer) {
|
||||
if err := handleStreamCache(bouncer); err != nil {
|
||||
isCrowdsecStreamHealthy = false
|
||||
logger.Error(err.Error())
|
||||
} else {
|
||||
isCrowdsecStreamHealthy = true
|
||||
}
|
||||
}
|
||||
|
||||
func startTicker(config *configuration.Config, work func()) chan bool {
|
||||
ticker := time.NewTicker(time.Duration(config.UpdateIntervalSeconds) * time.Second)
|
||||
stop := make(chan bool, 1)
|
||||
@@ -313,7 +324,11 @@ func handleNoStreamCache(bouncer *Bouncer, remoteIP string) error {
|
||||
return fmt.Errorf("handleNoStreamCache:parseDuration %w", err)
|
||||
}
|
||||
if isLiveMode {
|
||||
bouncer.cacheClient.SetDecision(remoteIP, true, int64(duration.Seconds()))
|
||||
durationSecond := int64(duration.Seconds())
|
||||
if bouncer.defaultDecisionTimeout < durationSecond {
|
||||
durationSecond = bouncer.defaultDecisionTimeout
|
||||
}
|
||||
bouncer.cacheClient.SetDecision(remoteIP, true, durationSecond)
|
||||
}
|
||||
return fmt.Errorf("handleNoStreamCache:banned")
|
||||
}
|
||||
@@ -342,7 +357,7 @@ func getToken(bouncer *Bouncer) error {
|
||||
return fmt.Errorf("getToken statusCode:%d", login.Code)
|
||||
}
|
||||
|
||||
func handleStreamCache(bouncer *Bouncer) {
|
||||
func handleStreamCache(bouncer *Bouncer) error {
|
||||
// TODO clean properly on exit.
|
||||
// Instead of blocking the goroutine interval for all the secondary node,
|
||||
// if the master service is shut down, other goroutine can take the lead
|
||||
@@ -350,27 +365,26 @@ func handleStreamCache(bouncer *Bouncer) {
|
||||
_, err := bouncer.cacheClient.GetDecision(cacheTimeoutKey)
|
||||
if err == nil {
|
||||
logger.Debug("handleStreamCache:alreadyUpdated")
|
||||
return
|
||||
return nil
|
||||
}
|
||||
if err.Error() != cache.CacheMiss {
|
||||
return err
|
||||
}
|
||||
bouncer.cacheClient.SetDecision(cacheTimeoutKey, false, bouncer.updateInterval-1)
|
||||
streamRouteURL := url.URL{
|
||||
Scheme: bouncer.crowdsecScheme,
|
||||
Host: bouncer.crowdsecHost,
|
||||
Path: bouncer.crowdsecStreamRoute,
|
||||
RawQuery: fmt.Sprintf("startup=%t", !isCrowdsecStreamHealthy),
|
||||
RawQuery: fmt.Sprintf("startup=%t", !isCrowdsecStreamHealthy || isStartup),
|
||||
}
|
||||
body, err := crowdsecQuery(bouncer, streamRouteURL.String(), false)
|
||||
if err != nil {
|
||||
logger.Error(err.Error())
|
||||
isCrowdsecStreamHealthy = false
|
||||
return
|
||||
return err
|
||||
}
|
||||
var stream Stream
|
||||
err = json.Unmarshal(body, &stream)
|
||||
if err != nil {
|
||||
logger.Error(fmt.Sprintf("handleStreamCache:parsingBody %s", err.Error()))
|
||||
isCrowdsecStreamHealthy = false
|
||||
return
|
||||
return fmt.Errorf("handleStreamCache:parsingBody %w", err)
|
||||
}
|
||||
for _, decision := range stream.New {
|
||||
duration, err := time.ParseDuration(decision.Duration)
|
||||
@@ -383,6 +397,7 @@ func handleStreamCache(bouncer *Bouncer) {
|
||||
}
|
||||
logger.Debug("handleStreamCache:updated")
|
||||
isCrowdsecStreamHealthy = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func crowdsecQuery(bouncer *Bouncer, stringURL string, isPost bool) ([]byte, error) {
|
||||
|
||||
+6
-1
@@ -144,12 +144,17 @@ func Test_handleStreamCache(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
wantErr bool
|
||||
}{
|
||||
// TODO: Add test cases.
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
handleStreamCache(tt.args.bouncer)
|
||||
err := handleStreamCache(tt.args.bouncer)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("handleStreamCache() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ version: "3.8"
|
||||
|
||||
services:
|
||||
traefik:
|
||||
image: "traefik:v2.9.6"
|
||||
image: "traefik:v2.9.8"
|
||||
container_name: "traefik"
|
||||
restart: unless-stopped
|
||||
command:
|
||||
@@ -15,7 +15,7 @@ services:
|
||||
- "--entrypoints.web.address=:80"
|
||||
|
||||
- "--experimental.plugins.bouncer.modulename=github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin"
|
||||
- "--experimental.plugins.bouncer.version=v1.1.7"
|
||||
- "--experimental.plugins.bouncer.version=v1.1.11-beta2"
|
||||
# - "--experimental.localplugins.bouncer.modulename=github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
@@ -26,16 +26,17 @@ services:
|
||||
- 8080:8080
|
||||
depends_on:
|
||||
- crowdsec
|
||||
- redis
|
||||
- redis-insecure
|
||||
- redis-secure
|
||||
|
||||
whoami-foo:
|
||||
whoami-redis-insecure:
|
||||
image: traefik/whoami
|
||||
container_name: "simple-service-foo"
|
||||
restart: unless-stopped
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
# Definition of the router
|
||||
- "traefik.http.routers.router-foo.rule=Path(`/foo`)"
|
||||
- "traefik.http.routers.router-foo.rule=Path(`/redis-insecure`)"
|
||||
- "traefik.http.routers.router-foo.entrypoints=web"
|
||||
- "traefik.http.routers.router-foo.middlewares=crowdsec-foo@docker"
|
||||
# Definition of the service
|
||||
@@ -45,16 +46,18 @@ services:
|
||||
# crowdseclapikey must be uniq to the middleware attached to the service
|
||||
- "traefik.http.middlewares.crowdsec-foo.plugin.bouncer.crowdseclapikey=40796d93c2958f9e58345514e67740e5"
|
||||
- "traefik.http.middlewares.crowdsec-foo.plugin.bouncer.rediscacheenabled=true"
|
||||
# Contact redis-unsecure without a password
|
||||
- "traefik.http.middlewares.crowdsec-foo.plugin.bouncer.redisCacheHost=redis-insecure:6379"
|
||||
- "traefik.http.middlewares.crowdsec-foo.plugin.bouncer.loglevel=DEBUG"
|
||||
|
||||
whoami-bar:
|
||||
whoami-redis-secure:
|
||||
image: traefik/whoami
|
||||
container_name: "simple-service-bar"
|
||||
restart: unless-stopped
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
# Definition of the router
|
||||
- "traefik.http.routers.router-bar.rule=Path(`/bar`)"
|
||||
- "traefik.http.routers.router-bar.rule=Path(`/redis-secure`)"
|
||||
- "traefik.http.routers.router-bar.entrypoints=web"
|
||||
- "traefik.http.routers.router-bar.middlewares=crowdsec-bar@docker"
|
||||
# Definition of the service
|
||||
@@ -64,11 +67,14 @@ services:
|
||||
# crowdseclapikey must be uniq to the middleware attached to the service
|
||||
- "traefik.http.middlewares.crowdsec-bar.plugin.bouncer.crowdseclapikey=44c36dac5c4140af9f06f397508e82c7"
|
||||
- "traefik.http.middlewares.crowdsec-bar.plugin.bouncer.rediscacheenabled=true"
|
||||
- "traefik.http.middlewares.crowdsec-bar.plugin.bouncer.redisCachePassword=FIXME"
|
||||
# Contact redis-secure with password
|
||||
- "traefik.http.middlewares.crowdsec-bar.plugin.bouncer.redisCacheHost=redis-secure:6379"
|
||||
- "traefik.http.middlewares.crowdsec-bar.plugin.bouncer.loglevel=DEBUG"
|
||||
|
||||
|
||||
crowdsec:
|
||||
image: crowdsecurity/crowdsec:v1.4.3
|
||||
image: crowdsecurity/crowdsec:v1.4.6
|
||||
container_name: "crowdsec"
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
@@ -84,18 +90,27 @@ services:
|
||||
labels:
|
||||
- "traefik.enable=false"
|
||||
|
||||
redis:
|
||||
image: "redis:7.0.5-alpine"
|
||||
container_name: "redis"
|
||||
redis-secure:
|
||||
image: "redis:7.0.9-alpine"
|
||||
container_name: "redis-secure"
|
||||
hostname: redis-secure
|
||||
restart: unless-stopped
|
||||
command: "redis-server --save 60 1"
|
||||
command: "redis-server --save 60 1 --loglevel debug --requirepass FIXME"
|
||||
volumes:
|
||||
- redis-data:/data
|
||||
ports:
|
||||
- 6379:6379
|
||||
- redis-secure-data:/data
|
||||
|
||||
redis-insecure:
|
||||
image: "redis:7.0.9-alpine"
|
||||
container_name: "redis-insecure"
|
||||
hostname: redis-unsecure
|
||||
restart: unless-stopped
|
||||
command: "redis-server --save 60 1 --loglevel debug"
|
||||
volumes:
|
||||
- redis-unsecure-data:/data
|
||||
|
||||
volumes:
|
||||
logs-redis:
|
||||
crowdsec-db-redis:
|
||||
crowdsec-config-redis:
|
||||
redis-data:
|
||||
redis-unsecure-data:
|
||||
redis-secure-data:
|
||||
|
||||
@@ -11,10 +11,11 @@ These CAPI credentials must be set in your docker-compose.yml or in your config
|
||||
...
|
||||
whoami:
|
||||
labels:
|
||||
- "traefik.http.middlewares.crowdsec.plugin.bouncer.enabled=true"
|
||||
- "traefik.http.middlewares.crowdsec.plugin.bouncer.crowdsecMode=alone"
|
||||
- "traefik.http.middlewares.crowdsec.plugin.bouncer.crowdsecCapiMachineId=LOGIN"
|
||||
- "traefik.http.middlewares.crowdsec.plugin.bouncer.crowdsecCapiPassword=PASSWORD"
|
||||
- "traefik.http.middlewares.crowdsec.plugin.bouncer.crowdseccapiscenarios=crowdsecurity/http-generic-bf,crowdsecurity/http-xss-probing,..."
|
||||
- "traefik.http.middlewares.crowdsec.plugin.bouncer.enabled=true"
|
||||
- "traefik.http.middlewares.crowdsec.plugin.bouncer.crowdsecCapiScenarios=crowdsecurity/http-generic-bf,crowdsecurity/http-xss-probing,..."
|
||||
```
|
||||
|
||||
You can then run all the containers:
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
version: "3.8"
|
||||
|
||||
services:
|
||||
traefik:
|
||||
image: "traefik:v2.9.6"
|
||||
container_name: "traefik"
|
||||
restart: unless-stopped
|
||||
command:
|
||||
# - "--log.level=DEBUG"
|
||||
- "--accesslog"
|
||||
- "--accesslog.filepath=/var/log/traefik/access.log"
|
||||
- "--api.insecure=true"
|
||||
- "--providers.docker=true"
|
||||
- "--providers.docker.exposedbydefault=false"
|
||||
- "--entrypoints.web.address=:80"
|
||||
|
||||
- "--experimental.plugins.bouncer.modulename=github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin"
|
||||
- "--experimental.plugins.bouncer.version=v1.1.7"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
ports:
|
||||
- 80:80
|
||||
- 8080:8080
|
||||
|
||||
whoami-foo:
|
||||
image: traefik/whoami
|
||||
container_name: "simple-service-foo"
|
||||
restart: unless-stopped
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.http.routers.router-foo.rule=Path(`/foo`)"
|
||||
- "traefik.http.routers.router-foo.entrypoints=web"
|
||||
- "traefik.http.routers.router-foo.middlewares=crowdsec-foo@docker"
|
||||
- "traefik.http.services.service-foo.loadbalancer.server.port=80"
|
||||
|
||||
- "traefik.http.middlewares.crowdsec-foo.plugin.bouncer.enabled=true"
|
||||
# - "traefik.http.middlewares.crowdsec-foo.plugin.bouncer.loglevel=DEBUG"
|
||||
- "traefik.http.middlewares.crowdsec-foo.plugin.bouncer.crowdsecmode=alone"
|
||||
- "traefik.http.middlewares.crowdsec-foo.plugin.bouncer.crowdseclapikey=40796d93c2958f9e58345514e67740e5"
|
||||
- "traefik.http.middlewares.crowdsec-foo.plugin.bouncer.CrowdsecCapiMachineId=logincacacalfkrjebfreifgzfblezgyfoerxsqxsqxsqxsr"
|
||||
- "traefik.http.middlewares.crowdsec-foo.plugin.bouncer.CrowdsecCapiPassword=Password2"
|
||||
- "traefik.http.middlewares.crowdsec-foo.plugin.bouncer.crowdseccapiscenarios=crowdsecurity/sshd,crowdsecurity/asterisk_bf,crowdsecurity/asterisk_user_enum,crowdsecurity/base-http-scenarios"
|
||||
|
||||
volumes:
|
||||
logs-local:
|
||||
@@ -4,5 +4,5 @@ go 1.19
|
||||
|
||||
require (
|
||||
github.com/leprosus/golang-ttl-map v1.1.7
|
||||
github.com/maxlerebourg/simpleredis v1.0.3
|
||||
github.com/maxlerebourg/simpleredis v1.0.6
|
||||
)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
github.com/leprosus/golang-ttl-map v1.1.7 h1:cF4AAFDDnJTFSV+/42sKLhmMluvLdRlCGS2UaifH6UM=
|
||||
github.com/leprosus/golang-ttl-map v1.1.7/go.mod h1:4QWHJPeVBbrkhOhXdhCv9IEiyj/YzkO04/iexy4vSe0=
|
||||
github.com/maxlerebourg/simpleredis v1.0.3 h1:VhXq9bVytWDqD/TS/GjHKayvQb/VUeEql5F+yUbdOiI=
|
||||
github.com/maxlerebourg/simpleredis v1.0.3/go.mod h1:/DH8zOK6kDskSqoX/m5CJJdNGfkIQZd/ERBJgytDDSk=
|
||||
github.com/maxlerebourg/simpleredis v1.0.6 h1:dKd0hgKk7uGKjujWUMuPTVOAONYdlCys5Iqh6w3dOU4=
|
||||
github.com/maxlerebourg/simpleredis v1.0.6/go.mod h1:/DH8zOK6kDskSqoX/m5CJJdNGfkIQZd/ERBJgytDDSk=
|
||||
|
||||
Vendored
+10
-4
@@ -16,6 +16,9 @@ const (
|
||||
cacheNoBannedValue = "f"
|
||||
)
|
||||
|
||||
// CacheMiss error string when cache is miss.
|
||||
const CacheMiss = "cache:miss"
|
||||
|
||||
//nolint:gochecknoglobals
|
||||
var (
|
||||
redis simpleredis.SimpleRedis
|
||||
@@ -30,7 +33,7 @@ func (localCache) getDecision(clientIP string) (bool, error) {
|
||||
if isCached && isValid && len(bannedString) > 0 {
|
||||
return bannedString == cacheBannedValue, nil
|
||||
}
|
||||
return false, fmt.Errorf("cache:miss")
|
||||
return false, fmt.Errorf(CacheMiss)
|
||||
}
|
||||
|
||||
func (localCache) setDecision(clientIP string, value string, duration int64) {
|
||||
@@ -49,6 +52,9 @@ func (redisCache) getDecision(clientIP string) (bool, error) {
|
||||
if err == nil && len(bannedString) > 0 {
|
||||
return bannedString == cacheBannedValue, nil
|
||||
}
|
||||
if err.Error() == simpleredis.RedisMiss {
|
||||
return false, fmt.Errorf(CacheMiss)
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
@@ -76,9 +82,9 @@ type Client struct {
|
||||
}
|
||||
|
||||
// New Initialize cache client.
|
||||
func (client *Client) New(isRedis bool, host string) {
|
||||
func (client *Client) New(isRedis bool, host string, pass string) {
|
||||
if isRedis {
|
||||
redis.Init(host)
|
||||
redis.Init(host, pass)
|
||||
client.cache = &redisCache{}
|
||||
} else {
|
||||
client.cache = &localCache{}
|
||||
@@ -101,7 +107,7 @@ func (client *Client) GetDecision(clientIP string) (bool, error) {
|
||||
|
||||
// SetDecision update the cache with the IP as key and the value banned / not banned.
|
||||
func (client *Client) SetDecision(clientIP string, isBanned bool, duration int64) {
|
||||
logger.Debug(fmt.Sprintf("cache:SetDecision ip:%v isBanned:%v", clientIP, isBanned))
|
||||
logger.Debug(fmt.Sprintf("cache:SetDecision ip:%v isBanned:%v duration:%vs", clientIP, isBanned, duration))
|
||||
var value string
|
||||
if isBanned {
|
||||
value = cacheBannedValue
|
||||
|
||||
@@ -55,6 +55,8 @@ type Config struct {
|
||||
ClientTrustedIPs []string `json:"clientTrustedIps,omitempty"`
|
||||
RedisCacheEnabled bool `json:"redisCacheEnabled,omitempty"`
|
||||
RedisCacheHost string `json:"redisCacheHost,omitempty"`
|
||||
RedisCachePassword string `json:"redisCachePassword,omitempty"`
|
||||
RedisCachePasswordFile string `json:"redisCachePasswordFile,omitempty"`
|
||||
}
|
||||
|
||||
func contains(source []string, target string) bool {
|
||||
@@ -83,6 +85,7 @@ func New() *Config {
|
||||
ClientTrustedIPs: []string{},
|
||||
RedisCacheEnabled: false,
|
||||
RedisCacheHost: "redis:6379",
|
||||
RedisCachePassword: "",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,7 +118,7 @@ func GetVariable(config *Config, key string) (string, error) {
|
||||
|
||||
// ValidateParams validate all the param gave by user.
|
||||
//
|
||||
//nolint:gocyclo
|
||||
//nolint:gocyclo,gocognit
|
||||
func ValidateParams(config *Config) error {
|
||||
if err := validateParamsRequired(config); err != nil {
|
||||
return err
|
||||
@@ -128,8 +131,12 @@ func ValidateParams(config *Config) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := GetVariable(config, "RedisCachePassword"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if config.CrowdsecMode == AloneMode {
|
||||
if _, err := GetVariable(config, "CrowdsecCapiMachineId"); err != nil {
|
||||
if _, err := GetVariable(config, "CrowdsecCapiMachineID"); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := GetVariable(config, "CrowdsecCapiPassword"); err != nil {
|
||||
|
||||
+30
-1
@@ -1,2 +1,31 @@
|
||||
# simpleredis
|
||||
Minimal go redis with only get, set and delete operation
|
||||
Minimal go redis with only `get`, `set` and `delete` operation.
|
||||
It supports password authentication with redis.
|
||||
With **NO** external dependencies.
|
||||
|
||||
## Example
|
||||
```go
|
||||
import simpleredis "github.com/maxlerebourg/simpleredis"
|
||||
|
||||
var redis simpleredis.SimpleRedis
|
||||
|
||||
redis.Init("redis:6379", "") // redisHost, redisPass
|
||||
|
||||
err := redis.Set("test", []bytes("whatever"), 60), // Set key "test" with "whatever" for 60 seconds
|
||||
if err != nil {
|
||||
...
|
||||
}
|
||||
val, err := redis.Get("test") // get key test
|
||||
if err != nil {
|
||||
// err could be only redis:unreachable, redis:miss or redis:timeout available in simpleredis.RedisUnreachable
|
||||
...
|
||||
}
|
||||
err = redis.Del("test")
|
||||
if err != nil {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
## Author
|
||||
Max Lerebourg @ [Primadviz.com](https://primadviz.com)
|
||||
Mathieu Hanotaux
|
||||
+46
-19
@@ -17,10 +17,11 @@ const (
|
||||
RedisUnreachable = "redis:unreachable"
|
||||
RedisMiss = "redis:miss"
|
||||
RedisTimeout = "redis:timeout"
|
||||
RedisNoAuth = "redis:noauth"
|
||||
)
|
||||
|
||||
// A RedisCmd is used to communicate with redis at low level using commands.
|
||||
type RedisCmd struct {
|
||||
// A redisCmd is used to communicate with redis at low level using commands.
|
||||
type redisCmd struct {
|
||||
Command string
|
||||
Name string
|
||||
Data []byte
|
||||
@@ -30,7 +31,8 @@ type RedisCmd struct {
|
||||
|
||||
// A SimpleRedis is used to communicate with redis.
|
||||
type SimpleRedis struct {
|
||||
redisHost string
|
||||
host string
|
||||
pass string
|
||||
}
|
||||
|
||||
func genRedisArray(params ...[]byte) []byte {
|
||||
@@ -49,11 +51,11 @@ func send(wr *textproto.Writer, method string, data []byte) {
|
||||
}
|
||||
}
|
||||
|
||||
func askRedis(hostnamePort string, cmd RedisCmd, channel chan RedisCmd) {
|
||||
func askRedis(sr *SimpleRedis, cmd redisCmd, channel chan redisCmd) {
|
||||
dialer := net.Dialer{Timeout: 2 * time.Second}
|
||||
conn, err := dialer.Dial("tcp", hostnamePort)
|
||||
conn, err := dialer.Dial("tcp", sr.host)
|
||||
if err != nil {
|
||||
channel <- RedisCmd{Error: fmt.Errorf(RedisUnreachable)}
|
||||
channel <- redisCmd{Error: fmt.Errorf(RedisUnreachable)}
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
@@ -65,6 +67,26 @@ func askRedis(hostnamePort string, cmd RedisCmd, channel chan RedisCmd) {
|
||||
writer := textproto.NewWriter(bufio.NewWriter(conn))
|
||||
reader := textproto.NewReader(bufio.NewReader(conn))
|
||||
|
||||
if sr.pass != "" {
|
||||
data := genRedisArray([]byte("AUTH"), []byte(sr.pass))
|
||||
send(writer, "auth", data)
|
||||
for {
|
||||
select {
|
||||
case <-time.After(time.Second * 1):
|
||||
channel <- redisCmd{Error: fmt.Errorf(RedisTimeout)}
|
||||
return
|
||||
default:
|
||||
read, _ := reader.ReadLineBytes()
|
||||
if string(read) != "+OK" {
|
||||
channel <- redisCmd{Error: fmt.Errorf(RedisNoAuth)}
|
||||
return
|
||||
}
|
||||
}
|
||||
// breaks out of for
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
switch cmd.Command {
|
||||
case "SET":
|
||||
data := genRedisArray([]byte("SET"), []byte(cmd.Name), cmd.Data, []byte("EX"), []byte(fmt.Sprintf("%d", cmd.Duration)))
|
||||
@@ -78,16 +100,20 @@ func askRedis(hostnamePort string, cmd RedisCmd, channel chan RedisCmd) {
|
||||
for {
|
||||
select {
|
||||
case <-time.After(time.Second * 1):
|
||||
channel <- RedisCmd{Error: fmt.Errorf(RedisTimeout)}
|
||||
channel <- redisCmd{Error: fmt.Errorf(RedisTimeout)}
|
||||
return
|
||||
default:
|
||||
read, _ := reader.ReadLineBytes()
|
||||
if string(read) != "$1" {
|
||||
channel <- RedisCmd{Error: fmt.Errorf(RedisMiss)}
|
||||
str := string(read)
|
||||
if strings.Contains(str, "-NOAUTH") {
|
||||
channel <- redisCmd{Error: fmt.Errorf(RedisNoAuth)}
|
||||
return
|
||||
} else if str != "$1" {
|
||||
channel <- redisCmd{Error: fmt.Errorf(RedisMiss)}
|
||||
return
|
||||
}
|
||||
read, _ = reader.ReadLineBytes()
|
||||
channel <- RedisCmd{Data: read}
|
||||
channel <- redisCmd{Data: read}
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -95,18 +121,19 @@ func askRedis(hostnamePort string, cmd RedisCmd, channel chan RedisCmd) {
|
||||
}
|
||||
|
||||
// Init sets the redisHost used to connect to redis.
|
||||
func (sr *SimpleRedis) Init(redisHost string) {
|
||||
sr.redisHost = redisHost
|
||||
func (sr *SimpleRedis) Init(host string, pass string) {
|
||||
sr.host = host
|
||||
sr.pass = pass
|
||||
}
|
||||
|
||||
// Get fetches the value for key name in redis.
|
||||
func (sr *SimpleRedis) Get(name string) ([]byte, error) {
|
||||
redisCmd := RedisCmd{
|
||||
cmd := redisCmd{
|
||||
Command: "GET",
|
||||
Name: name,
|
||||
}
|
||||
channel := make(chan RedisCmd)
|
||||
go askRedis(sr.redisHost, redisCmd, channel)
|
||||
channel := make(chan redisCmd)
|
||||
go askRedis(sr, cmd, channel)
|
||||
resp := <-channel
|
||||
if resp.Error != nil {
|
||||
return nil, resp.Error
|
||||
@@ -116,22 +143,22 @@ func (sr *SimpleRedis) Get(name string) ([]byte, error) {
|
||||
|
||||
// Set updates the value for key name in redis with value data for duration.
|
||||
func (sr *SimpleRedis) Set(name string, data []byte, duration int64) error {
|
||||
redisCmd := RedisCmd{
|
||||
cmd := redisCmd{
|
||||
Command: "SET",
|
||||
Name: name,
|
||||
Data: data,
|
||||
Duration: duration,
|
||||
}
|
||||
go askRedis(sr.redisHost, redisCmd, nil)
|
||||
go askRedis(sr, cmd, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Del removes the key name in redis.
|
||||
func (sr *SimpleRedis) Del(name string) error {
|
||||
redisCmd := RedisCmd{
|
||||
cmd := redisCmd{
|
||||
Command: "DEL",
|
||||
Name: name,
|
||||
}
|
||||
go askRedis(sr.redisHost, redisCmd, nil)
|
||||
go askRedis(sr, cmd, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
Vendored
+1
-1
@@ -1,6 +1,6 @@
|
||||
# github.com/leprosus/golang-ttl-map v1.1.7
|
||||
## explicit; go 1.15
|
||||
github.com/leprosus/golang-ttl-map
|
||||
# github.com/maxlerebourg/simpleredis v1.0.3
|
||||
# github.com/maxlerebourg/simpleredis v1.0.6
|
||||
## explicit; go 1.19
|
||||
github.com/maxlerebourg/simpleredis
|
||||
|
||||
Reference in New Issue
Block a user