Commit 2be75889 authored by ibuler's avatar ibuler

[Update] 修改结构

parent 21379f76
...@@ -12,7 +12,7 @@ type contextKey struct { ...@@ -12,7 +12,7 @@ type contextKey struct {
} }
var ( var (
ContextKeyUser = &contextKey{"User"} ContextKeyUser = &contextKey{"user"}
ContextKeyAsset = &contextKey{"asset"} ContextKeyAsset = &contextKey{"asset"}
ContextKeySystemUser = &contextKey{"systemUser"} ContextKeySystemUser = &contextKey{"systemUser"}
ContextKeySSHSession = &contextKey{"sshSession"} ContextKeySSHSession = &contextKey{"sshSession"}
...@@ -35,7 +35,7 @@ type CocoContext struct { ...@@ -35,7 +35,7 @@ type CocoContext struct {
context.Context context.Context
} }
// User 返回当前连接的用户model // user 返回当前连接的用户model
func (ctx *CocoContext) User() *model.User { func (ctx *CocoContext) User() *model.User {
return ctx.Value(ContextKeyUser).(*model.User) return ctx.Value(ContextKeyUser).(*model.User)
} }
......
...@@ -117,7 +117,7 @@ func (c *Client) SetReqHeaders(req *http.Request, params ...map[string]string) { ...@@ -117,7 +117,7 @@ func (c *Client) SetReqHeaders(req *http.Request, params ...map[string]string) {
if req.Header.Get("Content-Type") == "" { if req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
} }
req.Header.Set("User-Agent", "coco-client") req.Header.Set("user-Agent", "coco-client")
c.SetAuthHeader(req) c.SetAuthHeader(req)
} }
......
...@@ -38,7 +38,7 @@ func TestClient_Do(t *testing.T) { ...@@ -38,7 +38,7 @@ func TestClient_Do(t *testing.T) {
t.Errorf("Failed Do() error: %s", err.Error()) t.Errorf("Failed Do() error: %s", err.Error())
} }
if len(res) != 2 { if len(res) != 2 {
t.Errorf("User not equal 2: %d", len(res)) t.Errorf("user not equal 2: %d", len(res))
} }
} }
......
...@@ -97,7 +97,7 @@ func (i *InteractiveHandler) Dispatch(ctx cctx.Context) { ...@@ -97,7 +97,7 @@ func (i *InteractiveHandler) Dispatch(ctx cctx.Context) {
if err != nil { if err != nil {
if err != io.EOF { if err != io.EOF {
logger.Debug("User disconnected") logger.Debug("user disconnected")
} else { } else {
logger.Error("Read from user err: ", err) logger.Error("Read from user err: ", err)
} }
...@@ -342,10 +342,10 @@ func (i *InteractiveHandler) Proxy(ctx context.Context) { ...@@ -342,10 +342,10 @@ func (i *InteractiveHandler) Proxy(ctx context.Context) {
// serverAuth := transport.ServerAuth{ // serverAuth := transport.ServerAuth{
// SessionID: uuid.NewV4().String(), // SessionID: uuid.NewV4().String(),
// IP: asset.Ip, // IP: asset.Ip,
// Port: asset.Port, // port: asset.port,
// UserName: systemUser.UserName, // UserName: systemUser.UserName,
// Password: systemUser.Password, // password: systemUser.password,
// PublicKey: parsePrivateKey(systemUser.PrivateKey)} // PublicKey: parsePrivateKey(systemUser.privateKey)}
// //
// nodeConn, err := transport.NewNodeConn(i.sess.Context(), serverAuth, ptyReq, winChan) // nodeConn, err := transport.NewNodeConn(i.sess.Context(), serverAuth, ptyReq, winChan)
// if err != nil { // if err != nil {
......
...@@ -49,11 +49,11 @@ func (p *ProxyServer) Proxy() { ...@@ -49,11 +49,11 @@ func (p *ProxyServer) Proxy() {
if !p.checkProtocol() { if !p.checkProtocol() {
return return
} }
conn := SSHConnection{ conn := ServerSSHConnection{
Host: "192.168.244.185", host: "192.168.244.185",
Port: "22", port: "22",
User: "root", user: "root",
Password: "redhat", password: "redhat",
} }
ptyReq, _, ok := p.Session.Pty() ptyReq, _, ok := p.Session.Pty()
if !ok { if !ok {
...@@ -66,9 +66,9 @@ func (p *ProxyServer) Proxy() { ...@@ -66,9 +66,9 @@ func (p *ProxyServer) Proxy() {
} }
sw := Switch{ sw := Switch{
userSession: p.Session, userConn: p.Session,
serverConn: &conn, serverConn: &conn,
parser: parser, parser: parser,
} }
_ = sw.Bridge() _ = sw.Bridge()
_ = conn.Close() _ = conn.Close()
......
...@@ -11,20 +11,26 @@ import ( ...@@ -11,20 +11,26 @@ import (
type ServerConnection interface { type ServerConnection interface {
io.ReadWriteCloser io.ReadWriteCloser
Name() string
Host() string
Port() string
User() string
Timeout() time.Duration
Protocol() string Protocol() string
Connect(h, w int, term string) error Connect(h, w int, term string) error
SetWinSize(w, h int) error SetWinSize(w, h int) error
} }
type SSHConnection struct { type ServerSSHConnection struct {
Host string name string
Port string host string
User string port string
Password string user string
PrivateKey string password string
PrivateKeyPath string privateKey string
Timeout time.Duration privateKeyPath string
Proxy *SSHConnection timeout time.Duration
Proxy *ServerSSHConnection
client *gossh.Client client *gossh.Client
Session *gossh.Session Session *gossh.Session
...@@ -34,25 +40,49 @@ type SSHConnection struct { ...@@ -34,25 +40,49 @@ type SSHConnection struct {
closed bool closed bool
} }
func (sc *SSHConnection) Protocol() string { func (sc *ServerSSHConnection) Protocol() string {
return "ssh" return "ssh"
} }
func (sc *SSHConnection) Config() (config *gossh.ClientConfig, err error) { func (sc *ServerSSHConnection) User() string {
return sc.user
}
func (sc *ServerSSHConnection) Host() string {
return sc.host
}
func (sc *ServerSSHConnection) Name() string {
return sc.name
}
func (sc *ServerSSHConnection) Port() string {
return sc.port
}
func (sc *ServerSSHConnection) Timeout() time.Duration {
return sc.timeout
}
func (sc *ServerSSHConnection) String() string {
return fmt.Sprintf("%s@%s:%s", sc.user, sc.host, sc.port)
}
func (sc *ServerSSHConnection) Config() (config *gossh.ClientConfig, err error) {
authMethods := make([]gossh.AuthMethod, 0) authMethods := make([]gossh.AuthMethod, 0)
if sc.Password != "" { if sc.password != "" {
authMethods = append(authMethods, gossh.Password(sc.Password)) authMethods = append(authMethods, gossh.Password(sc.password))
} }
if sc.PrivateKeyPath != "" { if sc.privateKeyPath != "" {
if pubkey, err := GetPubKeyFromFile(sc.PrivateKeyPath); err != nil { if pubkey, err := GetPubKeyFromFile(sc.privateKeyPath); err != nil {
err = fmt.Errorf("parse private key from file error: %sc", err) err = fmt.Errorf("parse private key from file error: %sc", err)
return config, err return config, err
} else { } else {
authMethods = append(authMethods, gossh.PublicKeys(pubkey)) authMethods = append(authMethods, gossh.PublicKeys(pubkey))
} }
} }
if sc.PrivateKey != "" { if sc.privateKey != "" {
if signer, err := gossh.ParsePrivateKey([]byte(sc.PrivateKey)); err != nil { if signer, err := gossh.ParsePrivateKey([]byte(sc.privateKey)); err != nil {
err = fmt.Errorf("parse private key error: %sc", err) err = fmt.Errorf("parse private key error: %sc", err)
return config, err return config, err
} else { } else {
...@@ -60,15 +90,15 @@ func (sc *SSHConnection) Config() (config *gossh.ClientConfig, err error) { ...@@ -60,15 +90,15 @@ func (sc *SSHConnection) Config() (config *gossh.ClientConfig, err error) {
} }
} }
config = &gossh.ClientConfig{ config = &gossh.ClientConfig{
User: sc.User, User: sc.user,
Auth: authMethods, Auth: authMethods,
HostKeyCallback: gossh.InsecureIgnoreHostKey(), HostKeyCallback: gossh.InsecureIgnoreHostKey(),
Timeout: sc.Timeout, Timeout: sc.timeout,
} }
return config, nil return config, nil
} }
func (sc *SSHConnection) connect() (client *gossh.Client, err error) { func (sc *ServerSSHConnection) connect() (client *gossh.Client, err error) {
config, err := sc.Config() config, err := sc.Config()
if err != nil { if err != nil {
return return
...@@ -78,20 +108,20 @@ func (sc *SSHConnection) connect() (client *gossh.Client, err error) { ...@@ -78,20 +108,20 @@ func (sc *SSHConnection) connect() (client *gossh.Client, err error) {
if err != nil { if err != nil {
return client, err return client, err
} }
proxySock, err := proxyClient.Dial("tcp", net.JoinHostPort(sc.Host, sc.Port)) proxySock, err := proxyClient.Dial("tcp", net.JoinHostPort(sc.host, sc.port))
if err != nil { if err != nil {
return client, err return client, err
} }
proxyConn, chans, reqs, err := gossh.NewClientConn(proxySock, net.JoinHostPort(sc.Host, sc.Port), config) proxyConn, chans, reqs, err := gossh.NewClientConn(proxySock, net.JoinHostPort(sc.host, sc.port), config)
if err != nil { if err != nil {
return client, err return client, err
} }
sc.proxyConn = proxyConn sc.proxyConn = proxyConn
client = gossh.NewClient(proxyConn, chans, reqs) client = gossh.NewClient(proxyConn, chans, reqs)
} else { } else {
client, err = gossh.Dial("tcp", net.JoinHostPort(sc.Host, sc.Port), config) client, err = gossh.Dial("tcp", net.JoinHostPort(sc.host, sc.port), config)
if err != nil { if err != nil {
err = fmt.Errorf("connect host %sc error: %sc", sc.Host, err) err = fmt.Errorf("connect host %sc error: %sc", sc.host, err)
return return
} }
} }
...@@ -99,7 +129,7 @@ func (sc *SSHConnection) connect() (client *gossh.Client, err error) { ...@@ -99,7 +129,7 @@ func (sc *SSHConnection) connect() (client *gossh.Client, err error) {
return client, nil return client, nil
} }
func (sc *SSHConnection) invokeShell(h, w int, term string) (err error) { func (sc *ServerSSHConnection) invokeShell(h, w int, term string) (err error) {
sess, err := sc.client.NewSession() sess, err := sc.client.NewSession()
if err != nil { if err != nil {
return return
...@@ -126,7 +156,7 @@ func (sc *SSHConnection) invokeShell(h, w int, term string) (err error) { ...@@ -126,7 +156,7 @@ func (sc *SSHConnection) invokeShell(h, w int, term string) (err error) {
return err return err
} }
func (sc *SSHConnection) Connect(h, w int, term string) (err error) { func (sc *ServerSSHConnection) Connect(h, w int, term string) (err error) {
_, err = sc.connect() _, err = sc.connect()
if err != nil { if err != nil {
return return
...@@ -138,19 +168,19 @@ func (sc *SSHConnection) Connect(h, w int, term string) (err error) { ...@@ -138,19 +168,19 @@ func (sc *SSHConnection) Connect(h, w int, term string) (err error) {
return nil return nil
} }
func (sc *SSHConnection) SetWinSize(h, w int) error { func (sc *ServerSSHConnection) SetWinSize(h, w int) error {
return sc.Session.WindowChange(h, w) return sc.Session.WindowChange(h, w)
} }
func (sc *SSHConnection) Read(p []byte) (n int, err error) { func (sc *ServerSSHConnection) Read(p []byte) (n int, err error) {
return sc.stdout.Read(p) return sc.stdout.Read(p)
} }
func (sc *SSHConnection) Write(p []byte) (n int, err error) { func (sc *ServerSSHConnection) Write(p []byte) (n int, err error) {
return sc.stdin.Write(p) return sc.stdin.Write(p)
} }
func (sc *SSHConnection) Close() (err error) { func (sc *ServerSSHConnection) Close() (err error) {
if sc.closed { if sc.closed {
return return
} }
......
...@@ -5,12 +5,12 @@ import ( ...@@ -5,12 +5,12 @@ import (
"testing" "testing"
) )
var testConnection = SSHConnection{ var testConnection = ServerSSHConnection{
Host: "127.0.0.1", host: "127.0.0.1",
Port: "22", port: "22",
User: "root", user: "root",
Password: "redhat", password: "redhat",
Proxy: &SSHConnection{Host: "192.168.244.185", Port: "22", User: "root", Password: "redhat"}, Proxy: &ServerSSHConnection{host: "192.168.244.185", port: "22", user: "root", password: "redhat"},
} }
func TestSSHConnection_Config(t *testing.T) { func TestSSHConnection_Config(t *testing.T) {
......
package proxy package proxy
import ( import (
"cocogo/pkg/logger"
"cocogo/pkg/service" "cocogo/pkg/service"
"context" "context"
"github.com/ibuler/ssh" "github.com/ibuler/ssh"
"github.com/satori/go.uuid" "github.com/satori/go.uuid"
"time" "time"
"cocogo/pkg/logger"
) )
func NewSwitch(userSess ssh.Session, serverConn ServerConnection) (sw *Switch) { func NewSwitch(userConn UserConnection, serverConn ServerConnection) (sw *Switch) {
rules, err := service.GetSystemUserFilterRules("") rules, err := service.GetSystemUserFilterRules("")
if err != nil { if err != nil {
logger.Error("Get system user filter rule error: ", err) logger.Error("Get system user filter rule error: ", err)
...@@ -19,14 +18,14 @@ func NewSwitch(userSess ssh.Session, serverConn ServerConnection) (sw *Switch) { ...@@ -19,14 +18,14 @@ func NewSwitch(userSess ssh.Session, serverConn ServerConnection) (sw *Switch) {
cmdFilterRules: rules, cmdFilterRules: rules,
} }
parser.Initial() parser.Initial()
sw = &Switch{userSession: userSess, serverConn: serverConn, parser: parser} sw = &Switch{userConn: userConn, serverConn: serverConn, parser: parser}
return sw return sw
} }
type SwitchInfo struct { type Switch struct {
Id string `json:"id"` Id string
User string `json:"user"` User string `json:"user"`
Asset string `json:"asset"` Server string `json:"asset"`
SystemUser string `json:"system_user"` SystemUser string `json:"system_user"`
Org string `json:"org_id"` Org string `json:"org_id"`
LoginFrom string `json:"login_from"` LoginFrom string `json:"login_from"`
...@@ -36,20 +35,23 @@ type SwitchInfo struct { ...@@ -36,20 +35,23 @@ type SwitchInfo struct {
DateActive time.Time `json:"date_last_active"` DateActive time.Time `json:"date_last_active"`
Finished bool `json:"is_finished"` Finished bool `json:"is_finished"`
Closed bool Closed bool
}
type Switch struct { parser *Parser
Info *SwitchInfo userConn UserConnection
parser *Parser serverConn ServerConnection
userSession ssh.Session userTran Transport
serverConn ServerConnection serverTran Transport
userTran Transport cancelFunc context.CancelFunc
serverTran Transport
cancelFunc context.CancelFunc
} }
func (s *Switch) Initial() { func (s *Switch) Initial() {
s.Id = uuid.NewV4().String() s.Id = uuid.NewV4().String()
s.User = s.userConn.User()
s.Server = s.serverConn.Name()
s.SystemUser = s.serverConn.User()
s.LoginFrom = s.userConn.LoginFrom()
s.RemoteAddr = s.userConn.RemoteAddr()
s.DateStart = time.Now()
} }
func (s *Switch) preBridge() { func (s *Switch) preBridge() {
...@@ -128,11 +130,11 @@ func (s *Switch) readServerToUser(ctx context.Context) { ...@@ -128,11 +130,11 @@ func (s *Switch) readServerToUser(ctx context.Context) {
} }
func (s *Switch) Bridge() (err error) { func (s *Switch) Bridge() (err error) {
_, winCh, _ := s.userSession.Pty() winCh := s.userConn.WinCh()
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
s.cancelFunc = cancel s.cancelFunc = cancel
s.userTran = NewDirectTransport("", s.userSession) s.userTran = NewDirectTransport("", s.userConn)
s.serverTran = NewDirectTransport("", s.serverConn) s.serverTran = NewDirectTransport("", s.serverConn)
go s.watchWindowChange(ctx, winCh) go s.watchWindowChange(ctx, winCh)
go s.readServerToUser(ctx) go s.readServerToUser(ctx)
......
package proxy
import (
"io"
"strings"
"github.com/ibuler/ssh"
)
type UserConnection interface {
io.ReadWriteCloser
Protocol() string
WinCh() <-chan ssh.Window
User() string
Name() string
LoginFrom() string
RemoteAddr() string
}
type SSHUserConnection struct {
ssh.Session
winch <-chan ssh.Window
}
func (uc *SSHUserConnection) Protocol() string {
return "ssh"
}
func (uc *SSHUserConnection) User() string {
return uc.Session.User()
}
func (uc *SSHUserConnection) WinCh() (winch <-chan ssh.Window) {
_, winch, ok := uc.Pty()
if ok {
return
}
return nil
}
func (uc *SSHUserConnection) LoginFrom() string {
return "T"
}
func (uc *SSHUserConnection) RemoteAddr() string {
return strings.Split(uc.Session.RemoteAddr().String(), ":")[0]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment