Cloak/cmd/ck-server/ck-server.go

275 lines
6.6 KiB
Go
Raw Normal View History

2018-10-09 15:07:54 +00:00
package main
import (
"bytes"
2019-08-02 00:01:19 +00:00
"crypto/rand"
2019-01-12 15:51:20 +00:00
"encoding/base64"
2018-10-09 15:07:54 +00:00
"flag"
"fmt"
"io"
"net"
"net/http"
2019-07-25 21:06:33 +00:00
_ "net/http/pprof"
2018-10-09 15:07:54 +00:00
"os"
"runtime"
2018-10-09 15:07:54 +00:00
"strings"
"time"
mux "github.com/cbeuw/Cloak/internal/multiplex"
"github.com/cbeuw/Cloak/internal/server"
"github.com/cbeuw/Cloak/internal/util"
2019-08-02 14:45:33 +00:00
log "github.com/sirupsen/logrus"
2018-10-09 15:07:54 +00:00
)
2019-08-02 14:45:33 +00:00
var b64 = base64.StdEncoding.EncodeToString
2018-10-09 15:07:54 +00:00
var version string
func dispatchConnection(conn net.Conn, sta *server.State) {
2019-08-02 14:45:33 +00:00
remoteAddr := conn.RemoteAddr()
var err error
2018-10-09 15:07:54 +00:00
buf := make([]byte, 1500)
conn.SetReadDeadline(time.Now().Add(3 * time.Second))
i, err := io.ReadAtLeast(conn, buf, 1)
if err != nil {
go conn.Close()
return
}
conn.SetReadDeadline(time.Time{})
data := buf[:i]
2019-08-02 00:01:19 +00:00
goWeb := func() {
webConn, err := net.Dial("tcp", sta.RedirAddr)
if err != nil {
2019-08-02 14:45:33 +00:00
log.Errorf("Making connection to redirection server: %v", err)
2019-08-02 00:01:19 +00:00
return
}
2019-08-03 12:26:57 +00:00
_, err = webConn.Write(data)
if err != nil {
log.Error("Failed to send first packet to redirection server", err)
}
2019-08-03 13:58:48 +00:00
go util.Pipe(webConn, conn)
go util.Pipe(conn, webConn)
2019-08-02 00:01:19 +00:00
}
2019-08-06 14:50:33 +00:00
UID, sessionID, proxyMethod, encryptionMethod, finishHandshake, err := server.PrepareConnection(data, sta, conn)
2018-10-09 15:07:54 +00:00
if err != nil {
2019-08-02 14:45:33 +00:00
log.WithFields(log.Fields{
2019-08-06 14:50:33 +00:00
"remoteAddr": remoteAddr,
"UID": UID,
"sessionId": sessionID,
"proxyMethod": proxyMethod,
"encryptionMethod": encryptionMethod,
}).Warn(err)
2019-08-02 00:01:19 +00:00
}
2018-11-22 21:55:23 +00:00
2019-08-02 00:01:19 +00:00
sessionKey := make([]byte, 32)
rand.Read(sessionKey)
obfuscator, err := mux.GenerateObfs(encryptionMethod, sessionKey)
2019-08-02 00:01:19 +00:00
if err != nil {
2019-08-02 14:45:33 +00:00
log.Error(err)
2019-08-02 00:01:19 +00:00
goWeb()
}
// adminUID can use the server as normal with unlimited QoS credits. The adminUID is not
// added to the userinfo database. The distinction between going into the admin mode
// and normal proxy mode is that sessionID needs == 0 for admin mode
if bytes.Equal(UID, sta.AdminUID) && sessionID == 0 {
2019-08-02 00:01:19 +00:00
err = finishHandshake(sessionKey)
if err != nil {
2019-08-02 14:45:33 +00:00
log.Error(err)
return
}
2019-08-06 14:50:33 +00:00
log.Trace("finished handshake")
2019-08-02 15:37:48 +00:00
sesh := mux.MakeSession(0, mux.UNLIMITED_VALVE, obfuscator, util.ReadTLS)
sesh.AddConnection(conn)
//TODO: Router could be nil in cnc mode
2019-08-03 21:42:26 +00:00
log.WithField("remoteAddr", conn.RemoteAddr()).Info("New admin session")
err = http.Serve(sesh, sta.LocalAPIRouter)
if err != nil {
2019-08-02 14:45:33 +00:00
log.Error(err)
return
}
}
2019-08-04 20:10:59 +00:00
var user *server.ActiveUser
if sta.IsBypass(UID) {
user, err = sta.Panel.GetBypassUser(UID)
} else {
user, err = sta.Panel.GetUser(UID)
}
2019-08-03 21:42:26 +00:00
if err != nil {
log.WithFields(log.Fields{
"UID": b64(UID),
"remoteAddr": remoteAddr,
"error": err,
}).Warn("+1 unauthorised UID")
goWeb()
return
}
sesh, existing, err := user.GetSession(sessionID, obfuscator, util.ReadTLS)
if err != nil {
2019-08-04 20:10:59 +00:00
user.DeleteSession(sessionID, "")
2019-08-03 21:42:26 +00:00
log.Error(err)
return
}
if existing {
err = finishHandshake(sesh.SessionKey)
if err != nil {
log.Error(err)
return
}
2019-08-06 14:50:33 +00:00
log.Trace("finished handshake")
2019-08-03 21:42:26 +00:00
sesh.AddConnection(conn)
return
}
2019-08-02 00:01:19 +00:00
err = finishHandshake(sessionKey)
2018-10-09 15:07:54 +00:00
if err != nil {
2019-08-02 14:45:33 +00:00
log.Error(err)
2018-10-09 15:07:54 +00:00
return
}
2019-08-06 14:50:33 +00:00
log.Trace("finished handshake")
2018-10-09 15:07:54 +00:00
2019-08-02 14:45:33 +00:00
log.WithFields(log.Fields{
"UID": b64(UID),
"sessionID": sessionID,
}).Info("New session")
2019-08-02 00:01:19 +00:00
sesh.AddConnection(conn)
2019-08-02 00:01:19 +00:00
for {
newStream, err := sesh.Accept()
if err != nil {
if err == mux.ErrBrokenSession {
2019-08-02 14:45:33 +00:00
log.WithFields(log.Fields{
"UID": b64(UID),
"sessionID": sessionID,
"reason": sesh.TerminalMsg(),
}).Info("Session closed")
2019-08-04 20:10:59 +00:00
user.DeleteSession(sessionID, "")
2019-08-02 00:01:19 +00:00
return
} else {
2018-11-07 21:16:13 +00:00
continue
2018-10-09 15:07:54 +00:00
}
2018-11-07 21:16:13 +00:00
}
2019-08-02 00:01:19 +00:00
localConn, err := net.Dial("tcp", sta.ProxyBook[proxyMethod])
if err != nil {
2019-08-02 14:45:33 +00:00
log.Errorf("Failed to connect to %v: %v", proxyMethod, err)
2019-08-03 12:26:57 +00:00
sesh.Close()
2019-08-02 00:01:19 +00:00
continue
}
2019-08-03 13:58:48 +00:00
go util.Pipe(localConn, newStream)
go util.Pipe(newStream, localConn)
2018-11-07 21:16:13 +00:00
}
2018-10-09 15:07:54 +00:00
}
func main() {
// server in ss config, the outbound listening ip
var bindHost string
2018-10-09 15:07:54 +00:00
// Outbound listening ip, should be 443
var bindPort string
var config string
2018-10-09 15:07:54 +00:00
2019-08-02 14:45:33 +00:00
log.SetLevel(log.DebugLevel)
2018-10-09 15:07:54 +00:00
if os.Getenv("SS_LOCAL_HOST") != "" {
bindHost = os.Getenv("SS_REMOTE_HOST")
bindPort = os.Getenv("SS_REMOTE_PORT")
config = os.Getenv("SS_PLUGIN_OPTIONS")
2018-10-09 15:07:54 +00:00
} else {
flag.StringVar(&bindHost, "s", "0.0.0.0", "bindHost: ip to bind to, set to 0.0.0.0 to listen to everything")
flag.StringVar(&bindPort, "p", "443", "bindPort: port to bind to, should be 443")
flag.StringVar(&config, "c", "server.json", "config: path to the configuration file or its content")
2018-10-09 15:07:54 +00:00
askVersion := flag.Bool("v", false, "Print the version number")
printUsage := flag.Bool("h", false, "Print this message")
2018-12-17 22:12:38 +00:00
genUID := flag.Bool("u", false, "Generate a UID")
genKeyPair := flag.Bool("k", false, "Generate a pair of public and private key, output in the format of pubkey,pvkey")
2019-01-21 11:49:01 +00:00
pprofAddr := flag.String("d", "", "debug use: ip:port to be listened by pprof profiler")
2018-10-09 15:07:54 +00:00
flag.Parse()
if *askVersion {
2019-08-02 14:45:33 +00:00
fmt.Printf("ck-server %s", version)
2018-10-09 15:07:54 +00:00
return
}
if *printUsage {
flag.Usage()
return
}
2018-12-17 22:12:38 +00:00
if *genUID {
fmt.Println(generateUID())
return
}
if *genKeyPair {
pub, pv := generateKeyPair()
fmt.Printf("%v,%v", pub, pv)
return
}
2018-10-09 15:07:54 +00:00
2019-01-21 11:49:01 +00:00
if *pprofAddr != "" {
runtime.SetBlockProfileRate(5)
go func() {
2019-08-02 14:45:33 +00:00
log.Info(http.ListenAndServe(*pprofAddr, nil))
}()
2019-08-02 14:45:33 +00:00
log.Infof("pprof listening on %v", *pprofAddr)
2019-01-21 11:49:01 +00:00
}
2019-08-02 14:45:33 +00:00
log.Infof("Starting standalone mode, listening on %v:%v", bindHost, bindPort)
2018-10-09 15:07:54 +00:00
}
sta, _ := server.InitState(bindHost, bindPort, time.Now)
2018-11-07 21:16:13 +00:00
err := sta.ParseConfig(config)
2018-10-09 15:07:54 +00:00
if err != nil {
log.Fatalf("Configuration file error: %v", err)
}
// when cloak is started as a shadowsocks plugin
if os.Getenv("SS_LOCAL_HOST") != "" && os.Getenv("SS_LOCAL_PORT") != "" {
ssLocalHost := os.Getenv("SS_LOCAL_HOST")
ssLocalPort := os.Getenv("SS_LOCAL_PORT")
if net.ParseIP(ssLocalHost).To4() == nil {
ssLocalHost = "[" + ssLocalHost + "]"
}
sta.ProxyBook["shadowsocks"] = ssLocalHost + ":" + ssLocalPort
}
2018-10-09 15:07:54 +00:00
listen := func(addr, port string) {
listener, err := net.Listen("tcp", addr+":"+port)
2019-08-02 14:45:33 +00:00
log.Infof("Listening on " + addr + ":" + port)
2018-10-09 15:07:54 +00:00
if err != nil {
log.Fatal(err)
}
for {
conn, err := listener.Accept()
if err != nil {
2019-08-02 14:45:33 +00:00
log.Errorf("%v", err)
2018-10-09 15:07:54 +00:00
continue
}
go dispatchConnection(conn, sta)
}
}
// When listening on an IPv6 and IPv4, SS gives REMOTE_HOST as e.g. ::|0.0.0.0
listeningIP := strings.Split(sta.BindHost, "|")
2018-10-09 15:07:54 +00:00
for i, ip := range listeningIP {
if net.ParseIP(ip).To4() == nil {
// IPv6 needs square brackets
ip = "[" + ip + "]"
}
// The last listener must block main() because the program exits on main return.
if i == len(listeningIP)-1 {
listen(ip, sta.BindPort)
2018-10-09 15:07:54 +00:00
} else {
go listen(ip, sta.BindPort)
2018-10-09 15:07:54 +00:00
}
}
}