Skip to content

Commit

Permalink
add REST API for the defender
Browse files Browse the repository at this point in the history
  • Loading branch information
drakkan committed Jan 2, 2021
1 parent 037d89a commit d6b3acd
Show file tree
Hide file tree
Showing 13 changed files with 436 additions and 3 deletions.
28 changes: 28 additions & 0 deletions common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,34 @@ func IsBanned(ip string) bool {
return Config.defender.IsBanned(ip)
}

// GetDefenderBanTime returns the ban time for the given IP
// or nil if the IP is not banned or the defender is disabled
func GetDefenderBanTime(ip string) *time.Time {
if Config.defender == nil {
return nil
}

return Config.defender.GetBanTime(ip)
}

// Unban removes the specified IP address from the banned ones
func Unban(ip string) bool {
if Config.defender == nil {
return false
}

return Config.defender.Unban(ip)
}

// GetDefenderScore returns the score for the given IP
func GetDefenderScore(ip string) int {
if Config.defender == nil {
return 0
}

return Config.defender.GetScore(ip)
}

// AddDefenderEvent adds the specified defender event for the given IP
func AddDefenderEvent(ip string, event HostEvent) {
if Config.defender == nil {
Expand Down
13 changes: 13 additions & 0 deletions common/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,10 @@ func TestDefenderIntegration(t *testing.T) {
AddDefenderEvent(ip, HostEventNoLoginTried)
assert.False(t, IsBanned(ip))

assert.Nil(t, GetDefenderBanTime(ip))
assert.False(t, Unban(ip))
assert.Equal(t, 0, GetDefenderScore(ip))

Config.DefenderConfig = DefenderConfig{
Enabled: true,
BanTime: 10,
Expand All @@ -257,8 +261,17 @@ func TestDefenderIntegration(t *testing.T) {

AddDefenderEvent(ip, HostEventNoLoginTried)
assert.False(t, IsBanned(ip))
assert.Equal(t, 2, GetDefenderScore(ip))
assert.False(t, Unban(ip))
assert.Nil(t, GetDefenderBanTime(ip))

AddDefenderEvent(ip, HostEventLoginFailed)
assert.True(t, IsBanned(ip))
assert.Equal(t, 0, GetDefenderScore(ip))
assert.NotNil(t, GetDefenderBanTime(ip))
assert.True(t, Unban(ip))
assert.Nil(t, GetDefenderBanTime(ip))
assert.False(t, Unban(ip))

Config = configCopy
}
Expand Down
14 changes: 14 additions & 0 deletions common/defender.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ type Defender interface {
IsBanned(ip string) bool
GetBanTime(ip string) *time.Time
GetScore(ip string) int
Unban(ip string) bool
}

// DefenderConfig defines the "defender" configuration
Expand Down Expand Up @@ -201,6 +202,19 @@ func (d *memoryDefender) IsBanned(ip string) bool {
return false
}

// Unban removes the specified IP address from the banned ones
func (d *memoryDefender) Unban(ip string) bool {
d.Lock()
defer d.Unlock()

if _, ok := d.banned[ip]; ok {
delete(d.banned, ip)
return true
}

return false
}

// AddEvent adds an event for the given IP.
// This method must be called for clients not yet banned
func (d *memoryDefender) AddEvent(ip string, event HostEvent) {
Expand Down
3 changes: 3 additions & 0 deletions common/defender_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,9 @@ func TestBasicDefender(t *testing.T) {
assert.True(t, newBanTime.After(*banTime))
}

assert.True(t, defender.Unban(testIP3))
assert.False(t, defender.Unban(testIP3))

err = os.Remove(slFile)
assert.NoError(t, err)
err = os.Remove(blFile)
Expand Down
14 changes: 12 additions & 2 deletions docs/defender.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,23 @@ And then you can configure:

So a host is banned, for `ban_time` minutes, if it has exceeded the defined threshold during the last observation time minutes.

A banned IP has no score, it makes no sense to accumulate host events in memory for an already banned IP address.

If an already banned client tries to log in again its ban time will be incremented based on the `ban_time_increment` configuration.

The `ban_time_increment` is calculated as percentage of `ban_time`, so if `ban_time` is 30 minutes and `ban_time_increment` is 50 the host will be banned for additionally 15 minutes. You can specify values greater than 100 for `ban_time_increment`.

The `defender` will keep in memory both the host scores and the banned hosts, you can limit the memory usage using the `entries_soft_limit` and `entries_hard_limit` configuration keys.

The `defender` can also load a permanent block and/or safe list of ip addresses/networks from a file:
The REST API allows:

- to retrieve the score for an IP address
- to retrieve the ban time for an IP address
- to unban an IP address

We don't return the whole list of the banned IP addresses or all the stored scores because we store them as hash map and iterating over all the keys for an hash map is slow and will slow down new events registration.

The `defender` can also load a permanent block list and/or a safe list of ip addresses/networks from a file:

- `safelist_file`, string. Path to a file with a list of ip addresses and/or networks to never ban.
- `blocklist_file`, string. Path to a file with a list of ip addresses and/or networks to always ban.
Expand All @@ -48,6 +58,6 @@ Here is a small example:
}
```

These list will be loaded in memory for faster lookups.
These list will be loaded in memory for faster lookups. The REST API queries "live" data and not these lists.

The `defender` is optimized for fast and time constant lookups however as it keeps all the lists and the entries in memory you should carefully measure the memory requirements for your use case.
82 changes: 82 additions & 0 deletions httpd/api_defender.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package httpd

import (
"errors"
"fmt"
"net"
"net/http"
"time"

"github.com/go-chi/render"

"github.com/drakkan/sftpgo/common"
)

func getBanTime(w http.ResponseWriter, r *http.Request) {
ip := r.URL.Query().Get("ip")
err := validateIPAddress(ip)
if err != nil {
sendAPIResponse(w, r, err, "", http.StatusBadRequest)
return
}

banStatus := make(map[string]*string)

banTime := common.GetDefenderBanTime(ip)
var banTimeString *string
if banTime != nil {
rfc3339String := banTime.UTC().Format(time.RFC3339)
banTimeString = &rfc3339String
}

banStatus["date_time"] = banTimeString
render.JSON(w, r, banStatus)
}

func getScore(w http.ResponseWriter, r *http.Request) {
ip := r.URL.Query().Get("ip")
err := validateIPAddress(ip)
if err != nil {
sendAPIResponse(w, r, err, "", http.StatusBadRequest)
return
}

scoreStatus := make(map[string]int)
scoreStatus["score"] = common.GetDefenderScore(ip)

render.JSON(w, r, scoreStatus)
}

func unban(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)

var postBody map[string]string
err := render.DecodeJSON(r.Body, &postBody)
if err != nil {
sendAPIResponse(w, r, err, "", http.StatusBadRequest)
return
}

ip := postBody["ip"]
err = validateIPAddress(ip)
if err != nil {
sendAPIResponse(w, r, err, "", http.StatusBadRequest)
return
}

if common.Unban(ip) {
sendAPIResponse(w, r, nil, "OK", http.StatusOK)
} else {
sendAPIResponse(w, r, nil, "Not found", http.StatusNotFound)
}
}

func validateIPAddress(ip string) error {
if ip == "" {
return errors.New("ip address is required")
}
if net.ParseIP(ip) == nil {
return fmt.Errorf("ip address %#v is not valid", ip)
}
return nil
}
63 changes: 63 additions & 0 deletions httpd/api_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,69 @@ func GetStatus(expectedStatusCode int) (ServicesStatus, []byte, error) {
return response, body, err
}

// GetBanTime returns the ban time for the given IP address
func GetBanTime(ip string, expectedStatusCode int) (map[string]interface{}, []byte, error) {
var response map[string]interface{}
var body []byte
url, err := url.Parse(buildURLRelativeToBase(defenderBanTime))
if err != nil {
return response, body, err
}
q := url.Query()
q.Add("ip", ip)
url.RawQuery = q.Encode()
resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "")
if err != nil {
return response, body, err
}
defer resp.Body.Close()
err = checkResponse(resp.StatusCode, expectedStatusCode)
if err == nil && expectedStatusCode == http.StatusOK {
err = render.DecodeJSON(resp.Body, &response)
} else {
body, _ = getResponseBody(resp)
}
return response, body, err
}

// GetScore returns the score for the given IP address
func GetScore(ip string, expectedStatusCode int) (map[string]interface{}, []byte, error) {
var response map[string]interface{}
var body []byte
url, err := url.Parse(buildURLRelativeToBase(defenderScore))
if err != nil {
return response, body, err
}
q := url.Query()
q.Add("ip", ip)
url.RawQuery = q.Encode()
resp, err := sendHTTPRequest(http.MethodGet, url.String(), nil, "")
if err != nil {
return response, body, err
}
defer resp.Body.Close()
err = checkResponse(resp.StatusCode, expectedStatusCode)
if err == nil && expectedStatusCode == http.StatusOK {
err = render.DecodeJSON(resp.Body, &response)
} else {
body, _ = getResponseBody(resp)
}
return response, body, err
}

// UnbanIP unbans the given IP address
func UnbanIP(ip string, expectedStatusCode int) error {
postBody := make(map[string]string)
postBody["ip"] = ip
asJSON, _ := json.Marshal(postBody)
resp, err := sendHTTPRequest(http.MethodPost, buildURLRelativeToBase(defenderUnban), bytes.NewBuffer(asJSON), "")
if err != nil {
return err
}
defer resp.Body.Close()
return checkResponse(resp.StatusCode, expectedStatusCode)
}

// Dumpdata requests a backup to outputFile.
// outputFile is relative to the configured backups_path
func Dumpdata(outputFile, indent string, expectedStatusCode int) (map[string]interface{}, []byte, error) {
Expand Down
11 changes: 11 additions & 0 deletions httpd/httpd.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ const (
loadDataPath = "/api/v1/loaddata"
updateUsedQuotaPath = "/api/v1/quota_update"
updateFolderUsedQuotaPath = "/api/v1/folder_quota_update"
defenderBanTime = "/api/v1/defender/ban_time"
defenderUnban = "/api/v1/defender/unban"
defenderScore = "/api/v1/defender/score"
metricsPath = "/metrics"
webBasePath = "/web"
webUsersPath = "/web/users"
Expand All @@ -61,12 +64,17 @@ var (
certMgr *common.CertManager
)

type defenderStatus struct {
IsActive bool `json:"is_active"`
}

// ServicesStatus keep the state of the running services
type ServicesStatus struct {
SSH sftpd.ServiceStatus `json:"ssh"`
FTP ftpd.ServiceStatus `json:"ftp"`
WebDAV webdavd.ServiceStatus `json:"webdav"`
DataProvider dataprovider.ProviderStatus `json:"data_provider"`
Defender defenderStatus `json:"defender"`
}

// Conf httpd daemon configuration
Expand Down Expand Up @@ -186,6 +194,9 @@ func getServicesStatus() ServicesStatus {
FTP: ftpd.GetStatus(),
WebDAV: webdavd.GetStatus(),
DataProvider: dataprovider.GetProviderStatus(),
Defender: defenderStatus{
IsActive: common.Config.DefenderConfig.Enabled,
},
}
return status
}
Loading

0 comments on commit d6b3acd

Please sign in to comment.