@ -1,23 +1,15 @@
package obfssh
package obfssh
import (
import (
"bufio"
"context"
"errors"
"fmt"
"fmt"
socks "github.com/fangdingjun/socks-go"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
"net"
"net"
"net/http"
"os"
"os"
"os/signal"
"os/signal"
"strings"
"sync"
"syscall"
"syscall"
"time"
"time"
"github.com/fangdingjun/go-log"
socks "github.com/fangdingjun/socks-go"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
)
)
// Client is ssh client connection
// Client is ssh client connection
@ -26,30 +18,43 @@ type Client struct {
sshConn ssh . Conn
sshConn ssh . Conn
client * ssh . Client
client * ssh . Client
listeners [ ] net . Listener
listeners [ ] net . Listener
ch chan struct { }
err error
err error
ctx context . Context
cancel context . CancelFunc
}
}
// NewClient create a new ssh Client
// NewClient create a new ssh Client
//
//
// addr is server address
// addr is server address
//
//
// method is obfs encrypt method, value is rc4, aes or none or ""
//
// key is obfs encrypt key
//
// conf is the client configure
// conf is the client configure
//
//
// if set method to none or "", means disable the obfs,
// when the obfs is disabled, the client can connect to standard ssh server, like OpenSSH server
//
//
func NewClient ( c net . Conn , config * ssh . ClientConfig , addr string , conf * Conf ) ( * Client , error ) {
func NewClient ( c net . Conn , config * ssh . ClientConfig , addr string , conf * Conf ) ( * Client , error ) {
//obfsConn := &TimedOutConn{c, conf.Timeout}
Log ( DEBUG , "create obfs conn with method %s" , conf . ObfsMethod )
sshConn , newch , reqs , err := ssh . NewClientConn ( c , addr , config )
obfsConn , err := NewObfsConn ( & TimedOutConn { c , conf . Timeout } , conf . ObfsMethod , conf . ObfsKey , false )
if err != nil {
return nil , err
}
sshConn , newch , reqs , err := ssh . NewClientConn ( obfsConn , addr , config )
if err != nil {
if err != nil {
return nil , err
return nil , err
}
}
if conf . DisableObfsAfterHandshake {
obfsConn . DisableObfs ( )
}
sshClient := ssh . NewClient ( sshConn , newch , reqs )
sshClient := ssh . NewClient ( sshConn , newch , reqs )
client := & Client {
client := & Client {
conn : c , sshConn : sshConn , client : sshClient ,
conn : c , sshConn : sshConn , client : sshClient ,
ch : make ( chan struct { } ) ,
}
}
client . ctx , client . cancel = context . WithCancel ( context . Background ( ) )
go client . keepAlive ( conf . KeepAliveInterval , conf . KeepAliveMax )
go client . keepAlive ( conf . KeepAliveInterval , conf . KeepAliveMax )
return client , nil
return client , nil
}
}
@ -61,75 +66,50 @@ func (cc *Client) Client() *ssh.Client {
// Run wait ssh connection to finish
// Run wait ssh connection to finish
func ( cc * Client ) Run ( ) error {
func ( cc * Client ) Run ( ) error {
defer cc . Close ( )
defer cc . cancel ( )
select {
select {
case <- time . After ( 1 * time . Second ) :
case <- time . After ( 1 * time . Second ) :
}
}
// wait port forward to finish
// wait port forward to finish
if cc . listeners != nil {
if cc . listeners != nil {
log . Debugf ( "wait all channel to be done" )
Log ( DEBUG , "wait all channel to be done" )
go cc . registerSignal ( )
go cc . registerSignal ( )
go func ( ) {
go func ( ) {
cc . err = cc . sshConn . Wait ( )
cc . err = cc . sshConn . Wait ( )
log . Debugf ( "connection hang up" )
Log ( DEBUG , "connection hang up" )
cc . cancel ( )
close ( cc . ch )
//close(cc.ch)
} ( )
} ( )
<- cc . ctx . Done ( )
}
return cc . err
}
func ( cc * Client ) closeListener ( ) {
// wait exit signal
if len ( cc . listeners ) == 0 {
select {
return
case <- cc . ch :
}
Log ( INFO , "got signal, exit" )
}
// close remote listener may block, because of connection issue
// so only 1 second to wait
ctx , cancel := context . WithTimeout ( context . Background ( ) , 1 * time . Second )
defer cancel ( )
wg := & sync . WaitGroup { }
for _ , l := range cc . listeners {
go func ( l net . Listener ) {
log . Debugf ( "begin to close listener %s" , l . Addr ( ) . String ( ) )
l . Close ( )
log . Debugf ( "close listener %s done" , l . Addr ( ) . String ( ) )
wg . Done ( )
} ( l )
wg . Add ( 1 )
}
}
Log ( DEBUG , "Done" )
go func ( ) {
cc . Close ( )
wg . Wait ( )
return cc . err
cancel ( )
} ( )
<- ctx . Done ( )
}
}
// Close close the ssh connection
// Close close the ssh connection
// and free all the port forward resources
// and free all the port forward resources
func ( cc * Client ) Close ( ) {
func ( cc * Client ) Close ( ) {
cc . closeListener ( )
for _ , l := range cc . listeners {
Log ( INFO , "close the listener %s" , l . Addr ( ) )
log . Debugf ( "close ssh connection" )
l . Close ( )
}
//Log(DEBUG, "close ssh connection")
cc . sshConn . Close ( )
cc . sshConn . Close ( )
cc . conn . Close ( )
cc . conn . Close ( )
log . Debugf ( "close ssh connection done" )
}
}
// RunCmd run a single command on server
// RunCmd run a single command on server
func ( cc * Client ) RunCmd ( cmd string ) ( [ ] byte , error ) {
func ( cc * Client ) RunCmd ( cmd string ) ( [ ] byte , error ) {
log . Debugf ( "run command %s" , cmd )
Log ( INFO , "run command %s" , cmd )
session , err := cc . client . NewSession ( )
session , err := cc . client . NewSession ( )
if err != nil {
if err != nil {
log . Debugf ( "command exited with error: %s" , err . Error ( ) )
Log ( DEBUG , "command exited with error: %s" , err . Error ( ) )
} else {
} else {
log . Debugf ( "command exited with no error" )
Log ( DEBUG , "command exited with no error" )
}
}
if err != nil {
if err != nil {
@ -142,7 +122,7 @@ func (cc *Client) RunCmd(cmd string) ([]byte, error) {
// Shell start a login shell on server
// Shell start a login shell on server
func ( cc * Client ) Shell ( ) error {
func ( cc * Client ) Shell ( ) error {
log . Debugf ( "request new session" )
Log ( DEBUG , "request new session" )
session , err := cc . client . NewSession ( )
session , err := cc . client . NewSession ( )
if err != nil {
if err != nil {
return err
return err
@ -158,34 +138,34 @@ func (cc *Client) Shell() error {
}
}
// this make CTRL+C works
// this make CTRL+C works
log . Debugf ( "turn terminal mode to raw" )
Log ( DEBUG , "turn terminal mode to raw" )
oldState , _ := terminal . MakeRaw ( 0 )
oldState , _ := terminal . MakeRaw ( 0 )
defer func ( ) {
log . Debugf ( "restore terminal mode" )
terminal . Restore ( 0 , oldState )
} ( )
w , h , _ := terminal . GetSize ( 0 )
w , h , _ := terminal . GetSize ( 0 )
log . Debugf ( "request pty" )
Log ( DEBUG , "request pty" )
if err := session . RequestPty ( "xterm" , h , w , modes ) ; err != nil {
if err := session . RequestPty ( "xterm" , h , w , modes ) ; err != nil {
log . Errorf ( "request pty error: %s" , err . Error ( ) )
Log ( ERROR , "request pty error: %s" , err . Error ( ) )
Log ( DEBUG , "restore terminal mode" )
terminal . Restore ( 0 , oldState )
return err
return err
}
}
log . Debugf ( "request shell" )
Log ( DEBUG , "request shell" )
if err := session . Shell ( ) ; err != nil {
if err := session . Shell ( ) ; err != nil {
log . Errorf ( "start shell error: %s" , err . Error ( ) )
Log ( ERROR , "start shell error: %s" , err . Error ( ) )
Log ( DEBUG , "restore terminal mode" )
terminal . Restore ( 0 , oldState )
return err
return err
}
}
session . Wait ( )
session . Wait ( )
log . Debugf ( "session closed" )
Log ( DEBUG , "session closed" )
terminal . Restore ( 0 , oldState )
Log ( DEBUG , "restore terminal mode" )
return nil
return nil
}
}
// AddLocalForward add a local to remote port forward
// AddLocalForward add a local to remote port forward
func ( cc * Client ) AddLocalForward ( local , remote string ) error {
func ( cc * Client ) AddLocalForward ( local , remote string ) error {
log . Debugf ( "add local forward %s -> %s" , local , remote )
Log ( DEBUG , "add local forward %s -> %s" , local , remote )
l , err := net . Listen ( "tcp" , local )
l , err := net . Listen ( "tcp" , local )
if err != nil {
if err != nil {
return err
return err
@ -196,10 +176,10 @@ func (cc *Client) AddLocalForward(local, remote string) error {
for {
for {
c , err := l . Accept ( )
c , err := l . Accept ( )
if err != nil {
if err != nil {
log . Debugf ( "local listen %s closed" , l . Addr ( ) )
Log ( DEBUG , "local listen %s closed" , l . Addr ( ) )
return
return
}
}
log . Debugf ( "connection accepted from %s" , c . RemoteAddr ( ) )
Log ( DEBUG , "connection accepted from %s" , c . RemoteAddr ( ) )
go cc . handleLocalForward ( c , remote )
go cc . handleLocalForward ( c , remote )
}
}
} ( l )
} ( l )
@ -209,7 +189,7 @@ func (cc *Client) AddLocalForward(local, remote string) error {
// AddRemoteForward add a remote to local port forward
// AddRemoteForward add a remote to local port forward
func ( cc * Client ) AddRemoteForward ( local , remote string ) error {
func ( cc * Client ) AddRemoteForward ( local , remote string ) error {
log . Debugf ( "add remote forward %s -> %s" , remote , local )
Log ( DEBUG , "add remote forward %s -> %s" , remote , local )
l , err := cc . client . Listen ( "tcp" , remote )
l , err := cc . client . Listen ( "tcp" , remote )
if err != nil {
if err != nil {
return err
return err
@ -221,10 +201,10 @@ func (cc *Client) AddRemoteForward(local, remote string) error {
for {
for {
c , err := l . Accept ( )
c , err := l . Accept ( )
if err != nil {
if err != nil {
log . Debugf ( "remote listener %s closed" , l . Addr ( ) )
Log ( DEBUG , "remote listener %s closed" , l . Addr ( ) )
return
return
}
}
log . Debugf ( "accept remote forward connection from %s" , c . RemoteAddr ( ) )
Log ( DEBUG , "accept remote forward connection from %s" , c . RemoteAddr ( ) )
go cc . handleRemoteForward ( c , local )
go cc . handleRemoteForward ( c , local )
}
}
} ( l )
} ( l )
@ -233,7 +213,7 @@ func (cc *Client) AddRemoteForward(local, remote string) error {
// AddDynamicForward add a dynamic port forward
// AddDynamicForward add a dynamic port forward
func ( cc * Client ) AddDynamicForward ( local string ) error {
func ( cc * Client ) AddDynamicForward ( local string ) error {
log . Debugf ( "add dynamic forward %s" , local )
Log ( DEBUG , "add dynamic forward %s" , local )
l , err := net . Listen ( "tcp" , local )
l , err := net . Listen ( "tcp" , local )
if err != nil {
if err != nil {
return err
return err
@ -244,10 +224,10 @@ func (cc *Client) AddDynamicForward(local string) error {
for {
for {
c , err := l . Accept ( )
c , err := l . Accept ( )
if err != nil {
if err != nil {
log . Debugf ( "local listener %s closed" , l . Addr ( ) )
Log ( DEBUG , "local listener %s closed" , l . Addr ( ) )
return
return
}
}
log . Debugf ( "accept connection from %s" , c . RemoteAddr ( ) )
Log ( DEBUG , "accept connection from %s" , c . RemoteAddr ( ) )
go cc . handleDynamicForward ( c )
go cc . handleDynamicForward ( c )
}
}
} ( l )
} ( l )
@ -257,22 +237,22 @@ func (cc *Client) AddDynamicForward(local string) error {
func ( cc * Client ) handleLocalForward ( conn net . Conn , remote string ) {
func ( cc * Client ) handleLocalForward ( conn net . Conn , remote string ) {
rconn , err := cc . client . Dial ( "tcp" , remote )
rconn , err := cc . client . Dial ( "tcp" , remote )
if err != nil {
if err != nil {
log . Errorf ( "connect to %s failed: %s" , remote , err . Error ( ) )
Log ( ERROR , "connect to %s failed: %s" , remote , err . Error ( ) )
conn . Close ( )
conn . Close ( )
return
return
}
}
log . Debugf ( "remote connect to %s success" , remote )
Log ( DEBUG , "remote connect to %s success" , remote )
PipeAndClose ( rconn , conn )
PipeAndClose ( rconn , conn )
}
}
func ( cc * Client ) handleRemoteForward ( conn net . Conn , local string ) {
func ( cc * Client ) handleRemoteForward ( conn net . Conn , local string ) {
lconn , err := dialer . Dial ( "tcp" , local )
lconn , err := net . Dial ( "tcp" , local )
if err != nil {
if err != nil {
log . Errorf ( "connect to %s failed: %s" , local , err . Error ( ) )
Log ( ERROR , "connect to %s failed: %s" , local , err . Error ( ) )
conn . Close ( )
conn . Close ( )
return
return
}
}
log . Debugf ( "connect to %s success" , local )
Log ( DEBUG , "connect to %s success" , local )
PipeAndClose ( conn , lconn )
PipeAndClose ( conn , lconn )
}
}
@ -282,19 +262,19 @@ func (cc *Client) handleDynamicForward(conn net.Conn) {
if addr . String ( ) != conn . LocalAddr ( ) . String ( ) {
if addr . String ( ) != conn . LocalAddr ( ) . String ( ) {
// transparent proxy
// transparent proxy
// iptables redirect the packet to this port
// iptables redirect the packet to this port
log . Debugf ( "transparent %s -> %s" , conn . RemoteAddr ( ) , addr )
Log ( DEBUG , "transparent %s -> %s" , conn . RemoteAddr ( ) , addr )
cc . handleTransparentProxy ( conn , addr )
cc . handleTransparentProxy ( conn , addr )
return
return
}
}
} else {
} else {
// SO_ORIGNAL_DST failed
// SO_ORIGNAL_DST failed
// just ignore it
// just ignore it
log . Debugf ( "get original destination on %s failed: %s, ignore" ,
Log ( DEBUG , "get original destination on %s failed: %s, ignore" ,
conn . LocalAddr ( ) , err )
conn . LocalAddr ( ) , err )
}
}
// socks5 to this port
// socks5 to this port
log . Debugf ( "socks %s" , conn . RemoteAddr ( ) )
Log ( DEBUG , "socks %s" , conn . RemoteAddr ( ) )
s := socks . Conn { Conn : conn , Dial : cc . client . Dial }
s := socks . Conn { Conn : conn , Dial : cc . client . Dial }
s . Serve ( )
s . Serve ( )
}
}
@ -302,54 +282,33 @@ func (cc *Client) handleDynamicForward(conn net.Conn) {
func ( cc * Client ) handleTransparentProxy ( c net . Conn , addr net . Addr ) {
func ( cc * Client ) handleTransparentProxy ( c net . Conn , addr net . Addr ) {
c2 , err := cc . client . Dial ( "tcp" , addr . String ( ) )
c2 , err := cc . client . Dial ( "tcp" , addr . String ( ) )
if err != nil {
if err != nil {
log . Errorf ( "%s" , err )
Log ( ERROR , "%s" , err )
c . Close ( )
c . Close ( )
return
return
}
}
PipeAndClose ( c2 , c )
PipeAndClose ( c2 , c )
}
}
func doKeepAlive ( conn ssh . Conn , timeout time . Duration ) error {
ctx , cancel := context . WithTimeout ( context . Background ( ) , timeout )
defer cancel ( )
ch := make ( chan error , 1 )
go func ( ) {
_ , _ , err := conn . SendRequest ( "keepalive@openssh.org" , true , nil )
ch <- err
} ( )
select {
case <- ctx . Done ( ) :
return errors . New ( "keepalive timeout" )
case err := <- ch :
if err != nil {
return err
}
return nil
}
}
func ( cc * Client ) keepAlive ( interval time . Duration , maxCount int ) {
func ( cc * Client ) keepAlive ( interval time . Duration , maxCount int ) {
count := 0
count := 0
c := time . NewTicker ( interval )
c := time . NewTicker ( interval )
defer c . Stop ( )
for {
for {
select {
select {
case <- cc . ctx . Done ( ) :
return
case <- c . C :
case <- c . C :
if err := doKeepAlive ( cc . sshConn , 3 * time . Second ) ; err != nil {
_ , _ , err := cc . sshConn . SendRequest ( "keepalive@openssh.org" , true , nil )
if err != nil {
Log ( DEBUG , "keep alive error: %s" , err . Error ( ) )
count ++
count ++
} else {
} else {
count = 0
count = 0
}
}
if count >= maxCount {
if count >= maxCount {
cc . err = fmt . Errorf ( "keep alive detects connection hang up" )
cc . err = fmt . Errorf ( "keep alive detects connection hang up" )
log . Errorf ( "keep alive hit max count, exit" )
Log ( ERROR , "keep alive hit max count, exit" )
cc . cancel ( )
//cc.sshConn.Close()
//cc.conn.Close()
// send exit signal
close ( cc . ch )
return
return
}
}
}
}
@ -362,96 +321,7 @@ func (cc *Client) registerSignal() {
select {
select {
case s1 := <- c :
case s1 := <- c :
cc . err = fmt . Errorf ( "signal %v" , s1 )
cc . err = fmt . Errorf ( "signal %v" , s1 )
log . Errorf ( "signal %d received, exit" , s1 )
Log ( ERROR , "signal %d received, exit" , s1 )
//close(cc.ch)
close ( cc . ch )
cc . cancel ( )
}
}
// AddDynamicHTTPForward add a http dynamic forward through
// secure channel
func ( cc * Client ) AddDynamicHTTPForward ( addr string ) error {
log . Debugf ( "add dynamic http listen: %s" , addr )
l , err := net . Listen ( "tcp" , addr )
if err != nil {
log . Errorf ( "listen on %s failed, %s" , addr , err )
return err
}
cc . listeners = append ( cc . listeners , l )
go func ( l net . Listener ) {
// defer l.Close()
for {
c , err := l . Accept ( )
if err != nil {
log . Errorf ( "accept error %s" , err )
break
}
go cc . handleHTTPIncoming ( c )
}
} ( l )
return nil
}
func ( cc * Client ) handleHTTPIncoming ( c net . Conn ) {
//defer c.Close()
r := bufio . NewReader ( c )
req , err := http . ReadRequest ( r )
if err != nil {
log . Errorf ( "read http request error %s" , err )
c . Close ( )
return
}
if req . Method == "CONNECT" {
cc . handleConnect ( req , c )
return
}
cc . handleHTTPReq ( req , c )
}
func ( cc * Client ) handleConnect ( req * http . Request , c net . Conn ) {
log . Debugf ( "connect to %s" , req . RequestURI )
c1 , err := cc . client . Dial ( "tcp" , req . RequestURI )
if err != nil {
fmt . Fprintf ( c , "HTTP/1.0 503 connection failed\r\n\r\n" )
log . Errorf ( "dial error %s" , err )
c . Close ( )
return
}
//defer c1.Close()
fmt . Fprintf ( c , "HTTP/1.0 200 connection established\r\n\r\n" )
PipeAndClose ( c , c1 )
}
func ( cc * Client ) handleHTTPReq ( req * http . Request , c net . Conn ) {
host := req . Host
if ! strings . Contains ( host , ":" ) {
host = fmt . Sprintf ( "%s:80" , host )
}
log . Debugf ( "request to %s" , host )
c1 , err := cc . client . Dial ( "tcp" , host )
if err != nil {
fmt . Fprintf ( c , "HTTP/1.1 503 connection failed\r\nConnection: close\r\n\r\n" )
log . Errorf ( "connection failed %s" , err )
c . Close ( )
return
}
//defer c1.Close()
if err = req . Write ( c1 ) ; err != nil {
fmt . Fprintf ( c , "HTTP/1.1 503 write to server error\r\nConnection: close\r\n\r\n" )
log . Errorf ( "write request to server error %s" , err )
c . Close ( )
c1 . Close ( )
return
}
}
PipeAndClose ( c , c1 )
}
}