2019-01-01 01:39:45 +08:00
|
|
|
package bastion // import "moul.io/sshportal/pkg/bastion"
|
2018-01-18 18:20:37 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/binary"
|
2018-11-16 22:44:29 +08:00
|
|
|
"errors"
|
2018-01-18 18:20:37 +08:00
|
|
|
"io"
|
2018-11-16 22:44:29 +08:00
|
|
|
"log"
|
2018-01-18 18:20:37 +08:00
|
|
|
"syscall"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"golang.org/x/crypto/ssh"
|
|
|
|
)
|
|
|
|
|
|
|
|
type logTunnel struct {
|
|
|
|
host string
|
|
|
|
channel ssh.Channel
|
|
|
|
writer io.WriteCloser
|
|
|
|
}
|
|
|
|
|
2019-01-01 01:39:45 +08:00
|
|
|
type logTunnelForwardData struct {
|
2018-01-18 18:20:37 +08:00
|
|
|
DestinationHost string
|
|
|
|
DestinationPort uint32
|
2018-11-16 22:36:14 +08:00
|
|
|
SourceHost string
|
|
|
|
SourcePort uint32
|
2018-01-18 18:20:37 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func writeHeader(fd io.Writer, length int) {
|
|
|
|
t := time.Now()
|
|
|
|
|
|
|
|
tv := syscall.NsecToTimeval(t.UnixNano())
|
|
|
|
|
2018-11-16 22:44:29 +08:00
|
|
|
if err := binary.Write(fd, binary.LittleEndian, int32(tv.Sec)); err != nil {
|
|
|
|
log.Printf("failed to write log header: %v", err)
|
|
|
|
}
|
|
|
|
if err := binary.Write(fd, binary.LittleEndian, tv.Usec); err != nil {
|
|
|
|
log.Printf("failed to write log header: %v", err)
|
|
|
|
}
|
|
|
|
if err := binary.Write(fd, binary.LittleEndian, int32(length)); err != nil {
|
|
|
|
log.Printf("failed to write log header: %v", err)
|
|
|
|
}
|
2018-01-18 18:20:37 +08:00
|
|
|
}
|
|
|
|
|
2019-01-01 01:39:45 +08:00
|
|
|
func newLogTunnel(channel ssh.Channel, writer io.WriteCloser, host string) io.ReadWriteCloser {
|
2018-01-18 18:20:37 +08:00
|
|
|
return &logTunnel{
|
2018-11-16 22:36:14 +08:00
|
|
|
host: host,
|
2018-01-18 18:20:37 +08:00
|
|
|
channel: channel,
|
|
|
|
writer: writer,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *logTunnel) Read(data []byte) (int, error) {
|
2018-11-16 22:44:29 +08:00
|
|
|
return 0, errors.New("logTunnel.Read is not implemented")
|
2018-01-18 18:20:37 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (l *logTunnel) Write(data []byte) (int, error) {
|
2018-11-16 22:36:14 +08:00
|
|
|
writeHeader(l.writer, len(data)+len(l.host+": "))
|
2018-11-16 22:44:29 +08:00
|
|
|
if _, err := l.writer.Write([]byte(l.host + ": ")); err != nil {
|
|
|
|
log.Printf("failed to write log: %v", err)
|
|
|
|
}
|
|
|
|
if _, err := l.writer.Write(data); err != nil {
|
|
|
|
log.Printf("failed to write log: %v", err)
|
|
|
|
}
|
2018-01-18 18:20:37 +08:00
|
|
|
|
|
|
|
return l.channel.Write(data)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *logTunnel) Close() error {
|
|
|
|
l.writer.Close()
|
|
|
|
|
|
|
|
return l.channel.Close()
|
|
|
|
}
|