Refactor SessionManager
This commit is contained in:
parent
cbe259b1ee
commit
2f4bdbb679
19
README.md
19
README.md
|
@ -1,7 +1,8 @@
|
|||
# yubihsm-go
|
||||
Yubihsm-go is a minimal implementation of the securechannel and connector protocol of the YubiHSM2.
|
||||
|
||||
It also implements a simple SessionManager which can pool connections.
|
||||
It also implements a simple SessionManager which keeps connections alive and swaps them if the maximum number of
|
||||
messages is depleted.
|
||||
|
||||
Currently the following commands are implemented:
|
||||
|
||||
|
@ -26,18 +27,6 @@ if err != nil {
|
|||
panic(err)
|
||||
}
|
||||
|
||||
select {
|
||||
case <-sm.Connected:
|
||||
println("connected and authed")
|
||||
case <-time.After(5 * time.Second):
|
||||
panic(errors.New("connection/authentication with the HSM timed out; look at aiakos logs for more info"))
|
||||
}
|
||||
|
||||
session, err := sm.GetSession()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
echoMessage := []byte("test")
|
||||
|
||||
command, err := commands.CreateEchoCommand(echoMessage)
|
||||
|
@ -45,7 +34,7 @@ if err != nil {
|
|||
panic(err)
|
||||
}
|
||||
|
||||
resp, err := session.SendEncryptedCommand(command)
|
||||
resp, err := sm.SendEncryptedCommand(command)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
@ -61,4 +50,4 @@ if bytes.Equal(parsedResp.Data, echoMessage) {
|
|||
panic(errors.New("echoed message did not equal requested message"))
|
||||
}
|
||||
|
||||
```
|
||||
```
|
||||
|
|
180
manager.go
180
manager.go
|
@ -3,11 +3,9 @@ package yubihsm
|
|||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/certusone/yubihsm-go/commands"
|
||||
"github.com/certusone/yubihsm-go/connector"
|
||||
"github.com/certusone/yubihsm-go/securechannel"
|
||||
"math/rand"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
@ -15,117 +13,73 @@ import (
|
|||
type (
|
||||
// SessionManager manages a pool of authenticated secure sessions with a YubiHSM2
|
||||
SessionManager struct {
|
||||
sessions sessionList
|
||||
session *securechannel.SecureChannel
|
||||
lock sync.Mutex
|
||||
connector connector.Connector
|
||||
authKeyID uint16
|
||||
password string
|
||||
|
||||
poolSize uint
|
||||
|
||||
creationWait sync.WaitGroup
|
||||
destroyed bool
|
||||
|
||||
// Connected indicates whether a successful connection with the HSM is established
|
||||
Connected chan bool
|
||||
recycleQueue chan *securechannel.SecureChannel
|
||||
keepAlive *time.Timer
|
||||
swapping bool
|
||||
}
|
||||
|
||||
sessionList []*securechannel.SecureChannel
|
||||
)
|
||||
|
||||
var (
|
||||
echoPayload = []byte("keepalive")
|
||||
)
|
||||
|
||||
const (
|
||||
pingInterval = 15 * time.Second
|
||||
)
|
||||
|
||||
// NewSessionManager creates a new instance of the SessionManager with poolSize connections.
|
||||
// Wait on channel Connected with a timeout to wait for active connections to be ready.
|
||||
func NewSessionManager(connector connector.Connector, authKeyID uint16, password string, poolSize uint) (*SessionManager, error) {
|
||||
if poolSize > 16 {
|
||||
return nil, errors.New("pool size exceeds session limit")
|
||||
}
|
||||
|
||||
func NewSessionManager(connector connector.Connector, authKeyID uint16, password string) (*SessionManager, error) {
|
||||
manager := &SessionManager{
|
||||
sessions: make([]*securechannel.SecureChannel, 0),
|
||||
connector: connector,
|
||||
authKeyID: authKeyID,
|
||||
password: password,
|
||||
poolSize: poolSize,
|
||||
destroyed: false,
|
||||
Connected: make(chan bool, 1),
|
||||
recycleQueue: make(chan *securechannel.SecureChannel, 20),
|
||||
connector: connector,
|
||||
authKeyID: authKeyID,
|
||||
password: password,
|
||||
destroyed: false,
|
||||
}
|
||||
|
||||
manager.household()
|
||||
err := manager.swapSession()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
manager.household()
|
||||
time.Sleep(15 * time.Second)
|
||||
}
|
||||
}()
|
||||
manager.keepAlive = time.NewTimer(pingInterval)
|
||||
go manager.pingRoutine()
|
||||
|
||||
// Recycler function
|
||||
go func() {
|
||||
for channel := range manager.recycleQueue {
|
||||
func() {
|
||||
manager.lock.Lock()
|
||||
defer manager.lock.Unlock()
|
||||
|
||||
// Remove from list
|
||||
pos := manager.sessions.pos(channel)
|
||||
|
||||
manager.sessions[pos] = manager.sessions[len(manager.sessions)-1]
|
||||
manager.sessions[len(manager.sessions)-1] = nil
|
||||
manager.sessions = manager.sessions[:len(manager.sessions)-1]
|
||||
}()
|
||||
|
||||
channel.Close()
|
||||
err := manager.createSession()
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return manager, nil
|
||||
return manager, err
|
||||
}
|
||||
|
||||
func (s *SessionManager) household() {
|
||||
func() {
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
func (s *SessionManager) pingRoutine() {
|
||||
for range s.keepAlive.C {
|
||||
command, _ := commands.CreateEchoCommand(echoPayload)
|
||||
|
||||
for _, session := range s.sessions {
|
||||
// Send echo command
|
||||
command, _ := commands.CreateEchoCommand(echoPayload)
|
||||
resp, err := session.SendEncryptedCommand(command)
|
||||
if err == nil {
|
||||
parsedResp, matched := resp.(*commands.EchoResponse)
|
||||
if !matched {
|
||||
err = errors.New("invalid response type")
|
||||
}
|
||||
if !bytes.Equal(parsedResp.Data, echoPayload) {
|
||||
err = errors.New("echoed data is invalid")
|
||||
}
|
||||
resp, err := s.SendEncryptedCommand(command)
|
||||
if err == nil {
|
||||
parsedResp, matched := resp.(*commands.EchoResponse)
|
||||
if !matched {
|
||||
err = errors.New("invalid response type")
|
||||
}
|
||||
|
||||
if session.Counter > securechannel.MaxMessagesPerSession*0.9 || err != nil {
|
||||
// Remove expired session
|
||||
s.recycleQueue <- session
|
||||
if !bytes.Equal(parsedResp.Data, echoPayload) {
|
||||
err = errors.New("echoed data is invalid")
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for i := 0; i < int(s.poolSize)-len(s.sessions); i++ {
|
||||
err := s.createSession()
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
}
|
||||
println("pinged")
|
||||
s.keepAlive.Reset(pingInterval)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SessionManager) createSession() error {
|
||||
func (s *SessionManager) swapSession() error {
|
||||
// Lock swapping process
|
||||
s.swapping = true
|
||||
defer func() { s.swapping = false }()
|
||||
|
||||
newSession, err := securechannel.NewSecureChannel(s.connector, s.authKeyID, s.password)
|
||||
if err != nil {
|
||||
return err
|
||||
|
@ -138,28 +92,58 @@ func (s *SessionManager) createSession() error {
|
|||
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
s.sessions = append(s.sessions, newSession)
|
||||
select {
|
||||
case s.Connected <- true:
|
||||
default:
|
||||
// Close old session
|
||||
if s.session != nil {
|
||||
go s.session.Close()
|
||||
}
|
||||
|
||||
// Replace primary session
|
||||
s.session = newSession
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSession returns a secure authenticated session with the HSM from the pool on which commands can be executed
|
||||
func (s *SessionManager) GetSession() (*securechannel.SecureChannel, error) {
|
||||
func (s *SessionManager) checkSessionHealth() {
|
||||
if s.session.Counter >= securechannel.MaxMessagesPerSession*0.9 && !s.swapping {
|
||||
go s.swapSession()
|
||||
}
|
||||
}
|
||||
|
||||
// SendEncryptedCommand sends an encrypted & authenticated command to the HSM
|
||||
// and returns the decrypted and parsed response.
|
||||
func (s *SessionManager) SendEncryptedCommand(c *commands.CommandMessage) (commands.Response, error) {
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
|
||||
// Check session health after executing the command
|
||||
defer s.checkSessionHealth()
|
||||
|
||||
if s.destroyed {
|
||||
return nil, errors.New("sessionmanager has already been destroyed")
|
||||
}
|
||||
if s.session == nil {
|
||||
return nil, errors.New("no session available")
|
||||
}
|
||||
|
||||
// Reset keepalive since we are resetting the timeout by sending a command
|
||||
s.keepAlive.Reset(pingInterval)
|
||||
|
||||
return s.session.SendEncryptedCommand(c)
|
||||
}
|
||||
|
||||
// SendCommand sends an unauthenticated command to the HSM and returns the parsed response
|
||||
func (s *SessionManager) SendCommand(c *commands.CommandMessage) (commands.Response, error) {
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
|
||||
if s.destroyed {
|
||||
return nil, errors.New("sessionmanager has already been destroyed")
|
||||
}
|
||||
if len(s.sessions) == 0 {
|
||||
return nil, errors.New("no sessions available")
|
||||
if s.session == nil {
|
||||
return nil, errors.New("no session available")
|
||||
}
|
||||
|
||||
return s.sessions[rand.Intn(len(s.sessions))], nil
|
||||
return s.session.SendCommand(c)
|
||||
}
|
||||
|
||||
// Destroy closes all connections in the pool.
|
||||
|
@ -168,17 +152,7 @@ func (s *SessionManager) Destroy() {
|
|||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
|
||||
for _, session := range s.sessions {
|
||||
session.Close()
|
||||
}
|
||||
s.keepAlive.Stop()
|
||||
s.session.Close()
|
||||
s.destroyed = true
|
||||
}
|
||||
|
||||
func (slice sessionList) pos(value *securechannel.SecureChannel) int {
|
||||
for p, v := range slice {
|
||||
if v == value {
|
||||
return p
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue