freifunkmanager/ssh/manager.go

65 lines
1.5 KiB
Go
Raw Normal View History

2017-05-06 14:37:24 +02:00
package ssh
import (
"errors"
2017-05-06 14:37:24 +02:00
"net"
2017-05-14 10:04:45 +02:00
"strings"
2017-05-06 14:37:24 +02:00
"sync"
2017-05-14 10:04:45 +02:00
"time"
2017-05-06 14:37:24 +02:00
2018-06-30 01:45:51 +02:00
log "github.com/sirupsen/logrus"
2017-05-06 14:37:24 +02:00
"golang.org/x/crypto/ssh"
)
// the SSH Connection Manager for multiple connections
type Manager struct {
2017-05-14 10:04:45 +02:00
config *ssh.ClientConfig
clientsBlacklist map[string]time.Time
clientsMUX sync.Mutex
2017-05-06 14:37:24 +02:00
}
// create a new SSH Connection Manager by ssh file
func NewManager(file string) *Manager {
var auths []ssh.AuthMethod
if auth := SSHAgent(); auth != nil {
auths = append(auths, auth)
}
if auth := PublicKeyFile(file); auth != nil {
auths = append(auths, auth)
}
sshConfig := &ssh.ClientConfig{
User: "root",
Auth: auths,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
return &Manager{
2017-05-14 10:04:45 +02:00
config: sshConfig,
clientsBlacklist: make(map[string]time.Time),
2017-05-06 14:37:24 +02:00
}
}
func (m *Manager) ConnectTo(addr net.TCPAddr) (*ssh.Client, error) {
2017-05-06 14:37:24 +02:00
m.clientsMUX.Lock()
defer m.clientsMUX.Unlock()
2017-05-14 10:04:45 +02:00
if t, ok := m.clientsBlacklist[addr.IP.String()]; ok {
2017-05-16 00:22:15 +02:00
if time.Now().Add(-time.Hour * 24).Before(t) {
return nil, errors.New("node on blacklist")
2017-05-14 10:04:45 +02:00
} else {
delete(m.clientsBlacklist, addr.IP.String())
}
}
2017-05-06 14:37:24 +02:00
client, err := ssh.Dial("tcp", addr.String(), m.config)
if err != nil {
2017-05-14 10:04:45 +02:00
if strings.Contains(err.Error(), "no supported methods remain") {
m.clientsBlacklist[addr.IP.String()] = time.Now()
2018-06-30 01:45:51 +02:00
log.Warnf("node was set on the blacklist: %s", err)
return nil, errors.New("node on blacklist")
2017-05-14 10:04:45 +02:00
}
return nil, err
2017-05-06 14:37:24 +02:00
}
return client, nil
2017-05-06 14:37:24 +02:00
}