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

311 lines
7.3 KiB
Go
Raw Normal View History

2018-10-09 15:07:54 +00:00
package main
import (
2018-11-22 21:55:23 +00:00
"bytes"
2019-01-12 15:51:20 +00:00
"encoding/base64"
2018-10-09 15:07:54 +00:00
"flag"
"fmt"
"io"
"log"
"net"
"os"
"strings"
"time"
mux "github.com/cbeuw/Cloak/internal/multiplex"
"github.com/cbeuw/Cloak/internal/server"
"github.com/cbeuw/Cloak/internal/server/usermanager"
2018-10-09 15:07:54 +00:00
"github.com/cbeuw/Cloak/internal/util"
)
var version string
2019-06-09 11:05:41 +00:00
//TODO: take iv into account
2018-10-09 15:07:54 +00:00
func pipe(dst io.ReadWriteCloser, src io.ReadWriteCloser) {
// The maximum size of TLS message will be 16396+12. 12 because of the stream header
2018-10-20 20:41:01 +00:00
// 16408 is the max TLS message size on Firefox
buf := make([]byte, 16396)
2018-10-09 15:07:54 +00:00
for {
2018-10-20 10:35:50 +00:00
i, err := io.ReadAtLeast(src, buf, 1)
2019-01-12 17:06:14 +00:00
if err != nil {
2018-10-20 10:35:50 +00:00
go dst.Close()
go src.Close()
return
}
i, err = dst.Write(buf[:i])
2019-01-12 17:06:14 +00:00
if err != nil {
2018-10-09 15:07:54 +00:00
go dst.Close()
go src.Close()
return
}
}
}
func dispatchConnection(conn net.Conn, sta *server.State) {
goWeb := func(data []byte) {
webConn, err := net.Dial("tcp", sta.RedirAddr)
2018-10-09 15:07:54 +00:00
if err != nil {
log.Printf("Making connection to redirection server: %v\n", err)
return
}
webConn.Write(data)
go pipe(webConn, conn)
go pipe(conn, webConn)
}
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]
ch, err := server.ParseClientHello(data)
if err != nil {
log.Printf("+1 non Cloak non (or malformed) TLS traffic from %v\n", conn.RemoteAddr())
2018-10-09 15:07:54 +00:00
goWeb(data)
return
}
2019-06-09 11:05:41 +00:00
isCloak, UID, sessionID, proxyMethod, encryptionMethod := server.TouchStone(ch, sta)
if !isCloak {
log.Printf("+1 non Cloak TLS traffic from %v\n", conn.RemoteAddr())
goWeb(data)
return
}
if _, ok := sta.ProxyBook[proxyMethod]; !ok {
log.Printf("+1 Cloak TLS traffic with invalid proxy method `%v` from %v\n", proxyMethod, conn.RemoteAddr())
2018-10-09 15:07:54 +00:00
goWeb(data)
return
}
finishHandshake := func() error {
2018-11-22 21:55:23 +00:00
reply := server.ComposeReply(ch)
_, err = conn.Write(reply)
if err != nil {
go conn.Close()
return err
2018-11-22 21:55:23 +00:00
}
// Two discarded messages: ChangeCipherSpec and Finished
discardBuf := make([]byte, 1024)
for c := 0; c < 2; c++ {
_, err = util.ReadTLS(conn, discardBuf)
if err != nil {
go conn.Close()
return err
2018-11-22 21:55:23 +00:00
}
}
return nil
}
2018-11-22 21:55:23 +00:00
2019-01-12 15:51:20 +00:00
// 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 {
err = finishHandshake()
if err != nil {
log.Println(err)
return
}
2018-11-22 21:55:23 +00:00
c := sta.Userpanel.MakeController(sta.AdminUID)
for {
n, err := conn.Read(data)
if err != nil {
log.Println(err)
return
}
resp, err := c.HandleRequest(data[:n])
if err != nil {
log.Println(err)
2018-11-22 21:55:23 +00:00
}
_, err = conn.Write(resp)
if err != nil {
log.Println(err)
return
}
}
}
var user *usermanager.User
if bytes.Equal(UID, sta.AdminUID) {
user, err = sta.Userpanel.GetAndActivateAdminUser(UID)
} else {
user, err = sta.Userpanel.GetAndActivateUser(UID)
}
2018-11-07 21:16:13 +00:00
if err != nil {
log.Printf("+1 unauthorised user from %v, uid: %x\n", conn.RemoteAddr(), UID)
goWeb(data)
2018-11-22 21:55:23 +00:00
return
2018-11-07 21:16:13 +00:00
}
2018-10-09 15:07:54 +00:00
err = finishHandshake()
2018-10-09 15:07:54 +00:00
if err != nil {
log.Println(err)
2018-10-09 15:07:54 +00:00
return
}
2019-06-09 11:05:41 +00:00
var crypto mux.Crypto
switch encryptionMethod {
case 0x00:
crypto = &mux.Plain{}
case 0x01:
crypto, err = mux.MakeAESCipher(UID)
if err != nil {
log.Println(err)
goWeb(data)
return
}
default:
goWeb(data)
return
}
sesh, existing, err := user.GetSession(sessionID, mux.MakeObfs(UID, crypto), mux.MakeDeobfs(UID, crypto), util.ReadTLS)
if err != nil {
user.DelSession(sessionID)
log.Println(err)
return
}
if existing {
sesh.AddConnection(conn)
return
} else {
2019-01-12 15:51:20 +00:00
log.Printf("New session from UID:%v, sessionID:%v\n", base64.StdEncoding.EncodeToString(UID), sessionID)
sesh.AddConnection(conn)
for {
newStream, err := sesh.AcceptStream()
if err != nil {
if err == mux.ErrBrokenSession {
2019-01-12 15:51:20 +00:00
log.Printf("Session closed for UID:%v, sessionID:%v\n", base64.StdEncoding.EncodeToString(UID), sessionID)
user.DelSession(sessionID)
return
} else {
continue
}
}
localConn, err := net.Dial("tcp", sta.ProxyBook[proxyMethod])
if err != nil {
log.Printf("Failed to connect to %v: %v\n", proxyMethod, err)
2018-11-07 21:16:13 +00:00
continue
2018-10-09 15:07:54 +00:00
}
go pipe(localConn, newStream)
go 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
log.SetFlags(log.LstdFlags | log.Lshortfile)
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 {
fmt.Printf("ck-server %s\n", version)
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 != "" {
startPprof(*pprofAddr)
2019-01-21 11:49:01 +00:00
}
log.Printf("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-12-03 20:44:08 +00:00
if sta.AdminUID == nil {
log.Fatalln("AdminUID cannot be empty!")
}
2018-10-09 15:07:54 +00:00
go sta.UsedRandomCleaner()
listen := func(addr, port string) {
listener, err := net.Listen("tcp", addr+":"+port)
log.Println("Listening on " + addr + ":" + port)
if err != nil {
log.Fatal(err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("%v", err)
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
}
}
}