general: add vendor folder

This commit is contained in:
nadoo committed 2018-07-07 11:07:38 +08:00
1 parent 621e8ed018
commit 3c766d0b68
103 files changed
+18061 -19

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 YanXin Sun
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+84
View File
@@ -0,0 +1,84 @@
# shadowsocksR
[shadowsocksR](https://github.com/sun8911879/shadowsocksR) is a shadowsocksR for Go library
* shadowsocksR is based on [avege](https://github.com/avege/avege) and [shadowsocksR for Python](https://github.com/shadowsocksr-backup/shadowsocksr) changes.
* Repair avege SSR communication BUG and streamline version. Is a normal use version.
#### Use
```go
bi := &BackendInfo{
Address: "www.domain.com:445",
Type: "ssr",
SSInfo: SSInfo{
EncryptMethod: "aes-128-cfb",
EncryptPassword: "password",
SSRInfo: SSRInfo{
Protocol: "auth_aes128_sha1",
ProtocolParam: "",
Obfs: "tls1.2_ticket_auth",
ObfsParam: "",
},
},
}
dst, err := bi.DialSSRConn(rawaddr)
bi.Pipe(src, dst)
bi.Pipe(dst, src)
```
See 'example/client.go' for detailed usage.
#### SS Encrypting algorithm
* aes-128-cfb
* aes-192-cfb
* aes-256-cfb
* aes-128-ctr
* aes-192-ctr
* aes-256-ctr
* aes-128-ofb
* aes-192-ofb
* aes-256-ofb
* des-cfb
* bf-cfb
* cast5-cfb
* rc4-md5
* chacha20
* chacha20-ietf
* salsa20
* camellia-128-cfb
* camellia-192-cfb
* camellia-256-cfb
* idea-cfb
* rc2-cfb
* seed-cfb
#### SSR Obfs
* plain
* http_simple
* http_post
* random_head
* tls1.2_ticket_auth
#### SSR Protocol
* origin
* verify_sha1 aka. one time auth(OTA)
* auth_sha1_v4
* auth_aes128_md5
* auth_aes128_sha1
## Todo (help wanted)
* Optimize performance
### Thanks avege project
* [avege](https://github.com/avege/avege)
### Reference
* [avege](https://github.com/avege/avege)
* [shadowsocks-go](https://github.com/shadowsocks/shadowsocks-go)
* [go-shadowsocks2](https://github.com/shadowsocks/go-shadowsocks2)
* [ShadowsocksR](https://github.com/shadowsocksr-backup/shadowsocksr)
+61
View File
@@ -0,0 +1,61 @@
package shadowsocksr
import (
"errors"
"net"
"net/url"
"strconv"
"strings"
"time"
"github.com/sun8911879/shadowsocksR/obfs"
"github.com/sun8911879/shadowsocksR/protocol"
"github.com/sun8911879/shadowsocksR/ssr"
)
func NewSSRClient(u *url.URL) (*SSTCPConn, error) {
query := u.Query()
encryptMethod := query.Get("encrypt-method")
encryptKey := query.Get("encrypt-key")
cipher, err := NewStreamCipher(encryptMethod, encryptKey)
if err != nil {
return nil, err
}
dialer := net.Dialer{
Timeout: time.Millisecond * 500,
DualStack: true,
}
conn, err := dialer.Dial("tcp", u.Host)
if err != nil {
return nil, err
}
ssconn := NewSSTCPConn(conn, cipher)
if ssconn.Conn == nil || ssconn.RemoteAddr() == nil {
return nil, errors.New("nil connection")
}
// should initialize obfs/protocol now
rs := strings.Split(ssconn.RemoteAddr().String(), ":")
port, _ := strconv.Atoi(rs[1])
ssconn.IObfs = obfs.NewObfs(query.Get("obfs"))
obfsServerInfo := &ssr.ServerInfoForObfs{
Host: rs[0],
Port: uint16(port),
TcpMss: 1460,
Param: query.Get("obfs-param"),
}
ssconn.IObfs.SetServerInfo(obfsServerInfo)
ssconn.IProtocol = protocol.NewProtocol(query.Get("protocol"))
protocolServerInfo := &ssr.ServerInfoForObfs{
Host: rs[0],
Port: uint16(port),
TcpMss: 1460,
Param: query.Get("protocol-param"),
}
ssconn.IProtocol.SetServerInfo(protocolServerInfo)
return ssconn, nil
}
+296
View File
@@ -0,0 +1,296 @@
package shadowsocksr
import (
"crypto/aes"
"crypto/cipher"
"crypto/des"
"crypto/md5"
"crypto/rand"
"crypto/rc4"
"encoding/binary"
"errors"
"github.com/sun8911879/shadowsocksR/tools"
"github.com/sun8911879/shadowsocksR/tools/leakybuf"
"github.com/Yawning/chacha20"
"github.com/dgryski/go-camellia"
"github.com/dgryski/go-idea"
"github.com/dgryski/go-rc2"
"golang.org/x/crypto/blowfish"
"golang.org/x/crypto/cast5"
"golang.org/x/crypto/salsa20/salsa"
)
var errEmptyPassword = errors.New("empty key")
type DecOrEnc int
const (
Decrypt DecOrEnc = iota
Encrypt
)
func newCTRStream(block cipher.Block, err error, key, iv []byte, doe DecOrEnc) (cipher.Stream, error) {
if err != nil {
return nil, err
}
return cipher.NewCTR(block, iv), nil
}
func newAESCTRStream(key, iv []byte, doe DecOrEnc) (cipher.Stream, error) {
block, err := aes.NewCipher(key)
return newCTRStream(block, err, key, iv, doe)
}
func newOFBStream(block cipher.Block, err error, key, iv []byte, doe DecOrEnc) (cipher.Stream, error) {
if err != nil {
return nil, err
}
return cipher.NewCTR(block, iv), nil
}
func newAESOFBStream(key, iv []byte, doe DecOrEnc) (cipher.Stream, error) {
block, err := aes.NewCipher(key)
return newOFBStream(block, err, key, iv, doe)
}
func newCFBStream(block cipher.Block, err error, key, iv []byte, doe DecOrEnc) (cipher.Stream, error) {
if err != nil {
return nil, err
}
if doe == Encrypt {
return cipher.NewCFBEncrypter(block, iv), nil
} else {
return cipher.NewCFBDecrypter(block, iv), nil
}
}
func newAESCFBStream(key, iv []byte, doe DecOrEnc) (cipher.Stream, error) {
block, err := aes.NewCipher(key)
return newCFBStream(block, err, key, iv, doe)
}
func newDESStream(key, iv []byte, doe DecOrEnc) (cipher.Stream, error) {
block, err := des.NewCipher(key)
return newCFBStream(block, err, key, iv, doe)
}
func newBlowFishStream(key, iv []byte, doe DecOrEnc) (cipher.Stream, error) {
block, err := blowfish.NewCipher(key)
return newCFBStream(block, err, key, iv, doe)
}
func newCast5Stream(key, iv []byte, doe DecOrEnc) (cipher.Stream, error) {
block, err := cast5.NewCipher(key)
return newCFBStream(block, err, key, iv, doe)
}
func newRC4MD5Stream(key, iv []byte, _ DecOrEnc) (cipher.Stream, error) {
h := md5.New()
h.Write(key)
h.Write(iv)
rc4key := h.Sum(nil)
return rc4.NewCipher(rc4key)
}
func newChaCha20Stream(key, iv []byte, _ DecOrEnc) (cipher.Stream, error) {
return chacha20.NewCipher(key, iv)
}
func newChacha20IETFStream(key, iv []byte, _ DecOrEnc) (cipher.Stream, error) {
return chacha20.NewCipher(key, iv)
}
type salsaStreamCipher struct {
nonce [8]byte
key [32]byte
counter int
}
func (c *salsaStreamCipher) XORKeyStream(dst, src []byte) {
var buf []byte
padLen := c.counter % 64
dataSize := len(src) + padLen
if cap(dst) >= dataSize {
buf = dst[:dataSize]
} else if leakybuf.GlobalLeakyBufSize >= dataSize {
buf = leakybuf.GlobalLeakyBuf.Get()
defer leakybuf.GlobalLeakyBuf.Put(buf)
buf = buf[:dataSize]
} else {
buf = make([]byte, dataSize)
}
var subNonce [16]byte
copy(subNonce[:], c.nonce[:])
binary.LittleEndian.PutUint64(subNonce[len(c.nonce):], uint64(c.counter/64))
// It's difficult to avoid data copy here. src or dst maybe slice from
// Conn.Read/Write, which can't have padding.
copy(buf[padLen:], src[:])
salsa.XORKeyStream(buf, buf, &subNonce, &c.key)
copy(dst, buf[padLen:])
c.counter += len(src)
}
func newSalsa20Stream(key, iv []byte, _ DecOrEnc) (cipher.Stream, error) {
var c salsaStreamCipher
copy(c.nonce[:], iv[:8])
copy(c.key[:], key[:32])
return &c, nil
}
func newCamelliaStream(key, iv []byte, doe DecOrEnc) (cipher.Stream, error) {
block, err := camellia.New(key)
return newCFBStream(block, err, key, iv, doe)
}
func newIdeaStream(key, iv []byte, doe DecOrEnc) (cipher.Stream, error) {
block, err := idea.NewCipher(key)
return newCFBStream(block, err, key, iv, doe)
}
func newRC2Stream(key, iv []byte, doe DecOrEnc) (cipher.Stream, error) {
block, err := rc2.New(key, 16)
return newCFBStream(block, err, key, iv, doe)
}
func newSeedStream(key, iv []byte, doe DecOrEnc) (cipher.Stream, error) {
// TODO: SEED block cipher implementation is required
block, err := rc2.New(key, 16)
return newCFBStream(block, err, key, iv, doe)
}
type cipherInfo struct {
keyLen int
ivLen int
newStream func(key, iv []byte, doe DecOrEnc) (cipher.Stream, error)
}
var streamCipherMethod = map[string]*cipherInfo{
"aes-128-cfb": {16, 16, newAESCFBStream},
"aes-192-cfb": {24, 16, newAESCFBStream},
"aes-256-cfb": {32, 16, newAESCFBStream},
"aes-128-ctr": {16, 16, newAESCTRStream},
"aes-192-ctr": {24, 16, newAESCTRStream},
"aes-256-ctr": {32, 16, newAESCTRStream},
"aes-128-ofb": {16, 16, newAESOFBStream},
"aes-192-ofb": {24, 16, newAESOFBStream},
"aes-256-ofb": {32, 16, newAESOFBStream},
"des-cfb": {8, 8, newDESStream},
"bf-cfb": {16, 8, newBlowFishStream},
"cast5-cfb": {16, 8, newCast5Stream},
"rc4-md5": {16, 16, newRC4MD5Stream},
"rc4-md5-6": {16, 6, newRC4MD5Stream},
"chacha20": {32, 8, newChaCha20Stream},
"chacha20-ietf": {32, 12, newChacha20IETFStream},
"salsa20": {32, 8, newSalsa20Stream},
"camellia-128-cfb": {16, 16, newCamelliaStream},
"camellia-192-cfb": {24, 16, newCamelliaStream},
"camellia-256-cfb": {32, 16, newCamelliaStream},
"idea-cfb": {16, 8, newIdeaStream},
"rc2-cfb": {16, 8, newRC2Stream},
"seed-cfb": {16, 8, newSeedStream},
}
func CheckCipherMethod(method string) error {
if method == "" {
method = "rc4-md5"
}
_, ok := streamCipherMethod[method]
if !ok {
return errors.New("Unsupported encryption method: " + method)
}
return nil
}
type StreamCipher struct {
enc cipher.Stream
dec cipher.Stream
key []byte
info *cipherInfo
iv []byte
}
// NewStreamCipher creates a cipher that can be used in Dial() etc.
// Use cipher.Copy() to create a new cipher with the same method and password
// to avoid the cost of repeated cipher initialization.
func NewStreamCipher(method, password string) (c *StreamCipher, err error) {
if password == "" {
return nil, errEmptyPassword
}
if method == "" {
method = "rc4-md5"
}
mi, ok := streamCipherMethod[method]
if !ok {
return nil, errors.New("Unsupported encryption method: " + method)
}
key := tools.EVPBytesToKey(password, mi.keyLen)
c = &StreamCipher{key: key, info: mi}
if err != nil {
return nil, err
}
return c, nil
}
// Initializes the block cipher with CFB mode, returns IV.
func (c *StreamCipher) initEncrypt() (iv []byte, err error) {
if c.iv == nil {
iv = make([]byte, c.info.ivLen)
rand.Read(iv)
c.iv = iv
} else {
iv = c.iv
}
c.enc, err = c.info.newStream(c.key, iv, Encrypt)
return
}
func (c *StreamCipher) initDecrypt(iv []byte) (err error) {
c.dec, err = c.info.newStream(c.key, iv, Decrypt)
return
}
func (c *StreamCipher) encrypt(dst, src []byte) {
c.enc.XORKeyStream(dst, src)
}
func (c *StreamCipher) decrypt(dst, src []byte) {
c.dec.XORKeyStream(dst, src)
}
// Copy creates a new cipher at it's initial state.
func (c *StreamCipher) Copy() *StreamCipher {
// This optimization maybe not necessary. But without this function, we
// need to maintain a table cache for newTableCipher and use lock to
// protect concurrent access to that cache.
// AES and DES ciphers does not return specific types, so it's difficult
// to create copy. But their initialization time is less than 4000ns on my
// 2.26 GHz Intel Core 2 Duo processor. So no need to worry.
// Currently, blow-fish and cast5 initialization cost is an order of
// magnitude slower than other ciphers. (I'm not sure whether this is
// because the current implementation is not highly optimized, or this is
// the nature of the algorithm.)
nc := *c
nc.enc = nil
nc.dec = nil
return &nc
}
func (c *StreamCipher) Key() (key []byte, keyLen int) {
return c.key, c.info.keyLen
}
func (c *StreamCipher) IV() ([]byte, int) {
return c.iv, c.info.ivLen
}
+35
View File
@@ -0,0 +1,35 @@
package obfs
import (
"strings"
"github.com/sun8911879/shadowsocksR/ssr"
)
type creator func() IObfs
var (
creatorMap = make(map[string]creator)
)
type IObfs interface {
SetServerInfo(s *ssr.ServerInfoForObfs)
GetServerInfo() (s *ssr.ServerInfoForObfs)
Encode(data []byte) ([]byte, error)
Decode(data []byte) ([]byte, uint64, error)
SetData(data interface{})
GetData() interface{}
}
func register(name string, c creator) {
creatorMap[name] = c
}
// NewObfs create an obfs object by name and return as an IObfs interface
func NewObfs(name string) IObfs {
c, ok := creatorMap[strings.ToLower(name)]
if ok {
return c()
}
return nil
}
+19
View File
@@ -0,0 +1,19 @@
package obfs
import (
"math/rand"
)
func init() {
register("http_post", newHttpPost)
}
// newHttpPost create a http_post object
func newHttpPost() IObfs {
// newHttpSimple create a http_simple object
t := &httpSimplePost{
userAgentIndex: rand.Intn(len(requestUserAgent)),
getOrPost: false,
}
return t
}
+178
View File
@@ -0,0 +1,178 @@
package obfs
import (
"bytes"
"encoding/hex"
"fmt"
"math/rand"
"strings"
"github.com/sun8911879/shadowsocksR/ssr"
)
var (
requestPath = []string{
"", "",
"login.php?redir=", "",
"register.php?code=", "",
"s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&ch=&bar=&wd=", "&rn=",
"post.php?id=", "&goto=view.php",
}
requestUserAgent = []string{
"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0",
"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/44.0",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Ubuntu/11.10 Chromium/27.0.1453.93 Chrome/27.0.1453.93 Safari/537.36",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0",
"Mozilla/5.0 (compatible; WOW64; MSIE 10.0; Windows NT 6.2)",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; Trident/7.0; .NET4.0E; .NET4.0C)",
"Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (Linux; Android 4.4; Nexus 5 Build/BuildID) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36",
"Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3",
"Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3",
}
)
// HttpSimple http_simple obfs encapsulate
type httpSimplePost struct {
ssr.ServerInfoForObfs
rawTransSent bool
rawTransReceived bool
userAgentIndex int
getOrPost bool // true for get, false for post
}
func init() {
register("http_simple", newHttpSimple)
}
// newHttpSimple create a http_simple object
func newHttpSimple() IObfs {
t := &httpSimplePost{
rawTransSent: false,
rawTransReceived: false,
userAgentIndex: rand.Intn(len(requestUserAgent)),
getOrPost: true,
}
return t
}
func (t *httpSimplePost) SetServerInfo(s *ssr.ServerInfoForObfs) {
t.ServerInfoForObfs = *s
}
func (t *httpSimplePost) GetServerInfo() (s *ssr.ServerInfoForObfs) {
return &t.ServerInfoForObfs
}
func (t *httpSimplePost) SetData(data interface{}) {
}
func (t *httpSimplePost) GetData() interface{} {
return nil
}
func (t *httpSimplePost) boundary() (ret string) {
set := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
for i := 0; i < 32; i++ {
ret = fmt.Sprintf("%s%c", ret, set[rand.Intn(len(set))])
}
return
}
func (t *httpSimplePost) data2URLEncode(data []byte) (ret string) {
for i := 0; i < len(data); i++ {
ret = fmt.Sprintf("%s%%%s", ret, hex.EncodeToString([]byte{data[i]}))
}
return
}
func (t *httpSimplePost) Encode(data []byte) (encodedData []byte, err error) {
if t.rawTransSent {
return data, nil
}
dataLength := len(data)
var headData []byte
if headSize := t.IVLen + t.HeadLen; dataLength-headSize > 64 {
headData = make([]byte, headSize+rand.Intn(64))
} else {
headData = make([]byte, dataLength)
}
copy(headData, data[0:len(headData)])
requestPathIndex := rand.Intn(len(requestPath)/2) * 2
host := t.Host
var customHead string
if len(t.Param) > 0 {
customHeads := strings.Split(t.Param, "#")
if len(customHeads) > 2 {
customHeads = customHeads[0:2]
}
param := t.Param
if len(customHeads) > 1 {
customHead = customHeads[1]
param = customHeads[0]
}
hosts := strings.Split(param, ",")
if len(hosts) > 0 {
host = strings.TrimSpace(hosts[rand.Intn(len(hosts))])
}
}
method := "GET /"
if !t.getOrPost {
method = "POST /"
}
httpBuf := fmt.Sprintf("%s%s%s%s HTTP/1.1\r\nHost: %s:%d\r\n",
method,
requestPath[requestPathIndex],
t.data2URLEncode(headData),
requestPath[requestPathIndex+1],
host,
t.Port)
if len(customHead) > 0 {
httpBuf = httpBuf + strings.Replace(customHead, "\\n", "\r\n", -1) + "\r\n\r\n"
} else {
var contentType string
if !t.getOrPost {
contentType = "Content-Type: multipart/form-data; boundary=" + t.boundary() + "\r\n"
}
httpBuf = httpBuf +
"User-Agent: " + requestUserAgent[t.userAgentIndex] + "\r\n" +
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" +
"Accept-Language: en-US,en;q=0.8\r\n" +
"Accept-Encoding: gzip, deflate\r\n" +
contentType +
"DNT: 1\r\n" +
"Connection: keep-alive\r\n" +
"\r\n"
}
if len(headData) < dataLength {
encodedData = make([]byte, len(httpBuf)+(dataLength-len(headData)))
copy(encodedData, []byte(httpBuf))
copy(encodedData[len(httpBuf):], data[len(headData):])
} else {
encodedData = []byte(httpBuf)
}
t.rawTransSent = true
return
}
func (t *httpSimplePost) Decode(data []byte) ([]byte, uint64, error) {
if t.rawTransReceived {
return data, 0, nil
}
pos := bytes.Index(data, []byte("\r\n\r\n"))
if pos > 0 {
decodedData := make([]byte, len(data)-pos-4)
copy(decodedData, data[pos+4:])
t.rawTransReceived = true
return decodedData, 0, nil
}
return nil, 0, nil
}
+42
View File
@@ -0,0 +1,42 @@
package obfs
import (
"github.com/sun8911879/shadowsocksR/ssr"
)
func init() {
register("plain", newPlainObfs)
}
type plain struct {
ssr.ServerInfoForObfs
}
func newPlainObfs() IObfs {
p := &plain{}
return p
}
func (p *plain) SetServerInfo(s *ssr.ServerInfoForObfs) {
p.ServerInfoForObfs = *s
}
func (p *plain) GetServerInfo() (s *ssr.ServerInfoForObfs) {
return &p.ServerInfoForObfs
}
func (p *plain) Encode(data []byte) (encodedData []byte, err error) {
return data, nil
}
func (p *plain) Decode(data []byte) ([]byte, uint64, error) {
return data, 0, nil
}
func (p *plain) SetData(data interface{}) {
}
func (p *plain) GetData() interface{} {
return nil
}
+79
View File
@@ -0,0 +1,79 @@
package obfs
import (
"math/rand"
"github.com/sun8911879/shadowsocksR/ssr"
)
type randomHead struct {
ssr.ServerInfoForObfs
rawTransSent bool
rawTransReceived bool
hasSentHeader bool
dataBuffer []byte
}
func init() {
register("random_head", newRandomHead)
}
func newRandomHead() IObfs {
p := &randomHead{}
return p
}
func (r *randomHead) SetServerInfo(s *ssr.ServerInfoForObfs) {
r.ServerInfoForObfs = *s
}
func (r *randomHead) GetServerInfo() (s *ssr.ServerInfoForObfs) {
return &r.ServerInfoForObfs
}
func (r *randomHead) SetData(data interface{}) {
}
func (r *randomHead) GetData() interface{} {
return nil
}
func (r *randomHead) Encode(data []byte) (encodedData []byte, err error) {
if r.rawTransSent {
return data, nil
}
dataLength := len(data)
if r.hasSentHeader {
if dataLength > 0 {
d := make([]byte, len(r.dataBuffer)+dataLength)
copy(d, r.dataBuffer)
copy(d[len(r.dataBuffer):], data)
r.dataBuffer = d
} else {
encodedData = r.dataBuffer
r.dataBuffer = nil
r.rawTransSent = true
}
} else {
size := rand.Intn(96) + 8
encodedData = make([]byte, size)
rand.Read(encodedData)
ssr.SetCRC32(encodedData, size)
d := make([]byte, dataLength)
copy(d, data)
r.dataBuffer = d
}
r.hasSentHeader = true
return
}
func (r *randomHead) Decode(data []byte) ([]byte, uint64, error) {
if r.rawTransReceived {
return data, 0, nil
}
r.rawTransReceived = true
return data, 0, nil
}
+279
View File
@@ -0,0 +1,279 @@
package obfs
import (
"crypto/hmac"
"encoding/binary"
"fmt"
"math/rand"
"strings"
"time"
"github.com/sun8911879/shadowsocksR/ssr"
"github.com/sun8911879/shadowsocksR/tools"
)
func init() {
register("tls1.2_ticket_auth", newTLS12TicketAuth)
}
type tlsAuthData struct {
localClientID [32]byte
}
// tls12TicketAuth tls1.2_ticket_auth obfs encapsulate
type tls12TicketAuth struct {
ssr.ServerInfoForObfs
data *tlsAuthData
sendID int
handshakeStatus int
sendBuffer []byte
}
// newTLS12TicketAuth create a tlv1.2_ticket_auth object
func newTLS12TicketAuth() IObfs {
return &tls12TicketAuth{}
}
func (t *tls12TicketAuth) SetServerInfo(s *ssr.ServerInfoForObfs) {
t.ServerInfoForObfs = *s
}
func (t *tls12TicketAuth) GetServerInfo() (s *ssr.ServerInfoForObfs) {
return &t.ServerInfoForObfs
}
func (t *tls12TicketAuth) SetData(data interface{}) {
if auth, ok := data.(*tlsAuthData); ok {
t.data = auth
}
}
func (t *tls12TicketAuth) GetData() interface{} {
if t.data == nil {
t.data = &tlsAuthData{}
b := make([]byte, 32)
rand.Read(b)
copy(t.data.localClientID[:], b)
}
return t.data
}
func (t *tls12TicketAuth) getHost() string {
host := t.Host
if len(t.Param) > 0 {
hosts := strings.Split(t.Param, ",")
if len(hosts) > 0 {
host = hosts[rand.Intn(len(hosts))]
host = strings.TrimSpace(host)
}
}
if len(host) > 0 && host[len(host)-1] >= byte('0') && host[len(host)-1] <= byte('9') && len(t.Param) == 0 {
host = ""
}
return host
}
func (t *tls12TicketAuth) Encode(data []byte) (encodedData []byte, err error) {
if t.handshakeStatus == -1 {
return data, nil
}
dataLength := len(data)
if t.handshakeStatus == 8 {
encodedData = make([]byte, dataLength+4096)
start := 0
outLength := 0
for t.sendID <= 4 && dataLength-start > 256 {
length := rand.Intn(512) + 64
if length > dataLength-start {
length = dataLength - start
}
copy(encodedData[outLength:], []byte{0x17, 0x3, 0x3})
binary.BigEndian.PutUint16(encodedData[outLength+3:], uint16(length&0xFFFF))
copy(encodedData[outLength+5:], data[start:start+length])
start += length
outLength += length + 5
t.sendID++
}
for dataLength-start > 2048 {
length := rand.Intn(3990) + 100
if length > dataLength-start {
length = dataLength - start
}
copy(encodedData[outLength:], []byte{0x17, 0x3, 0x3})
binary.BigEndian.PutUint16(encodedData[outLength+3:], uint16(length&0xFFFF))
copy(encodedData[outLength+5:], data[start:start+length])
start += length
outLength += length + 5
t.sendID++
}
if dataLength-start > 0 {
length := dataLength - start
copy(encodedData[outLength:], []byte{0x17, 0x3, 0x3})
binary.BigEndian.PutUint16(encodedData[outLength+3:], uint16(length&0xFFFF))
copy(encodedData[outLength+5:], data[start:start+length])
// not necessary to update variable *start* any more
outLength += length + 5
t.sendID++
}
encodedData = encodedData[:outLength]
return
}
if t.handshakeStatus == 1 {
//outLength := 0
if dataLength > 0 {
b := make([]byte, len(t.sendBuffer)+dataLength+5)
copy(b, t.sendBuffer)
copy(b[len(t.sendBuffer):], []byte{0x17, 0x3, 0x3})
binary.BigEndian.PutUint16(b[len(t.sendBuffer)+3:], uint16(dataLength&0xFFFF))
copy(b[len(t.sendBuffer)+5:], data)
t.sendBuffer = b
return []byte{}, nil
}
hmacData := make([]byte, 43)
rnd := make([]byte, 22)
rand.Read(rnd)
handshakeFinish := []byte("\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00\x20")
copy(hmacData, handshakeFinish)
copy(hmacData[len(handshakeFinish):], rnd)
h := t.hmacSHA1(hmacData[:33])
copy(hmacData[33:], h)
encodedData = make([]byte, len(hmacData)+len(t.sendBuffer))
copy(encodedData, hmacData)
copy(encodedData[len(hmacData):], t.sendBuffer)
t.sendBuffer = nil
t.handshakeStatus = 8
return
}
rnd := t.packAuthData()
tlsData0 := []byte("\x00\x1c\xc0\x2b\xc0\x2f\xcc\xa9\xcc\xa8\xcc\x14\xcc\x13\xc0\x0a\xc0\x14\xc0\x09\xc0\x13\x00\x9c\x00\x35\x00\x2f\x00\x0a\x01\x00")
tlsData1 := []byte("\xff\x01\x00\x01\x00")
tlsData2 := []byte("\x00\x17\x00\x00\x00\x23\x00\xd0")
tlsData3 := []byte("\x00\x0d\x00\x16\x00\x14\x06\x01\x06\x03\x05\x01\x05\x03\x04\x01\x04\x03\x03\x01\x03\x03\x02\x01\x02\x03\x00\x05\x00\x05\x01\x00\x00\x00\x00\x00\x12\x00\x00\x75\x50\x00\x00\x00\x0b\x00\x02\x01\x00\x00\x0a\x00\x06\x00\x04\x00\x17\x00\x18" +
"\x00\x15\x00\x66\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
var sslBuf []byte
sslBuf = append(sslBuf, rnd...)
sslBuf = append(sslBuf, byte(32))
sslBuf = append(sslBuf, t.data.localClientID[:]...)
sslBuf = append(sslBuf, tlsData0...)
var extBuf []byte
extBuf = append(extBuf, tlsData1...)
host := t.getHost()
extBuf = append(extBuf, t.sni(host)...)
extBuf = append(extBuf, tlsData2...)
ticket := make([]byte, 208)
rand.Read(ticket)
extBuf = append(extBuf, ticket...)
extBuf = append(extBuf, tlsData3...)
extBuf = append([]byte{byte(len(extBuf) / 256), byte(len(extBuf) % 256)}, extBuf...)
sslBuf = append(sslBuf, extBuf...)
// client version
sslBuf = append([]byte{3, 3}, sslBuf...)
// length
sslBuf = append([]byte{1, 0, byte(len(sslBuf) / 256), byte(len(sslBuf) % 256)}, sslBuf...)
// length
sslBuf = append([]byte{byte(len(sslBuf) / 256), byte(len(sslBuf) % 256)}, sslBuf...)
// version
sslBuf = append([]byte{0x16, 3, 1}, sslBuf...)
encodedData = sslBuf
d := make([]byte, dataLength+5)
copy(d[0:], []byte{0x17, 0x3, 0x3})
binary.BigEndian.PutUint16(d[3:], uint16(dataLength&0xFFFF))
copy(d[5:], data)
b := make([]byte, len(t.sendBuffer)+len(d))
copy(b, t.sendBuffer)
copy(b[len(t.sendBuffer):], d)
t.sendBuffer = b
t.handshakeStatus = 1
return
}
func (t *tls12TicketAuth) Decode(data []byte) ([]byte, uint64, error) {
if t.handshakeStatus == -1 {
return data, 0, nil
}
dataLength := len(data)
if t.handshakeStatus == 8 {
if dataLength < 5 {
return nil, 5, fmt.Errorf("data need minimum length: 5 ,data only length: %d", dataLength)
}
if data[0] != 0x17 {
return nil, 0, ssr.ErrTLS12TicketAuthIncorrectMagicNumber
}
size := int(binary.BigEndian.Uint16(data[3:5]))
if size+5 > dataLength {
return nil, uint64(size + 5), fmt.Errorf("unexpected data length: %d ,data only length: %d", size+5, dataLength)
}
if dataLength == size+5 {
return data[5:], 0, nil
}
return data[5 : 5+size], uint64(size + 5), nil
}
if dataLength < 11+32+1+32 {
return nil, 0, ssr.ErrTLS12TicketAuthTooShortData
}
hash := t.hmacSHA1(data[11 : 11+22])
if !hmac.Equal(data[33:33+ssr.ObfsHMACSHA1Len], hash) {
return nil, 0, ssr.ErrTLS12TicketAuthHMACError
}
return nil, 1, nil
}
func (t *tls12TicketAuth) packAuthData() (outData []byte) {
outSize := 32
outData = make([]byte, outSize)
now := time.Now().Unix()
binary.BigEndian.PutUint32(outData[0:4], uint32(now))
rand.Read(outData[4 : 4+18])
hash := t.hmacSHA1(outData[:outSize-ssr.ObfsHMACSHA1Len])
copy(outData[outSize-ssr.ObfsHMACSHA1Len:], hash)
return
}
func (t *tls12TicketAuth) hmacSHA1(data []byte) []byte {
key := make([]byte, t.KeyLen+32)
copy(key, t.Key)
copy(key[t.KeyLen:], t.data.localClientID[:])
sha1Data := tools.HmacSHA1(key, data)
return sha1Data[:ssr.ObfsHMACSHA1Len]
}
func (t *tls12TicketAuth) sni(u string) []byte {
bURL := []byte(u)
length := len(bURL)
ret := make([]byte, length+9)
copy(ret[9:9+length], bURL)
binary.BigEndian.PutUint16(ret[7:], uint16(length&0xFFFF))
length += 3
binary.BigEndian.PutUint16(ret[4:], uint16(length&0xFFFF))
length += 2
binary.BigEndian.PutUint16(ret[2:], uint16(length&0xFFFF))
return ret
}
+282
View File
@@ -0,0 +1,282 @@
package protocol
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"encoding/binary"
"math/rand"
"strconv"
"strings"
"time"
"github.com/sun8911879/shadowsocksR/ssr"
"github.com/sun8911879/shadowsocksR/tools"
)
type hmacMethod func(key []byte, data []byte) []byte
type hashDigestMethod func(data []byte) []byte
func init() {
register("auth_aes128_md5", NewAuthAES128MD5)
}
func NewAuthAES128MD5() IProtocol {
a := &authAES128{
salt: "auth_aes128_md5",
hmac: tools.HmacMD5,
hashDigest: tools.MD5Sum,
packID: 1,
recvInfo: recvInfo{
recvID: 1,
buffer: bytes.NewBuffer(nil),
},
data: &authData{
connectionID: 0xFF000001,
},
}
return a
}
type recvInfo struct {
recvID uint32
buffer *bytes.Buffer
}
type authAES128 struct {
ssr.ServerInfoForObfs
recvInfo
data *authData
hasSentHeader bool
packID uint32
userKey []byte
salt string
hmac hmacMethod
hashDigest hashDigestMethod
}
func (a *authAES128) SetServerInfo(s *ssr.ServerInfoForObfs) {
a.ServerInfoForObfs = *s
}
func (a *authAES128) GetServerInfo() (s *ssr.ServerInfoForObfs) {
return &a.ServerInfoForObfs
}
func (a *authAES128) SetData(data interface{}) {
if auth, ok := data.(*authData); ok {
a.data = auth
}
}
func (a *authAES128) GetData() interface{} {
if a.data == nil {
a.data = &authData{}
}
return a.data
}
func (a *authAES128) packData(data []byte) (outData []byte) {
dataLength := len(data)
randLength := 1
if dataLength <= 1200 {
if a.packID > 4 {
randLength += rand.Intn(32)
} else {
if dataLength > 900 {
randLength += rand.Intn(128)
} else {
randLength += rand.Intn(512)
}
}
}
outLength := randLength + dataLength + 8
outData = make([]byte, outLength)
// 0~1, out length
binary.LittleEndian.PutUint16(outData[0:], uint16(outLength&0xFFFF))
// 2~3, hmac
key := make([]byte, len(a.userKey)+4)
copy(key, a.userKey)
binary.LittleEndian.PutUint32(key[len(key)-4:], a.packID)
h := a.hmac(key, outData[0:2])
copy(outData[2:4], h[:2])
// 4~rand length+4, rand number
rand.Read(outData[4 : 4+randLength])
// 4, rand length
if randLength < 128 {
outData[4] = byte(randLength & 0xFF)
} else {
// 4, magic number 0xFF
outData[4] = 0xFF
// 5~6, rand length
binary.LittleEndian.PutUint16(outData[5:], uint16(randLength&0xFFFF))
}
// rand length+4~out length-4, data
if dataLength > 0 {
copy(outData[randLength+4:], data)
}
a.packID++
h = a.hmac(key, outData[:outLength-4])
copy(outData[outLength-4:], h[:4])
return
}
func (a *authAES128) packAuthData(data []byte) (outData []byte) {
dataLength := len(data)
var randLength int
if dataLength > 400 {
randLength = rand.Intn(512)
} else {
randLength = rand.Intn(1024)
}
dataOffset := randLength + 16 + 4 + 4 + 7
outLength := dataOffset + dataLength + 4
outData = make([]byte, outLength)
encrypt := make([]byte, 24)
key := make([]byte, a.IVLen+a.KeyLen)
copy(key, a.IV)
copy(key[a.IVLen:], a.Key)
rand.Read(outData[dataOffset-randLength:])
if a.data.connectionID > 0xFF000000 {
a.data.clientID = nil
}
if len(a.data.clientID) == 0 {
a.data.clientID = make([]byte, 4)
rand.Read(a.data.clientID)
b := make([]byte, 4)
rand.Read(b)
a.data.connectionID = binary.LittleEndian.Uint32(b) & 0xFFFFFF
}
a.data.connectionID++
copy(encrypt[4:], a.data.clientID)
binary.LittleEndian.PutUint32(encrypt[8:], a.data.connectionID)
now := time.Now().Unix()
binary.LittleEndian.PutUint32(encrypt[0:4], uint32(now))
binary.LittleEndian.PutUint16(encrypt[12:], uint16(outLength&0xFFFF))
binary.LittleEndian.PutUint16(encrypt[14:], uint16(randLength&0xFFFF))
params := strings.Split(a.Param, ":")
uid := make([]byte, 4)
if len(params) >= 2 {
if userID, err := strconv.ParseUint(params[0], 10, 32); err != nil {
rand.Read(uid)
} else {
binary.LittleEndian.PutUint32(uid, uint32(userID))
a.userKey = a.hashDigest([]byte(params[1]))
}
} else {
rand.Read(uid)
}
if a.userKey == nil {
a.userKey = make([]byte, a.KeyLen)
copy(a.userKey, a.Key)
}
encryptKey := make([]byte, len(a.userKey))
copy(encryptKey, a.userKey)
aesCipherKey := tools.EVPBytesToKey(base64.StdEncoding.EncodeToString(encryptKey)+a.salt, 16)
block, err := aes.NewCipher(aesCipherKey)
if err != nil {
return nil
}
encryptData := make([]byte, 16)
iv := make([]byte, aes.BlockSize)
cbc := cipher.NewCBCEncrypter(block, iv)
cbc.CryptBlocks(encryptData, encrypt[0:16])
copy(encrypt[4:4+16], encryptData)
copy(encrypt[0:4], uid)
h := a.hmac(key, encrypt[0:20])
copy(encrypt[20:], h[:4])
rand.Read(outData[0:1])
h = a.hmac(key, outData[0:1])
copy(outData[1:], h[0:7-1])
copy(outData[7:], encrypt)
copy(outData[dataOffset:], data)
h = a.hmac(a.userKey, outData[0:outLength-4])
copy(outData[outLength-4:], h[:4])
return
}
func (a *authAES128) PreEncrypt(plainData []byte) (outData []byte, err error) {
dataLength := len(plainData)
offset := 0
if !a.hasSentHeader {
authLength := dataLength
if authLength > 1200 {
authLength = 1200
}
packData := a.packAuthData(plainData[:authLength])
a.hasSentHeader = true
outData = append(outData, packData...)
dataLength -= authLength
offset += authLength
}
const blockSize = 4096
for dataLength > blockSize {
packData := a.packData(plainData[offset : offset+blockSize])
outData = append(outData, packData...)
dataLength -= blockSize
offset += blockSize
}
if dataLength > 0 {
packData := a.packData(plainData[offset:])
outData = append(outData, packData...)
}
return
}
func (a *authAES128) PostDecrypt(plainData []byte) ([]byte, int, error) {
a.buffer.Reset()
plainLength := len(plainData)
datalength := plainLength
readlenth := 0
key := make([]byte, len(a.userKey)+4)
copy(key, a.userKey)
for plainLength > 4 {
binary.LittleEndian.PutUint32(key[len(key)-4:], a.recvID)
h := a.hmac(key, plainData[0:2])
if h[0] != plainData[2] || h[1] != plainData[3] {
return nil, 0, ssr.ErrAuthAES128HMACError
}
length := int(binary.LittleEndian.Uint16(plainData[0:2]))
if length >= 8192 || length < 8 {
return nil, 0, ssr.ErrAuthAES128DataLengthError
}
if length > plainLength {
break
}
a.recvID++
pos := int(plainData[4])
if pos < 255 {
pos += 4
} else {
pos = int(binary.LittleEndian.Uint16(plainData[5:7])) + 4
}
a.buffer.Write(plainData[pos : length-4])
plainData = plainData[length:]
plainLength -= length
readlenth += length
}
if datalength == readlenth {
readlenth = -1
}
return a.buffer.Bytes(), readlenth, nil
}
+28
View File
@@ -0,0 +1,28 @@
package protocol
import (
"bytes"
"github.com/sun8911879/shadowsocksR/tools"
)
func init() {
register("auth_aes128_sha1", NewAuthAES128SHA1)
}
func NewAuthAES128SHA1() IProtocol {
a := &authAES128{
salt: "auth_aes128_sha1",
hmac: tools.HmacSHA1,
hashDigest: tools.SHA1Sum,
packID: 1,
recvInfo: recvInfo{
recvID: 1,
buffer: bytes.NewBuffer(nil),
},
data: &authData{
connectionID: 0xFF000001,
},
}
return a
}
+232
View File
@@ -0,0 +1,232 @@
package protocol
import (
"encoding/binary"
"math/rand"
"time"
"github.com/sun8911879/shadowsocksR/ssr"
"github.com/sun8911879/shadowsocksR/tools"
)
func init() {
register("auth_sha1_v4", NewAuthSHA1v4)
}
type authSHA1v4 struct {
ssr.ServerInfoForObfs
data *authData
hasSentHeader bool
recvBuffer []byte
recvBufferLength int
}
func NewAuthSHA1v4() IProtocol {
a := &authSHA1v4{}
return a
}
func (a *authSHA1v4) SetServerInfo(s *ssr.ServerInfoForObfs) {
a.ServerInfoForObfs = *s
}
func (a *authSHA1v4) GetServerInfo() (s *ssr.ServerInfoForObfs) {
return &a.ServerInfoForObfs
}
func (a *authSHA1v4) SetData(data interface{}) {
if auth, ok := data.(*authData); ok {
a.data = auth
}
}
func (a *authSHA1v4) GetData() interface{} {
if a.data == nil {
a.data = &authData{}
}
return a.data
}
func (a *authSHA1v4) packData(data []byte) (outData []byte) {
dataLength := len(data)
randLength := 1
if dataLength <= 1300 {
if dataLength > 400 {
randLength += rand.Intn(128)
} else {
randLength += rand.Intn(1024)
}
}
outLength := randLength + dataLength + 8
outData = make([]byte, outLength)
// 0~1, out length
binary.BigEndian.PutUint16(outData[0:2], uint16(outLength&0xFFFF))
// 2~3, crc of out length
crc32 := ssr.CalcCRC32(outData, 2, 0xFFFFFFFF)
binary.LittleEndian.PutUint16(outData[2:4], uint16(crc32&0xFFFF))
// 4~rand length+4, rand number
rand.Read(outData[4 : 4+randLength])
// 4, rand length
if randLength < 128 {
outData[4] = byte(randLength & 0xFF)
} else {
// 4, magic number 0xFF
outData[4] = 0xFF
// 5~6, rand length
binary.BigEndian.PutUint16(outData[5:], uint16(randLength&0xFFFF))
}
// rand length+4~out length-4, data
if dataLength > 0 {
copy(outData[randLength+4:], data)
}
// out length-4~end, adler32 of full data
adler := ssr.CalcAdler32(outData[:outLength-4])
binary.LittleEndian.PutUint32(outData[outLength-4:], adler)
return outData
}
func (a *authSHA1v4) packAuthData(data []byte) (outData []byte) {
dataLength := len(data)
randLength := 1
if dataLength <= 1300 {
if dataLength > 400 {
randLength += rand.Intn(128)
} else {
randLength += rand.Intn(1024)
}
}
dataOffset := randLength + 4 + 2
outLength := dataOffset + dataLength + 12 + ssr.ObfsHMACSHA1Len
outData = make([]byte, outLength)
a.data.connectionID++
if a.data.connectionID > 0xFF000000 {
a.data.clientID = nil
}
if len(a.data.clientID) == 0 {
a.data.clientID = make([]byte, 8)
rand.Read(a.data.clientID)
b := make([]byte, 4)
rand.Read(b)
a.data.connectionID = binary.LittleEndian.Uint32(b) & 0xFFFFFF
}
// 0-1, out length
binary.BigEndian.PutUint16(outData[0:], uint16(outLength&0xFFFF))
// 2~6, crc of out length+salt+key
salt := []byte("auth_sha1_v4")
crcData := make([]byte, len(salt)+a.KeyLen+2)
copy(crcData[0:2], outData[0:2])
copy(crcData[2:], salt)
copy(crcData[2+len(salt):], a.Key)
crc32 := ssr.CalcCRC32(crcData, len(crcData), 0xFFFFFFFF)
// 2~6, crc of out length+salt+key
binary.LittleEndian.PutUint32(outData[2:], crc32)
// 6~rand length+6, rand numbers
rand.Read(outData[dataOffset-randLength : dataOffset])
// 6, rand length
if randLength < 128 {
outData[6] = byte(randLength & 0xFF)
} else {
// 6, magic number 0xFF
outData[6] = 0xFF
// 7-8, rand length
binary.BigEndian.PutUint16(outData[7:], uint16(randLength&0xFFFF))
}
// rand length+6~rand length+10, time stamp
now := time.Now().Unix()
binary.LittleEndian.PutUint32(outData[dataOffset:dataOffset+4], uint32(now))
// rand length+10~rand length+14, client ID
copy(outData[dataOffset+4:dataOffset+4+4], a.data.clientID[0:4])
// rand length+14~rand length+18, connection ID
binary.LittleEndian.PutUint32(outData[dataOffset+8:dataOffset+8+4], a.data.connectionID)
// rand length+18~rand length+18+data length, data
copy(outData[dataOffset+12:], data)
key := make([]byte, a.IVLen+a.KeyLen)
copy(key, a.IV)
copy(key[a.IVLen:], a.Key)
h := tools.HmacSHA1(key, outData[:outLength-ssr.ObfsHMACSHA1Len])
// out length-10~out length/rand length+18+data length~end, hmac
copy(outData[outLength-ssr.ObfsHMACSHA1Len:], h[0:ssr.ObfsHMACSHA1Len])
return outData
}
func (a *authSHA1v4) PreEncrypt(plainData []byte) (outData []byte, err error) {
dataLength := len(plainData)
offset := 0
if !a.hasSentHeader && dataLength > 0 {
authLength := dataLength
if headSize := ssr.GetHeadSize(plainData, 30); headSize <= dataLength {
authLength = headSize
}
packData := a.packAuthData(plainData[:authLength])
a.hasSentHeader = true
outData = append(outData, packData...)
dataLength -= authLength
offset += authLength
}
const blockSize = 4096
for dataLength > blockSize {
packData := a.packData(plainData[offset : offset+blockSize])
outData = append(outData, packData...)
dataLength -= blockSize
offset += blockSize
}
if dataLength > 0 {
packData := a.packData(plainData[offset:])
outData = append(outData, packData...)
}
return
}
func (a *authSHA1v4) PostDecrypt(plainData []byte) ([]byte, int, error) {
var outData []byte
dataLength := len(plainData)
b := make([]byte, len(a.recvBuffer)+dataLength)
copy(b, a.recvBuffer)
copy(b[len(a.recvBuffer):], plainData)
a.recvBuffer = b
a.recvBufferLength = len(b)
for a.recvBufferLength > 4 {
crc32 := ssr.CalcCRC32(a.recvBuffer, 2, 0xFFFFFFFF)
if binary.LittleEndian.Uint16(a.recvBuffer[2:4]) != uint16(crc32&0xFFFF) {
return nil, 0, ssr.ErrAuthSHA1v4CRC32Error
}
length := int(binary.BigEndian.Uint16(a.recvBuffer[0:2]))
if length >= 8192 || length < 8 {
a.recvBufferLength = 0
a.recvBuffer = nil
return nil, 0, ssr.ErrAuthSHA1v4DataLengthError
}
if length > a.recvBufferLength {
break
}
if ssr.CheckAdler32(a.recvBuffer, length) {
pos := int(a.recvBuffer[4])
if pos != 0xFF {
pos += 4
} else {
pos = int(binary.BigEndian.Uint16(a.recvBuffer[5:5+2])) + 4
}
outLength := length - pos - 4
b = make([]byte, len(outData)+outLength)
copy(b, outData)
copy(b[len(outData):], a.recvBuffer[pos:pos+outLength])
outData = b
a.recvBufferLength -= length
a.recvBuffer = a.recvBuffer[length:]
} else {
a.recvBufferLength = 0
a.recvBuffer = nil
return nil, 0, ssr.ErrAuthSHA1v4IncorrectChecksum
}
}
return outData, 0, nil
}
+39
View File
@@ -0,0 +1,39 @@
package protocol
import (
"strings"
"github.com/sun8911879/shadowsocksR/ssr"
)
type creator func() IProtocol
var (
creatorMap = make(map[string]creator)
)
type IProtocol interface {
SetServerInfo(s *ssr.ServerInfoForObfs)
GetServerInfo() *ssr.ServerInfoForObfs
PreEncrypt(data []byte) ([]byte, error)
PostDecrypt(data []byte) ([]byte, int, error)
SetData(data interface{})
GetData() interface{}
}
type authData struct {
clientID []byte
connectionID uint32
}
func register(name string, c creator) {
creatorMap[name] = c
}
func NewProtocol(name string) IProtocol {
c, ok := creatorMap[strings.ToLower(name)]
if ok {
return c()
}
return nil
}
+42
View File
@@ -0,0 +1,42 @@
package protocol
import (
"github.com/sun8911879/shadowsocksR/ssr"
)
func init() {
register("origin", NewOrigin)
}
type origin struct {
ssr.ServerInfoForObfs
}
func NewOrigin() IProtocol {
a := &origin{}
return a
}
func (o *origin) SetServerInfo(s *ssr.ServerInfoForObfs) {
o.ServerInfoForObfs = *s
}
func (o *origin) GetServerInfo() (s *ssr.ServerInfoForObfs) {
return &o.ServerInfoForObfs
}
func (o *origin) PreEncrypt(data []byte) (encryptedData []byte, err error) {
return data, nil
}
func (o *origin) PostDecrypt(data []byte) ([]byte, int, error) {
return data, 0, nil
}
func (o *origin) SetData(data interface{}) {
}
func (o *origin) GetData() interface{} {
return nil
}
+101
View File
@@ -0,0 +1,101 @@
package protocol
import (
"bytes"
"encoding/binary"
"github.com/sun8911879/shadowsocksR/ssr"
"github.com/sun8911879/shadowsocksR/tools"
)
func init() {
register("verify_sha1", NewVerifySHA1)
register("ota", NewVerifySHA1)
}
type verifySHA1 struct {
ssr.ServerInfoForObfs
hasSentHeader bool
chunkId uint32
}
const (
oneTimeAuthMask byte = 0x10
)
func NewVerifySHA1() IProtocol {
a := &verifySHA1{}
return a
}
func (v *verifySHA1) otaConnectAuth(data []byte) []byte {
return append(data, tools.HmacSHA1(append(v.IV, v.Key...), data)...)
}
func (v *verifySHA1) otaReqChunkAuth(chunkId uint32, data []byte) []byte {
nb := make([]byte, 2)
binary.BigEndian.PutUint16(nb, uint16(len(data)))
chunkIdBytes := make([]byte, 4)
binary.BigEndian.PutUint32(chunkIdBytes, chunkId)
header := append(nb, tools.HmacSHA1(append(v.IV, chunkIdBytes...), data)...)
return append(header, data...)
}
func (v *verifySHA1) otaVerifyAuth(iv []byte, chunkId uint32, data []byte, expectedHmacSha1 []byte) bool {
chunkIdBytes := make([]byte, 4)
binary.BigEndian.PutUint32(chunkIdBytes, chunkId)
actualHmacSha1 := tools.HmacSHA1(append(iv, chunkIdBytes...), data)
return bytes.Equal(expectedHmacSha1, actualHmacSha1)
}
func (v *verifySHA1) getAndIncreaseChunkId() (chunkId uint32) {
chunkId = v.chunkId
v.chunkId += 1
return
}
func (v *verifySHA1) SetServerInfo(s *ssr.ServerInfoForObfs) {
v.ServerInfoForObfs = *s
}
func (v *verifySHA1) GetServerInfo() (s *ssr.ServerInfoForObfs) {
return &v.ServerInfoForObfs
}
func (v *verifySHA1) SetData(data interface{}) {
}
func (v *verifySHA1) GetData() interface{} {
return nil
}
func (v *verifySHA1) PreEncrypt(data []byte) (encryptedData []byte, err error) {
dataLength := len(data)
offset := 0
if !v.hasSentHeader {
data[0] |= oneTimeAuthMask
encryptedData = v.otaConnectAuth(data[:v.HeadLen])
v.hasSentHeader = true
dataLength -= v.HeadLen
offset += v.HeadLen
}
const blockSize = 4096
for dataLength > blockSize {
chunkId := v.getAndIncreaseChunkId()
b := v.otaReqChunkAuth(chunkId, data[offset:offset+blockSize])
encryptedData = append(encryptedData, b...)
dataLength -= blockSize
offset += blockSize
}
if dataLength > 0 {
chunkId := v.getAndIncreaseChunkId()
b := v.otaReqChunkAuth(chunkId, data[offset:])
encryptedData = append(encryptedData, b...)
}
return
}
func (v *verifySHA1) PostDecrypt(data []byte) ([]byte, int, error) {
return data, 0, nil
}
+31
View File
@@ -0,0 +1,31 @@
package ssr
import "encoding/binary"
func calcShortAdler32(input []byte, a, b uint32) (uint32, uint32) {
for _, i := range input {
a += uint32(i)
b += a
}
a %= 65521
b %= 65521
return a, b
}
func CalcAdler32(input []byte) uint32 {
var a uint32 = 1
var b uint32 = 0
const nMax = 5552
for length := len(input); length > nMax; length -= nMax {
a, b = calcShortAdler32(input[:nMax], a, b)
input = input[nMax:]
}
a, b = calcShortAdler32(input, a, b)
return (b << 16) + a
}
func CheckAdler32(input []byte, l int) bool {
adler32 := CalcAdler32(input[:l-4])
checksum := binary.LittleEndian.Uint32(input[l-4:])
return adler32 == checksum
}
+52
View File
@@ -0,0 +1,52 @@
package ssr
import "encoding/binary"
var (
crc32Table = make([]uint32, 256)
)
func init() {
createCRC32Table()
}
func createCRC32Table() {
for i := 0; i < 256; i++ {
crc := uint32(i)
for j := 8; j > 0; j-- {
if crc&1 == 1 {
crc = (crc >> 1) ^ 0xEDB88320
} else {
crc >>= 1
}
}
crc32Table[i] = crc
}
}
func CalcCRC32(input []byte, length int, value uint32) uint32 {
value = 0xFFFFFFFF
return DoCalcCRC32(input, 0, length, value)
}
func DoCalcCRC32(input []byte, index int, length int, value uint32) uint32 {
buffer := input
for i := index; i < length; i++ {
value = (value >> 8) ^ crc32Table[byte(value&0xFF)^buffer[i]]
}
return value ^ 0xFFFFFFFF
}
func DoSetCRC32(buffer []byte, index int, length int) {
crc := CalcCRC32(buffer[:length-4], length-4, 0xFFFFFFFF)
binary.LittleEndian.PutUint32(buffer[length-4:], crc^0xFFFFFFFF)
}
func SetCRC32(buffer []byte, length int) {
DoSetCRC32(buffer, 0, length)
}
func CheckCRC32(buffer []byte, length int) bool {
crc := CalcCRC32(buffer, length, 0xFFFFFFFF)
return crc == 0xFFFFFFFF
}
+55
View File
@@ -0,0 +1,55 @@
package ssr
import "errors"
const ObfsHMACSHA1Len = 10
var (
ErrAuthSHA1v4CRC32Error = errors.New("auth_sha1_v4 post decrypt data crc32 error")
ErrAuthSHA1v4DataLengthError = errors.New("auth_sha1_v4 post decrypt data length error")
ErrAuthSHA1v4IncorrectChecksum = errors.New("auth_sha1_v4 post decrypt incorrect checksum")
ErrAuthAES128HMACError = errors.New("auth_aes128_* post decrypt hmac error")
ErrAuthAES128DataLengthError = errors.New("auth_aes128_* post decrypt length mismatch")
ErrAuthAES128IncorrectChecksum = errors.New("auth_aes128_* post decrypt incorrect checksum")
ErrTLS12TicketAuthTooShortData = errors.New("tls1.2_ticket_auth too short data")
ErrTLS12TicketAuthHMACError = errors.New("tls1.2_ticket_auth hmac verifying failed")
ErrTLS12TicketAuthIncorrectMagicNumber = errors.New("tls1.2_ticket_auth incorrect magic number")
)
type ServerInfoForObfs struct {
Host string
Port uint16
Param string
IV []byte
IVLen int
RecvIV []byte
RecvIVLen int
Key []byte
KeyLen int
HeadLen int
TcpMss int
}
func GetHeadSize(data []byte, defaultValue int) int {
if data == nil || len(data) < 2 {
return defaultValue
}
headType := data[0] & 0x07
switch headType {
case 1:
// IPv4 1+4+2
return 7
case 4:
// IPv6 1+16+2
return 19
case 3:
// domain name, variant length
return 4 + int(data[1])
}
return defaultValue
}
func (s *ServerInfoForObfs) SetHeadLen(data []byte, defaultValue int) {
s.HeadLen = GetHeadSize(data, defaultValue)
}
+251
View File
@@ -0,0 +1,251 @@
package shadowsocksr
import (
"bytes"
"fmt"
"net"
"sync"
"github.com/sun8911879/shadowsocksR/obfs"
"github.com/sun8911879/shadowsocksR/protocol"
"github.com/sun8911879/shadowsocksR/tools/leakybuf"
)
// SSTCPConn the struct that override the net.Conn methods
type SSTCPConn struct {
net.Conn
sync.RWMutex
*StreamCipher
IObfs obfs.IObfs
IProtocol protocol.IProtocol
readBuf []byte
readDecodeBuf *bytes.Buffer
readIObfsBuf *bytes.Buffer
readEncryptBuf *bytes.Buffer
readIndex uint64
readUserBuf *bytes.Buffer
writeBuf []byte
lastReadError error
}
func NewSSTCPConn(c net.Conn, cipher *StreamCipher) *SSTCPConn {
return &SSTCPConn{
Conn: c,
StreamCipher: cipher,
readBuf: leakybuf.GlobalLeakyBuf.Get(),
readDecodeBuf: bytes.NewBuffer(nil),
readIObfsBuf: bytes.NewBuffer(nil),
readUserBuf: bytes.NewBuffer(nil),
readEncryptBuf: bytes.NewBuffer(nil),
writeBuf: leakybuf.GlobalLeakyBuf.Get(),
}
}
func (c *SSTCPConn) Close() error {
leakybuf.GlobalLeakyBuf.Put(c.readBuf)
leakybuf.GlobalLeakyBuf.Put(c.writeBuf)
return c.Conn.Close()
}
func (c *SSTCPConn) GetIv() (iv []byte) {
iv = make([]byte, len(c.iv))
copy(iv, c.iv)
return
}
func (c *SSTCPConn) GetKey() (key []byte) {
key = make([]byte, len(c.key))
copy(key, c.key)
return
}
func (c *SSTCPConn) initEncryptor(b []byte) (iv []byte, err error) {
if c.enc == nil {
iv, err = c.initEncrypt()
if err != nil {
return nil, err
}
// should initialize obfs/protocol now, because iv is ready now
obfsServerInfo := c.IObfs.GetServerInfo()
obfsServerInfo.SetHeadLen(b, 30)
obfsServerInfo.IV, obfsServerInfo.IVLen = c.IV()
obfsServerInfo.Key, obfsServerInfo.KeyLen = c.Key()
c.IObfs.SetServerInfo(obfsServerInfo)
protocolServerInfo := c.IProtocol.GetServerInfo()
protocolServerInfo.SetHeadLen(b, 30)
protocolServerInfo.IV, protocolServerInfo.IVLen = c.IV()
protocolServerInfo.Key, protocolServerInfo.KeyLen = c.Key()
c.IProtocol.SetServerInfo(protocolServerInfo)
}
return
}
func (c *SSTCPConn) Read(b []byte) (n int, err error) {
for {
n, err = c.doRead(b)
if b == nil || n != 0 || err != nil {
return n, err
}
}
}
func (c *SSTCPConn) doRead(b []byte) (n int, err error) {
//先吐出已经解密后数据
if c.readUserBuf.Len() > 0 {
return c.readUserBuf.Read(b)
}
//未读取够长度继续读取并解码
decodelength := c.readDecodeBuf.Len()
if (decodelength == 0 || c.readEncryptBuf.Len() > 0 || (c.readIndex != 0 && c.readIndex > uint64(decodelength))) && c.lastReadError == nil {
c.readIndex = 0
n, c.lastReadError = c.Conn.Read(c.readBuf)
//写入decode 缓存
c.readDecodeBuf.Write(c.readBuf[0:n])
}
//无缓冲数据返回错误
if c.lastReadError != nil && (decodelength == 0 || uint64(decodelength) < c.readIndex) {
return 0, c.lastReadError
}
decodelength = c.readDecodeBuf.Len()
decodebytes := c.readDecodeBuf.Bytes()
c.readDecodeBuf.Reset()
for {
decodedData, length, err := c.IObfs.Decode(decodebytes)
if length == 0 && err != nil {
return 0, err
}
//do send back
if length == 1 {
c.Write(make([]byte, 0))
return 0, nil
}
//数据不够长度
if err != nil {
if uint64(decodelength) >= length {
return 0, fmt.Errorf("data length: %d,decode data length: %d unknown panic", decodelength, length)
}
c.readIndex = length
c.readDecodeBuf.Write(decodebytes)
if c.readIObfsBuf.Len() == 0 {
return 0, nil
}
break
}
if length >= 1 {
//读出数据 但是有多余的数据 返回已经读取数值
c.readIObfsBuf.Write(decodedData)
decodebytes = decodebytes[length:]
decodelength = len(decodebytes)
continue
}
//完全读取数据 -- length == 0
c.readIObfsBuf.Write(decodedData)
break
}
decodedData := c.readIObfsBuf.Bytes()
decodelength = c.readIObfsBuf.Len()
c.readIObfsBuf.Reset()
if c.dec == nil {
iv := decodedData[0:c.info.ivLen]
if err = c.initDecrypt(iv); err != nil {
return 0, err
}
if len(c.iv) == 0 {
c.iv = iv
}
decodelength -= c.info.ivLen
if decodelength <= 0 {
return 0, nil
}
decodedData = decodedData[c.info.ivLen:]
}
buf := make([]byte, decodelength)
c.decrypt(buf, decodedData)
c.readEncryptBuf.Write(buf)
encryptbuf := c.readEncryptBuf.Bytes()
c.readEncryptBuf.Reset()
postDecryptedData, length, err := c.IProtocol.PostDecrypt(encryptbuf)
if err != nil {
return 0, err
}
if length == 0 {
c.readEncryptBuf.Write(encryptbuf)
return 0, nil
}
if length > 0 {
c.readEncryptBuf.Write(encryptbuf[length:])
}
postDecryptedlength := len(postDecryptedData)
blength := len(b)
copy(b, postDecryptedData)
if blength > postDecryptedlength {
return postDecryptedlength, nil
}
c.readUserBuf.Write(postDecryptedData[len(b):])
return blength, nil
}
func (c *SSTCPConn) preWrite(b []byte) (outData []byte, err error) {
var iv []byte
if iv, err = c.initEncryptor(b); err != nil {
return
}
var preEncryptedData []byte
preEncryptedData, err = c.IProtocol.PreEncrypt(b)
if err != nil {
return
}
preEncryptedDataLen := len(preEncryptedData)
//c.encrypt(cipherData[len(iv):], b)
encryptedData := make([]byte, preEncryptedDataLen)
//! \attention here the expected output buffer length MUST be accurate, it is preEncryptedDataLen now!
c.encrypt(encryptedData[0:preEncryptedDataLen], preEncryptedData)
//common.Info("len(b)=", len(b), ", b:", b,
// ", pre encrypted data length:", preEncryptedDataLen,
// ", pre encrypted data:", preEncryptedData,
// ", encrypted data length:", preEncryptedDataLen)
cipherData := c.writeBuf
dataSize := len(encryptedData) + len(iv)
if dataSize > len(cipherData) {
cipherData = make([]byte, dataSize)
} else {
cipherData = cipherData[:dataSize]
}
if iv != nil {
// Put initialization vector in buffer before be encoded
copy(cipherData, iv)
}
copy(cipherData[len(iv):], encryptedData)
return c.IObfs.Encode(cipherData)
}
func (c *SSTCPConn) Write(b []byte) (n int, err error) {
outData, err := c.preWrite(b)
if err == nil {
n, err = c.Conn.Write(outData)
if err != nil {
return n, err
}
}
return len(b), nil
}
+51
View File
@@ -0,0 +1,51 @@
package tools
import (
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
)
func HmacMD5(key []byte, data []byte) []byte {
hmacMD5 := hmac.New(md5.New, key)
hmacMD5.Write(data)
return hmacMD5.Sum(nil)[:10]
}
func HmacSHA1(key []byte, data []byte) []byte {
hmacSHA1 := hmac.New(sha1.New, key)
hmacSHA1.Write(data)
return hmacSHA1.Sum(nil)[:10]
}
func MD5Sum(d []byte) []byte {
h := md5.New()
h.Write(d)
return h.Sum(nil)
}
func SHA1Sum(d []byte) []byte {
h := sha1.New()
h.Write(d)
return h.Sum(nil)
}
func EVPBytesToKey(password string, keyLen int) (key []byte) {
const md5Len = 16
cnt := (keyLen-1)/md5Len + 1
m := make([]byte, cnt*md5Len)
copy(m, MD5Sum([]byte(password)))
// Repeatedly call md5 until bytes generated is enough.
// Each call to md5 uses data: prev md5 sum + password.
d := make([]byte, md5Len+len(password))
start := 0
for i := 1; i < cnt; i++ {
start += md5Len
copy(d, m[start-md5Len:start])
copy(d[md5Len:], password)
copy(m[start:], MD5Sum(d))
}
return m[:keyLen]
}
+47
View File
@@ -0,0 +1,47 @@
// Provides leaky buffer, based on the example in Effective Go.
package leakybuf
type LeakyBuf struct {
bufSize int // size of each buffer
freeList chan []byte
}
// NewLeakyBuf creates a leaky buffer which can hold at most n buffer, each
// with bufSize bytes.
func NewLeakyBuf(n, bufSize int) *LeakyBuf {
return &LeakyBuf{
bufSize: bufSize,
freeList: make(chan []byte, n),
}
}
// Get returns a buffer from the leaky buffer or create a new buffer.
func (lb *LeakyBuf) Get() (b []byte) {
select {
case b = <-lb.freeList:
default:
b = make([]byte, lb.bufSize)
}
return
}
// Put add the buffer into the free buffer pool for reuse. Panic if the buffer
// size is not the same with the leaky buffer's. This is intended to expose
// error usage of leaky buffer.
func (lb *LeakyBuf) Put(b []byte) {
if len(b) != lb.bufSize {
panic("invalid buffer size that's put into leaky buffer")
}
select {
case lb.freeList <- b:
default:
}
return
}
const (
GlobalLeakyBufSize = 32 * 1024 // data.len(2) + hmacsha1(10) + data(4096)
maxNBuf = 8192
)
var GlobalLeakyBuf = NewLeakyBuf(maxNBuf, GlobalLeakyBufSize)