2020-07-27 11:47:32 +00:00
|
|
|
package cwhub
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2023-11-24 14:57:32 +00:00
|
|
|
"net/http"
|
2022-05-24 13:46:48 +00:00
|
|
|
"path/filepath"
|
2023-11-28 22:51:51 +00:00
|
|
|
"sort"
|
2022-05-24 13:46:48 +00:00
|
|
|
"strings"
|
2023-11-24 14:57:32 +00:00
|
|
|
"time"
|
2024-03-25 09:40:41 +00:00
|
|
|
|
|
|
|
"github.com/crowdsecurity/go-cs-lib/version"
|
2023-10-09 19:33:35 +00:00
|
|
|
)
|
2020-07-27 11:47:32 +00:00
|
|
|
|
2024-03-25 09:40:41 +00:00
|
|
|
// hubTransport wraps a Transport to set a custom User-Agent.
|
|
|
|
type hubTransport struct {
|
|
|
|
http.RoundTripper
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *hubTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
|
|
req.Header.Set("User-Agent", "crowdsec/"+version.String())
|
|
|
|
return t.RoundTripper.RoundTrip(req)
|
|
|
|
}
|
|
|
|
|
|
|
|
// hubClient is the HTTP client used to communicate with the CrowdSec Hub.
|
2023-11-24 14:57:32 +00:00
|
|
|
var hubClient = &http.Client{
|
|
|
|
Timeout: 120 * time.Second,
|
2024-03-25 09:40:41 +00:00
|
|
|
Transport: &hubTransport{http.DefaultTransport},
|
2023-10-05 07:35:03 +00:00
|
|
|
}
|
|
|
|
|
2023-11-24 14:57:32 +00:00
|
|
|
// safePath returns a joined path and ensures that it does not escape the base directory.
|
|
|
|
func safePath(dir, filePath string) (string, error) {
|
|
|
|
absBaseDir, err := filepath.Abs(filepath.Clean(dir))
|
2023-10-05 07:35:03 +00:00
|
|
|
if err != nil {
|
2023-11-24 14:57:32 +00:00
|
|
|
return "", err
|
2022-04-20 13:44:48 +00:00
|
|
|
}
|
2023-10-03 09:20:56 +00:00
|
|
|
|
2023-11-24 14:57:32 +00:00
|
|
|
absFilePath, err := filepath.Abs(filepath.Join(dir, filePath))
|
2022-04-20 13:44:48 +00:00
|
|
|
if err != nil {
|
2023-11-24 14:57:32 +00:00
|
|
|
return "", err
|
2022-04-20 13:44:48 +00:00
|
|
|
}
|
2023-06-29 09:34:59 +00:00
|
|
|
|
2023-11-24 14:57:32 +00:00
|
|
|
if !strings.HasPrefix(absFilePath, absBaseDir) {
|
|
|
|
return "", fmt.Errorf("path %s escapes base directory %s", filePath, dir)
|
2020-07-27 11:47:32 +00:00
|
|
|
}
|
|
|
|
|
2023-11-24 14:57:32 +00:00
|
|
|
return absFilePath, nil
|
2020-07-27 11:47:32 +00:00
|
|
|
}
|
2023-11-28 22:51:51 +00:00
|
|
|
|
|
|
|
// SortItemSlice sorts a slice of items by name, case insensitive.
|
|
|
|
func SortItemSlice(items []*Item) {
|
|
|
|
sort.Slice(items, func(i, j int) bool {
|
|
|
|
return strings.ToLower(items[i].Name) < strings.ToLower(items[j].Name)
|
|
|
|
})
|
|
|
|
}
|