2021-07-11 13:26:51 +00:00
|
|
|
// Package util provides some common utility methods
|
|
|
|
package util
|
2019-07-20 10:26:52 +00:00
|
|
|
|
|
|
|
import (
|
2021-03-26 14:19:01 +00:00
|
|
|
"bytes"
|
2020-02-16 17:17:39 +00:00
|
|
|
"crypto/ecdsa"
|
2020-10-19 12:30:40 +00:00
|
|
|
"crypto/ed25519"
|
2020-02-16 17:17:39 +00:00
|
|
|
"crypto/elliptic"
|
2020-01-19 06:41:05 +00:00
|
|
|
"crypto/rand"
|
2020-02-16 17:17:39 +00:00
|
|
|
"crypto/rsa"
|
2021-02-18 19:17:16 +00:00
|
|
|
"crypto/tls"
|
2020-02-16 17:17:39 +00:00
|
|
|
"crypto/x509"
|
|
|
|
"encoding/pem"
|
2020-01-19 06:41:05 +00:00
|
|
|
"errors"
|
2019-10-07 16:19:01 +00:00
|
|
|
"fmt"
|
2020-03-02 08:34:13 +00:00
|
|
|
"html/template"
|
2020-01-19 06:41:05 +00:00
|
|
|
"io"
|
2019-11-11 14:20:00 +00:00
|
|
|
"net"
|
2020-12-29 18:02:56 +00:00
|
|
|
"net/http"
|
2021-05-12 20:44:17 +00:00
|
|
|
"net/url"
|
2020-02-16 17:17:39 +00:00
|
|
|
"os"
|
2020-02-23 10:30:26 +00:00
|
|
|
"path"
|
|
|
|
"path/filepath"
|
2020-03-04 08:27:14 +00:00
|
|
|
"runtime"
|
2019-08-17 13:20:49 +00:00
|
|
|
"strings"
|
2019-07-20 10:26:52 +00:00
|
|
|
"time"
|
2020-02-16 17:17:39 +00:00
|
|
|
|
2021-11-06 13:13:20 +00:00
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/lithammer/shortuuid/v3"
|
2021-01-17 21:29:08 +00:00
|
|
|
"github.com/rs/xid"
|
2020-02-16 17:17:39 +00:00
|
|
|
"golang.org/x/crypto/ssh"
|
2020-05-06 17:36:34 +00:00
|
|
|
|
2021-06-26 05:31:41 +00:00
|
|
|
"github.com/drakkan/sftpgo/v2/logger"
|
2019-07-20 10:26:52 +00:00
|
|
|
)
|
|
|
|
|
2021-01-17 21:29:08 +00:00
|
|
|
const (
|
2021-09-18 08:50:17 +00:00
|
|
|
logSender = "util"
|
2021-03-21 21:21:04 +00:00
|
|
|
osWindows = "windows"
|
2021-01-17 21:29:08 +00:00
|
|
|
)
|
2019-07-20 10:26:52 +00:00
|
|
|
|
2021-05-11 04:54:06 +00:00
|
|
|
var (
|
2021-05-30 21:07:46 +00:00
|
|
|
xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
|
|
|
|
xRealIP = http.CanonicalHeaderKey("X-Real-IP")
|
|
|
|
cfConnectingIP = http.CanonicalHeaderKey("CF-Connecting-IP")
|
|
|
|
trueClientIP = http.CanonicalHeaderKey("True-Client-IP")
|
2021-05-11 04:54:06 +00:00
|
|
|
)
|
|
|
|
|
2019-07-30 18:51:29 +00:00
|
|
|
// IsStringInSlice searches a string in a slice and returns true if the string is found
|
2019-07-20 10:26:52 +00:00
|
|
|
func IsStringInSlice(obj string, list []string) bool {
|
2021-05-06 19:35:43 +00:00
|
|
|
for i := 0; i < len(list); i++ {
|
|
|
|
if list[i] == obj {
|
2019-07-20 10:26:52 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2019-08-17 13:20:49 +00:00
|
|
|
// IsStringPrefixInSlice searches a string prefix in a slice and returns true
|
|
|
|
// if a matching prefix is found
|
|
|
|
func IsStringPrefixInSlice(obj string, list []string) bool {
|
2021-05-06 19:35:43 +00:00
|
|
|
for i := 0; i < len(list); i++ {
|
|
|
|
if strings.HasPrefix(obj, list[i]) {
|
2019-08-17 13:20:49 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-11-16 18:21:50 +00:00
|
|
|
// RemoveDuplicates returns a new slice removing any duplicate element from the initial one
|
|
|
|
func RemoveDuplicates(obj []string) []string {
|
|
|
|
if len(obj) == 0 {
|
|
|
|
return obj
|
|
|
|
}
|
|
|
|
result := make([]string, 0, len(obj))
|
|
|
|
seen := make(map[string]bool)
|
|
|
|
for _, item := range obj {
|
|
|
|
if _, ok := seen[item]; !ok {
|
|
|
|
result = append(result, item)
|
|
|
|
}
|
|
|
|
seen[item] = true
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2019-07-20 10:26:52 +00:00
|
|
|
// GetTimeAsMsSinceEpoch returns unix timestamp as milliseconds from a time struct
|
|
|
|
func GetTimeAsMsSinceEpoch(t time.Time) int64 {
|
|
|
|
return t.UnixNano() / 1000000
|
|
|
|
}
|
|
|
|
|
2019-10-07 16:19:01 +00:00
|
|
|
// GetTimeFromMsecSinceEpoch return a time struct from a unix timestamp with millisecond precision
|
|
|
|
func GetTimeFromMsecSinceEpoch(msec int64) time.Time {
|
|
|
|
return time.Unix(0, msec*1000000)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetDurationAsString returns a string representation for a time.Duration
|
|
|
|
func GetDurationAsString(d time.Duration) string {
|
|
|
|
d = d.Round(time.Second)
|
|
|
|
h := d / time.Hour
|
|
|
|
d -= h * time.Hour
|
|
|
|
m := d / time.Minute
|
|
|
|
d -= m * time.Minute
|
|
|
|
s := d / time.Second
|
|
|
|
if h > 0 {
|
|
|
|
return fmt.Sprintf("%02d:%02d:%02d", h, m, s)
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%02d:%02d", m, s)
|
|
|
|
}
|
|
|
|
|
|
|
|
// ByteCountSI returns humanized size in SI (decimal) format
|
|
|
|
func ByteCountSI(b int64) string {
|
|
|
|
return byteCount(b, 1000)
|
|
|
|
}
|
|
|
|
|
|
|
|
// ByteCountIEC returns humanized size in IEC (binary) format
|
|
|
|
func ByteCountIEC(b int64) string {
|
|
|
|
return byteCount(b, 1024)
|
|
|
|
}
|
|
|
|
|
|
|
|
func byteCount(b int64, unit int64) string {
|
|
|
|
if b < unit {
|
|
|
|
return fmt.Sprintf("%d B", b)
|
|
|
|
}
|
|
|
|
div, exp := unit, 0
|
|
|
|
for n := b / unit; n >= unit; n /= unit {
|
|
|
|
div *= unit
|
|
|
|
exp++
|
|
|
|
}
|
|
|
|
if unit == 1000 {
|
|
|
|
return fmt.Sprintf("%.1f %cB",
|
|
|
|
float64(b)/float64(div), "KMGTPE"[exp])
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%.1f %ciB",
|
|
|
|
float64(b)/float64(div), "KMGTPE"[exp])
|
|
|
|
}
|
2019-11-11 14:20:00 +00:00
|
|
|
|
|
|
|
// GetIPFromRemoteAddress returns the IP from the remote address.
|
|
|
|
// If the given remote address cannot be parsed it will be returned unchanged
|
|
|
|
func GetIPFromRemoteAddress(remoteAddress string) string {
|
|
|
|
ip, _, err := net.SplitHostPort(remoteAddress)
|
|
|
|
if err == nil {
|
|
|
|
return ip
|
|
|
|
}
|
|
|
|
return remoteAddress
|
|
|
|
}
|
2020-01-19 06:41:05 +00:00
|
|
|
|
|
|
|
// NilIfEmpty returns nil if the input string is empty
|
|
|
|
func NilIfEmpty(s string) *string {
|
|
|
|
if len(s) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return &s
|
|
|
|
}
|
|
|
|
|
2020-02-16 17:17:39 +00:00
|
|
|
// GenerateRSAKeys generate rsa private and public keys and write the
|
|
|
|
// private key to specified file and the public key to the specified
|
|
|
|
// file adding the .pub suffix
|
|
|
|
func GenerateRSAKeys(file string) error {
|
2020-10-05 12:16:57 +00:00
|
|
|
if err := createDirPathIfMissing(file, 0700); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-02-16 17:17:39 +00:00
|
|
|
key, err := rsa.GenerateKey(rand.Reader, 4096)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer o.Close()
|
|
|
|
|
|
|
|
priv := &pem.Block{
|
|
|
|
Type: "RSA PRIVATE KEY",
|
|
|
|
Bytes: x509.MarshalPKCS1PrivateKey(key),
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := pem.Encode(o, priv); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
pub, err := ssh.NewPublicKey(&key.PublicKey)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-02-25 20:53:04 +00:00
|
|
|
return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
|
2020-02-16 17:17:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// GenerateECDSAKeys generate ecdsa private and public keys and write the
|
|
|
|
// private key to specified file and the public key to the specified
|
|
|
|
// file adding the .pub suffix
|
|
|
|
func GenerateECDSAKeys(file string) error {
|
2020-10-05 12:16:57 +00:00
|
|
|
if err := createDirPathIfMissing(file, 0700); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-02-16 17:17:39 +00:00
|
|
|
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-10-19 12:30:40 +00:00
|
|
|
keyBytes, err := x509.MarshalECPrivateKey(key)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
priv := &pem.Block{
|
|
|
|
Type: "EC PRIVATE KEY",
|
|
|
|
Bytes: keyBytes,
|
|
|
|
}
|
|
|
|
|
2020-02-16 17:17:39 +00:00
|
|
|
o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer o.Close()
|
|
|
|
|
2020-10-19 12:30:40 +00:00
|
|
|
if err := pem.Encode(o, priv); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
pub, err := ssh.NewPublicKey(&key.PublicKey)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-02-25 20:53:04 +00:00
|
|
|
return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
|
2020-10-19 12:30:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// GenerateEd25519Keys generate ed25519 private and public keys and write the
|
|
|
|
// private key to specified file and the public key to the specified
|
|
|
|
// file adding the .pub suffix
|
|
|
|
func GenerateEd25519Keys(file string) error {
|
|
|
|
pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
keyBytes, err := x509.MarshalPKCS8PrivateKey(privKey)
|
2020-02-16 17:17:39 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
priv := &pem.Block{
|
2020-10-19 12:30:40 +00:00
|
|
|
Type: "PRIVATE KEY",
|
2020-02-16 17:17:39 +00:00
|
|
|
Bytes: keyBytes,
|
|
|
|
}
|
2020-10-19 12:30:40 +00:00
|
|
|
o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer o.Close()
|
2020-02-16 17:17:39 +00:00
|
|
|
|
|
|
|
if err := pem.Encode(o, priv); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-10-19 12:30:40 +00:00
|
|
|
pub, err := ssh.NewPublicKey(pubKey)
|
2020-02-16 17:17:39 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-02-25 20:53:04 +00:00
|
|
|
return os.WriteFile(file+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
|
2020-02-16 17:17:39 +00:00
|
|
|
}
|
2020-02-23 10:30:26 +00:00
|
|
|
|
2021-03-21 18:15:47 +00:00
|
|
|
// GetDirsForVirtualPath returns all the directory for the given path in reverse order
|
2020-02-23 10:30:26 +00:00
|
|
|
// for example if the path is: /1/2/3/4 it returns:
|
|
|
|
// [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
|
2021-03-21 18:15:47 +00:00
|
|
|
func GetDirsForVirtualPath(virtualPath string) []string {
|
|
|
|
if virtualPath == "." {
|
|
|
|
virtualPath = "/"
|
|
|
|
} else {
|
|
|
|
if !path.IsAbs(virtualPath) {
|
|
|
|
virtualPath = CleanPath(virtualPath)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
dirsForPath := []string{virtualPath}
|
2020-02-23 10:30:26 +00:00
|
|
|
for {
|
2021-03-21 18:15:47 +00:00
|
|
|
if virtualPath == "/" {
|
2020-02-23 10:30:26 +00:00
|
|
|
break
|
|
|
|
}
|
2021-03-21 18:15:47 +00:00
|
|
|
virtualPath = path.Dir(virtualPath)
|
|
|
|
dirsForPath = append(dirsForPath, virtualPath)
|
2020-02-23 10:30:26 +00:00
|
|
|
}
|
|
|
|
return dirsForPath
|
|
|
|
}
|
|
|
|
|
2020-08-11 21:56:10 +00:00
|
|
|
// CleanPath returns a clean POSIX (/) absolute path to work with
|
|
|
|
func CleanPath(p string) string {
|
|
|
|
p = filepath.ToSlash(p)
|
2020-02-23 10:30:26 +00:00
|
|
|
if !path.IsAbs(p) {
|
2020-08-11 21:56:10 +00:00
|
|
|
p = "/" + p
|
2020-02-23 10:30:26 +00:00
|
|
|
}
|
2020-08-11 21:56:10 +00:00
|
|
|
return path.Clean(p)
|
2020-02-23 10:30:26 +00:00
|
|
|
}
|
2020-03-02 08:34:13 +00:00
|
|
|
|
2021-06-05 16:06:53 +00:00
|
|
|
// LoadTemplate parses the given template paths.
|
2021-10-02 20:25:41 +00:00
|
|
|
// It behaves like template.Must but it writes a log before exiting.
|
|
|
|
// You can optionally provide a base template (e.g. to define some custom functions)
|
2021-06-05 16:06:53 +00:00
|
|
|
func LoadTemplate(base *template.Template, paths ...string) *template.Template {
|
|
|
|
var t *template.Template
|
|
|
|
var err error
|
|
|
|
|
|
|
|
if base != nil {
|
2021-09-30 08:23:25 +00:00
|
|
|
base, err = base.Clone()
|
2021-06-05 16:06:53 +00:00
|
|
|
if err == nil {
|
2021-09-30 08:23:25 +00:00
|
|
|
t, err = base.ParseFiles(paths...)
|
2021-06-05 16:06:53 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
t, err = template.ParseFiles(paths...)
|
|
|
|
}
|
|
|
|
|
2020-03-02 08:34:13 +00:00
|
|
|
if err != nil {
|
|
|
|
logger.ErrorToConsole("error loading required template: %v", err)
|
|
|
|
logger.Error(logSender, "", "error loading required template: %v", err)
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return t
|
|
|
|
}
|
2020-03-03 08:09:58 +00:00
|
|
|
|
|
|
|
// IsFileInputValid returns true this is a valid file name.
|
|
|
|
// This method must be used before joining a file name, generally provided as
|
|
|
|
// user input, with a directory
|
|
|
|
func IsFileInputValid(fileInput string) bool {
|
|
|
|
cleanInput := filepath.Clean(fileInput)
|
|
|
|
if cleanInput == "." || cleanInput == ".." {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
2020-03-04 08:27:14 +00:00
|
|
|
|
|
|
|
// CleanDirInput sanitizes user input for directories.
|
|
|
|
// On Windows it removes any trailing `"`.
|
|
|
|
// We try to help windows users that set an invalid path such as "C:\ProgramData\SFTPGO\".
|
|
|
|
// This will only help if the invalid path is the last argument, for example in this command:
|
|
|
|
// sftpgo.exe serve -c "C:\ProgramData\SFTPGO\" -l "sftpgo.log"
|
|
|
|
// the -l flag will be ignored and the -c flag will get the value `C:\ProgramData\SFTPGO" -l sftpgo.log`
|
|
|
|
// since the backslash after SFTPGO escape the double quote. This is definitely a bad user input
|
|
|
|
func CleanDirInput(dirInput string) string {
|
2021-03-21 21:21:04 +00:00
|
|
|
if runtime.GOOS == osWindows {
|
2020-03-04 08:27:14 +00:00
|
|
|
for strings.HasSuffix(dirInput, "\"") {
|
|
|
|
dirInput = strings.TrimSuffix(dirInput, "\"")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return filepath.Clean(dirInput)
|
|
|
|
}
|
2020-10-05 12:16:57 +00:00
|
|
|
|
|
|
|
func createDirPathIfMissing(file string, perm os.FileMode) error {
|
|
|
|
dirPath := filepath.Dir(file)
|
|
|
|
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
|
|
|
|
err = os.MkdirAll(dirPath, perm)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2020-12-29 18:02:56 +00:00
|
|
|
|
2021-01-17 21:29:08 +00:00
|
|
|
// GenerateRandomBytes generates the secret to use for JWT auth
|
|
|
|
func GenerateRandomBytes(length int) []byte {
|
|
|
|
b := make([]byte, length)
|
|
|
|
_, err := io.ReadFull(rand.Reader, b)
|
2021-05-25 06:36:01 +00:00
|
|
|
if err == nil {
|
2021-01-17 21:29:08 +00:00
|
|
|
return b
|
|
|
|
}
|
|
|
|
|
|
|
|
b = xid.New().Bytes()
|
|
|
|
for len(b) < length {
|
|
|
|
b = append(b, xid.New().Bytes()...)
|
|
|
|
}
|
|
|
|
|
|
|
|
return b[:length]
|
|
|
|
}
|
|
|
|
|
2021-11-06 13:13:20 +00:00
|
|
|
// GenerateUniqueID retuens an unique ID
|
|
|
|
func GenerateUniqueID() string {
|
|
|
|
u, err := uuid.NewRandom()
|
|
|
|
if err != nil {
|
|
|
|
return xid.New().String()
|
|
|
|
}
|
|
|
|
return shortuuid.DefaultEncoder.Encode(u)
|
|
|
|
}
|
|
|
|
|
2020-12-29 18:02:56 +00:00
|
|
|
// HTTPListenAndServe is a wrapper for ListenAndServe that support both tcp
|
|
|
|
// and Unix-domain sockets
|
2021-01-03 08:51:54 +00:00
|
|
|
func HTTPListenAndServe(srv *http.Server, address string, port int, isTLS bool, logSender string) error {
|
2020-12-29 18:02:56 +00:00
|
|
|
var listener net.Listener
|
|
|
|
var err error
|
|
|
|
|
2021-03-21 21:21:04 +00:00
|
|
|
if filepath.IsAbs(address) && runtime.GOOS != osWindows {
|
2020-12-29 18:02:56 +00:00
|
|
|
if !IsFileInputValid(address) {
|
|
|
|
return fmt.Errorf("invalid socket address %#v", address)
|
|
|
|
}
|
|
|
|
err = createDirPathIfMissing(address, os.ModePerm)
|
|
|
|
if err != nil {
|
|
|
|
logger.ErrorToConsole("error creating Unix-domain socket parent dir: %v", err)
|
|
|
|
logger.Error(logSender, "", "error creating Unix-domain socket parent dir: %v", err)
|
|
|
|
}
|
|
|
|
os.Remove(address)
|
2021-05-07 18:41:20 +00:00
|
|
|
listener, err = newListener("unix", address, srv.ReadTimeout, srv.WriteTimeout)
|
2020-12-29 18:02:56 +00:00
|
|
|
} else {
|
2021-03-21 21:21:04 +00:00
|
|
|
CheckTCP4Port(port)
|
2021-05-07 18:41:20 +00:00
|
|
|
listener, err = newListener("tcp", fmt.Sprintf("%s:%d", address, port), srv.ReadTimeout, srv.WriteTimeout)
|
2020-12-29 18:02:56 +00:00
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-01-03 08:51:54 +00:00
|
|
|
logger.Info(logSender, "", "server listener registered, address: %v TLS enabled: %v", listener.Addr().String(), isTLS)
|
|
|
|
|
2020-12-29 18:02:56 +00:00
|
|
|
defer listener.Close()
|
|
|
|
|
|
|
|
if isTLS {
|
|
|
|
return srv.ServeTLS(listener, "", "")
|
|
|
|
}
|
|
|
|
return srv.Serve(listener)
|
|
|
|
}
|
2021-02-18 19:17:16 +00:00
|
|
|
|
|
|
|
// GetTLSCiphersFromNames returns the TLS ciphers from the specified names
|
|
|
|
func GetTLSCiphersFromNames(cipherNames []string) []uint16 {
|
|
|
|
var ciphers []uint16
|
|
|
|
|
|
|
|
for _, name := range RemoveDuplicates(cipherNames) {
|
|
|
|
for _, c := range tls.CipherSuites() {
|
|
|
|
if c.Name == strings.TrimSpace(name) {
|
|
|
|
ciphers = append(ciphers, c.ID)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ciphers
|
|
|
|
}
|
2021-02-28 11:10:40 +00:00
|
|
|
|
|
|
|
// EncodeTLSCertToPem returns the specified certificate PEM encoded.
|
|
|
|
// This can be verified using openssl x509 -in cert.crt -text -noout
|
|
|
|
func EncodeTLSCertToPem(tlsCert *x509.Certificate) (string, error) {
|
|
|
|
if len(tlsCert.Raw) == 0 {
|
2021-03-21 21:21:04 +00:00
|
|
|
return "", errors.New("invalid x509 certificate, no der contents")
|
2021-02-28 11:10:40 +00:00
|
|
|
}
|
|
|
|
publicKeyBlock := pem.Block{
|
|
|
|
Type: "CERTIFICATE",
|
|
|
|
Bytes: tlsCert.Raw,
|
|
|
|
}
|
|
|
|
return string(pem.EncodeToMemory(&publicKeyBlock)), nil
|
|
|
|
}
|
2021-03-21 21:21:04 +00:00
|
|
|
|
2021-04-01 16:53:48 +00:00
|
|
|
// CheckTCP4Port quits the app if bind on the given IPv4 port fails.
|
2021-03-21 21:21:04 +00:00
|
|
|
// This is a ugly hack to avoid to bind on an already used port.
|
2021-04-01 16:53:48 +00:00
|
|
|
// It is required on Windows only. Upstream does not consider this
|
|
|
|
// behaviour a bug:
|
2021-03-21 21:21:04 +00:00
|
|
|
// https://github.com/golang/go/issues/45150
|
|
|
|
func CheckTCP4Port(port int) {
|
|
|
|
if runtime.GOOS != osWindows {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
listener, err := net.Listen("tcp4", fmt.Sprintf(":%d", port))
|
|
|
|
if err != nil {
|
2021-04-01 16:53:48 +00:00
|
|
|
logger.ErrorToConsole("unable to bind on tcp4 address: %v", err)
|
|
|
|
logger.Error(logSender, "", "unable to bind on tcp4 address: %v", err)
|
2021-03-21 21:21:04 +00:00
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
listener.Close()
|
|
|
|
}
|
2021-03-26 14:19:01 +00:00
|
|
|
|
|
|
|
// IsByteArrayEmpty return true if the byte array is empty or a new line
|
|
|
|
func IsByteArrayEmpty(b []byte) bool {
|
|
|
|
if len(b) == 0 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if bytes.Equal(b, []byte("\n")) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if bytes.Equal(b, []byte("\r\n")) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetSSHPublicKeyAsString returns an SSH public key serialized as string
|
|
|
|
func GetSSHPublicKeyAsString(pubKey []byte) (string, error) {
|
|
|
|
if len(pubKey) == 0 {
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
k, err := ssh.ParsePublicKey(pubKey)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return string(ssh.MarshalAuthorizedKey(k)), nil
|
|
|
|
}
|
2021-05-11 04:54:06 +00:00
|
|
|
|
|
|
|
// GetRealIP returns the ip address as result of parsing either the
|
|
|
|
// X-Real-IP header or the X-Forwarded-For header
|
|
|
|
func GetRealIP(r *http.Request) string {
|
|
|
|
var ip string
|
|
|
|
|
2021-11-19 21:44:50 +00:00
|
|
|
if clientIP := r.Header.Get(trueClientIP); clientIP != "" {
|
2021-05-30 21:07:46 +00:00
|
|
|
ip = clientIP
|
2021-11-19 21:44:50 +00:00
|
|
|
} else if xrip := r.Header.Get(xRealIP); xrip != "" {
|
|
|
|
ip = xrip
|
2021-05-30 21:07:46 +00:00
|
|
|
} else if clientIP := r.Header.Get(cfConnectingIP); clientIP != "" {
|
|
|
|
ip = clientIP
|
2021-05-11 04:54:06 +00:00
|
|
|
} else if xff := r.Header.Get(xForwardedFor); xff != "" {
|
2021-12-10 17:43:26 +00:00
|
|
|
i := strings.Index(xff, ",")
|
2021-05-11 04:54:06 +00:00
|
|
|
if i == -1 {
|
|
|
|
i = len(xff)
|
|
|
|
}
|
|
|
|
ip = strings.TrimSpace(xff[:i])
|
|
|
|
}
|
|
|
|
if net.ParseIP(ip) == nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
return ip
|
|
|
|
}
|
|
|
|
|
2021-07-24 18:11:17 +00:00
|
|
|
// GetHTTPLocalAddress returns the local address for an http.Request
|
|
|
|
// or empty if it cannot be determined
|
|
|
|
func GetHTTPLocalAddress(r *http.Request) string {
|
|
|
|
if r == nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
localAddr, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr)
|
|
|
|
if ok {
|
|
|
|
return localAddr.String()
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2021-10-03 18:50:05 +00:00
|
|
|
// ParseAllowedIPAndRanges returns a list of functions that allow to find if an
|
|
|
|
// IP is equal or is contained within the allowed list
|
2021-05-11 04:54:06 +00:00
|
|
|
func ParseAllowedIPAndRanges(allowed []string) ([]func(net.IP) bool, error) {
|
|
|
|
res := make([]func(net.IP) bool, len(allowed))
|
|
|
|
for i, allowFrom := range allowed {
|
|
|
|
if strings.LastIndex(allowFrom, "/") > 0 {
|
|
|
|
_, ipRange, err := net.ParseCIDR(allowFrom)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("given string %q is not a valid IP range: %v", allowFrom, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
res[i] = ipRange.Contains
|
|
|
|
} else {
|
|
|
|
allowed := net.ParseIP(allowFrom)
|
|
|
|
if allowed == nil {
|
|
|
|
return nil, fmt.Errorf("given string %q is not a valid IP address", allowFrom)
|
|
|
|
}
|
|
|
|
|
|
|
|
res[i] = allowed.Equal
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return res, nil
|
|
|
|
}
|
2021-05-12 20:44:17 +00:00
|
|
|
|
|
|
|
// GetRedactedURL returns the url redacting the password if any
|
|
|
|
func GetRedactedURL(rawurl string) string {
|
2021-10-03 13:17:49 +00:00
|
|
|
if !strings.HasPrefix(rawurl, "http") {
|
|
|
|
return rawurl
|
|
|
|
}
|
2021-05-12 20:44:17 +00:00
|
|
|
u, err := url.Parse(rawurl)
|
|
|
|
if err != nil {
|
|
|
|
return rawurl
|
|
|
|
}
|
|
|
|
return u.Redacted()
|
|
|
|
}
|
2021-07-31 07:42:23 +00:00
|
|
|
|
|
|
|
// PrependFileInfo prepends a file info to a slice in an efficient way.
|
|
|
|
// We, optimistically, assume that the slice has enough capacity
|
|
|
|
func PrependFileInfo(files []os.FileInfo, info os.FileInfo) []os.FileInfo {
|
|
|
|
files = append(files, nil)
|
|
|
|
copy(files[1:], files)
|
|
|
|
files[0] = info
|
|
|
|
return files
|
|
|
|
}
|