github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/proxy/shadowsocks/protocol.go (about) 1 // +build !confonly 2 3 package shadowsocks 4 5 import ( 6 "crypto/hmac" 7 "crypto/rand" 8 "crypto/sha256" 9 "hash" 10 "hash/crc32" 11 "io" 12 "io/ioutil" 13 "v2ray.com/core/common/dice" 14 15 "v2ray.com/core/common" 16 "v2ray.com/core/common/buf" 17 "v2ray.com/core/common/net" 18 "v2ray.com/core/common/protocol" 19 ) 20 21 const ( 22 Version = 1 23 ) 24 25 var addrParser = protocol.NewAddressParser( 26 protocol.AddressFamilyByte(0x01, net.AddressFamilyIPv4), 27 protocol.AddressFamilyByte(0x04, net.AddressFamilyIPv6), 28 protocol.AddressFamilyByte(0x03, net.AddressFamilyDomain), 29 protocol.WithAddressTypeParser(func(b byte) byte { 30 return b & 0x0F 31 }), 32 ) 33 34 // ReadTCPSession reads a Shadowsocks TCP session from the given reader, returns its header and remaining parts. 35 func ReadTCPSession(user *protocol.MemoryUser, reader io.Reader) (*protocol.RequestHeader, buf.Reader, error) { 36 account := user.Account.(*MemoryAccount) 37 38 hashkdf := hmac.New(func() hash.Hash { return sha256.New() }, []byte("SSBSKDF")) 39 hashkdf.Write(account.Key) 40 41 behaviorSeed := crc32.ChecksumIEEE(hashkdf.Sum(nil)) 42 43 behaviorRand := dice.NewDeterministicDice(int64(behaviorSeed)) 44 BaseDrainSize := behaviorRand.Roll(3266) 45 RandDrainMax := behaviorRand.Roll(64) + 1 46 RandDrainRolled := dice.Roll(RandDrainMax) 47 DrainSize := BaseDrainSize + 16 + 38 + RandDrainRolled 48 readSizeRemain := DrainSize 49 50 buffer := buf.New() 51 defer buffer.Release() 52 53 ivLen := account.Cipher.IVSize() 54 var iv []byte 55 if ivLen > 0 { 56 if _, err := buffer.ReadFullFrom(reader, ivLen); err != nil { 57 readSizeRemain -= int(buffer.Len()) 58 DrainConnN(reader, readSizeRemain) 59 return nil, nil, newError("failed to read IV").Base(err) 60 } 61 62 iv = append([]byte(nil), buffer.BytesTo(ivLen)...) 63 } 64 65 r, err := account.Cipher.NewDecryptionReader(account.Key, iv, reader) 66 if err != nil { 67 readSizeRemain -= int(buffer.Len()) 68 DrainConnN(reader, readSizeRemain) 69 return nil, nil, newError("failed to initialize decoding stream").Base(err).AtError() 70 } 71 br := &buf.BufferedReader{Reader: r} 72 73 request := &protocol.RequestHeader{ 74 Version: Version, 75 User: user, 76 Command: protocol.RequestCommandTCP, 77 } 78 79 readSizeRemain -= int(buffer.Len()) 80 buffer.Clear() 81 82 addr, port, err := addrParser.ReadAddressPort(buffer, br) 83 if err != nil { 84 readSizeRemain -= int(buffer.Len()) 85 DrainConnN(reader, readSizeRemain) 86 return nil, nil, newError("failed to read address").Base(err) 87 } 88 89 request.Address = addr 90 request.Port = port 91 92 if request.Address == nil { 93 readSizeRemain -= int(buffer.Len()) 94 DrainConnN(reader, readSizeRemain) 95 return nil, nil, newError("invalid remote address.") 96 } 97 98 return request, br, nil 99 } 100 101 func DrainConnN(reader io.Reader, n int) error { 102 _, err := io.CopyN(ioutil.Discard, reader, int64(n)) 103 return err 104 } 105 106 // WriteTCPRequest writes Shadowsocks request into the given writer, and returns a writer for body. 107 func WriteTCPRequest(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) { 108 user := request.User 109 account := user.Account.(*MemoryAccount) 110 111 var iv []byte 112 if account.Cipher.IVSize() > 0 { 113 iv = make([]byte, account.Cipher.IVSize()) 114 common.Must2(rand.Read(iv)) 115 if err := buf.WriteAllBytes(writer, iv); err != nil { 116 return nil, newError("failed to write IV") 117 } 118 } 119 120 w, err := account.Cipher.NewEncryptionWriter(account.Key, iv, writer) 121 if err != nil { 122 return nil, newError("failed to create encoding stream").Base(err).AtError() 123 } 124 125 header := buf.New() 126 127 if err := addrParser.WriteAddressPort(header, request.Address, request.Port); err != nil { 128 return nil, newError("failed to write address").Base(err) 129 } 130 131 if err := w.WriteMultiBuffer(buf.MultiBuffer{header}); err != nil { 132 return nil, newError("failed to write header").Base(err) 133 } 134 135 return w, nil 136 } 137 138 func ReadTCPResponse(user *protocol.MemoryUser, reader io.Reader) (buf.Reader, error) { 139 account := user.Account.(*MemoryAccount) 140 141 var iv []byte 142 if account.Cipher.IVSize() > 0 { 143 iv = make([]byte, account.Cipher.IVSize()) 144 if _, err := io.ReadFull(reader, iv); err != nil { 145 return nil, newError("failed to read IV").Base(err) 146 } 147 } 148 149 return account.Cipher.NewDecryptionReader(account.Key, iv, reader) 150 } 151 152 func WriteTCPResponse(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) { 153 user := request.User 154 account := user.Account.(*MemoryAccount) 155 156 var iv []byte 157 if account.Cipher.IVSize() > 0 { 158 iv = make([]byte, account.Cipher.IVSize()) 159 common.Must2(rand.Read(iv)) 160 if err := buf.WriteAllBytes(writer, iv); err != nil { 161 return nil, newError("failed to write IV.").Base(err) 162 } 163 } 164 165 return account.Cipher.NewEncryptionWriter(account.Key, iv, writer) 166 } 167 168 func EncodeUDPPacket(request *protocol.RequestHeader, payload []byte) (*buf.Buffer, error) { 169 user := request.User 170 account := user.Account.(*MemoryAccount) 171 172 buffer := buf.New() 173 ivLen := account.Cipher.IVSize() 174 if ivLen > 0 { 175 common.Must2(buffer.ReadFullFrom(rand.Reader, ivLen)) 176 } 177 178 if err := addrParser.WriteAddressPort(buffer, request.Address, request.Port); err != nil { 179 return nil, newError("failed to write address").Base(err) 180 } 181 182 buffer.Write(payload) 183 184 if err := account.Cipher.EncodePacket(account.Key, buffer); err != nil { 185 return nil, newError("failed to encrypt UDP payload").Base(err) 186 } 187 188 return buffer, nil 189 } 190 191 func DecodeUDPPacket(user *protocol.MemoryUser, payload *buf.Buffer) (*protocol.RequestHeader, *buf.Buffer, error) { 192 account := user.Account.(*MemoryAccount) 193 194 var iv []byte 195 if !account.Cipher.IsAEAD() && account.Cipher.IVSize() > 0 { 196 // Keep track of IV as it gets removed from payload in DecodePacket. 197 iv = make([]byte, account.Cipher.IVSize()) 198 copy(iv, payload.BytesTo(account.Cipher.IVSize())) 199 } 200 201 if err := account.Cipher.DecodePacket(account.Key, payload); err != nil { 202 return nil, nil, newError("failed to decrypt UDP payload").Base(err) 203 } 204 205 request := &protocol.RequestHeader{ 206 Version: Version, 207 User: user, 208 Command: protocol.RequestCommandUDP, 209 } 210 211 payload.SetByte(0, payload.Byte(0)&0x0F) 212 213 addr, port, err := addrParser.ReadAddressPort(nil, payload) 214 if err != nil { 215 return nil, nil, newError("failed to parse address").Base(err) 216 } 217 218 request.Address = addr 219 request.Port = port 220 221 return request, payload, nil 222 } 223 224 type UDPReader struct { 225 Reader io.Reader 226 User *protocol.MemoryUser 227 } 228 229 func (v *UDPReader) ReadMultiBuffer() (buf.MultiBuffer, error) { 230 buffer := buf.New() 231 _, err := buffer.ReadFrom(v.Reader) 232 if err != nil { 233 buffer.Release() 234 return nil, err 235 } 236 _, payload, err := DecodeUDPPacket(v.User, buffer) 237 if err != nil { 238 buffer.Release() 239 return nil, err 240 } 241 return buf.MultiBuffer{payload}, nil 242 } 243 244 type UDPWriter struct { 245 Writer io.Writer 246 Request *protocol.RequestHeader 247 } 248 249 // Write implements io.Writer. 250 func (w *UDPWriter) Write(payload []byte) (int, error) { 251 packet, err := EncodeUDPPacket(w.Request, payload) 252 if err != nil { 253 return 0, err 254 } 255 _, err = w.Writer.Write(packet.Bytes()) 256 packet.Release() 257 return len(payload), err 258 }