| // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | package net |
| 16 |
| 17 | import ( |
| 18 | "context" |
| 19 | "crypto/sha256" |
| 20 | "errors" |
| 21 | "io" |
| 22 | "net" |
| 23 | "sync/atomic" |
| 24 | "time" |
| 25 |
| 26 | libcrypto "github.com/fatedier/golib/crypto" |
| 27 | quic "github.com/quic-go/quic-go" |
| 28 | "golang.org/x/crypto/hkdf" |
| 29 |
| 30 | "github.com/fatedier/frp/pkg/util/xlog" |
| 31 | ) |
| 32 |
| 33 | type ContextGetter interface { |
| 34 | Context() context.Context |
| 35 | } |
| 36 |
| 37 | type ContextSetter interface { |
| 38 | WithContext(ctx context.Context) |
| 39 | } |
| 40 |
| 41 | func NewLogFromConn(conn net.Conn) *xlog.Logger { |
| 42 | if c, ok := conn.(ContextGetter); ok { |
| 43 | return xlog.FromContextSafe(c.Context()) |
| 44 | } |
| 45 | return xlog.New() |
| 46 | } |
| 47 |
| 48 | func NewContextFromConn(conn net.Conn) context.Context { |
| 49 | if c, ok := conn.(ContextGetter); ok { |
| 50 | return c.Context() |
| 51 | } |
| 52 | return context.Background() |
| 53 | } |
| 54 |
| 55 | // ContextConn is the connection with context |
| 56 | type ContextConn struct { |
| 57 | net.Conn |
| 58 |
| 59 | ctx context.Context |
| 60 | } |
| 61 |
| 62 | func NewContextConn(ctx context.Context, c net.Conn) *ContextConn { |
| 63 | return &ContextConn{ |
| 64 | Conn: c, |
| 65 | ctx: ctx, |
| 66 | } |
| 67 | } |
| 68 |
| 69 | func (c *ContextConn) WithContext(ctx context.Context) { |
| 70 | c.ctx = ctx |
| 71 | } |
| 72 |
| 73 | func (c *ContextConn) Context() context.Context { |
| 74 | return c.ctx |
| 75 | } |
| 76 |
| 77 | type WrapReadWriteCloserConn struct { |
| 78 | io.ReadWriteCloser |
| 79 |
| 80 | underConn net.Conn |
| 81 |
| 82 | remoteAddr net.Addr |
| 83 | } |
| 84 |
| 85 | func WrapReadWriteCloserToConn(rwc io.ReadWriteCloser, underConn net.Conn) *WrapReadWriteCloserConn { |
| 86 | return &WrapReadWriteCloserConn{ |
| 87 | ReadWriteCloser: rwc, |
| 88 | underConn: underConn, |
| 89 | } |
| 90 | } |
| 91 |
| 92 | func (conn *WrapReadWriteCloserConn) LocalAddr() net.Addr { |
| 93 | if conn.underConn != nil { |
| 94 | return conn.underConn.LocalAddr() |
| 95 | } |
| 96 | return (*net.TCPAddr)(nil) |
| 97 | } |
| 98 |
| 99 | func (conn *WrapReadWriteCloserConn) SetRemoteAddr(addr net.Addr) { |
| 100 | conn.remoteAddr = addr |
| 101 | } |
| 102 |
| 103 | func (conn *WrapReadWriteCloserConn) RemoteAddr() net.Addr { |
| 104 | if conn.remoteAddr != nil { |
| 105 | return conn.remoteAddr |
| 106 | } |
| 107 | if conn.underConn != nil { |
| 108 | return conn.underConn.RemoteAddr() |
| 109 | } |
| 110 | return (*net.TCPAddr)(nil) |
| 111 | } |
| 112 |
| 113 | func (conn *WrapReadWriteCloserConn) SetDeadline(t time.Time) error { |
| 114 | if conn.underConn != nil { |
| 115 | return conn.underConn.SetDeadline(t) |
| 116 | } |
| 117 | return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")} |
| 118 | } |
| 119 |
| 120 | func (conn *WrapReadWriteCloserConn) SetReadDeadline(t time.Time) error { |
| 121 | if conn.underConn != nil { |
| 122 | return conn.underConn.SetReadDeadline(t) |
| 123 | } |
| 124 | return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")} |
| 125 | } |
| 126 |
| 127 | func (conn *WrapReadWriteCloserConn) SetWriteDeadline(t time.Time) error { |
| 128 | if conn.underConn != nil { |
| 129 | return conn.underConn.SetWriteDeadline(t) |
| 130 | } |
| 131 | return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")} |
| 132 | } |
| 133 |
| 134 | type CloseNotifyConn struct { |
| 135 | net.Conn |
| 136 |
| 137 | // 1 means closed |
| 138 | closeFlag atomic.Int32 |
| 139 |
| 140 | closeFn func(error) |
| 141 | } |
| 142 |
| 143 | // closeFn will be only called once with the error (nil if Close() was called, non-nil if CloseWithError() was called) |
| 144 | func WrapCloseNotifyConn(c net.Conn, closeFn func(error)) *CloseNotifyConn { |
| 145 | return &CloseNotifyConn{ |
| 146 | Conn: c, |
| 147 | closeFn: closeFn, |
| 148 | } |
| 149 | } |
| 150 |
| 151 | func (cc *CloseNotifyConn) Close() (err error) { |
| 152 | pflag := cc.closeFlag.Swap(1) |
| 153 | if pflag == 0 { |
| 154 | err = cc.Conn.Close() |
| 155 | if cc.closeFn != nil { |
| 156 | cc.closeFn(nil) |
| 157 | } |
| 158 | } |
| 159 | return |
| 160 | } |
| 161 |
| 162 | // CloseWithError closes the connection and passes the error to the close callback. |
| 163 | func (cc *CloseNotifyConn) CloseWithError(err error) error { |
| 164 | pflag := cc.closeFlag.Swap(1) |
| 165 | if pflag == 0 { |
| 166 | closeErr := cc.Conn.Close() |
| 167 | if cc.closeFn != nil { |
| 168 | cc.closeFn(err) |
| 169 | } |
| 170 | return closeErr |
| 171 | } |
| 172 | return nil |
| 173 | } |
| 174 |
| 175 | type StatsConn struct { |
| 176 | net.Conn |
| 177 |
| 178 | closed atomic.Int64 // 1 means closed |
| 179 | totalRead int64 |
| 180 | totalWrite int64 |
| 181 | statsFunc func(totalRead, totalWrite int64) |
| 182 | } |
| 183 |
| 184 | func WrapStatsConn(conn net.Conn, statsFunc func(total, totalWrite int64)) *StatsConn { |
| 185 | return &StatsConn{ |
| 186 | Conn: conn, |
| 187 | statsFunc: statsFunc, |
| 188 | } |
| 189 | } |
| 190 |
| 191 | func (statsConn *StatsConn) Read(p []byte) (n int, err error) { |
| 192 | n, err = statsConn.Conn.Read(p) |
| 193 | statsConn.totalRead += int64(n) |
| 194 | return |
| 195 | } |
| 196 |
| 197 | func (statsConn *StatsConn) Write(p []byte) (n int, err error) { |
| 198 | n, err = statsConn.Conn.Write(p) |
| 199 | statsConn.totalWrite += int64(n) |
| 200 | return |
| 201 | } |
| 202 |
| 203 | func (statsConn *StatsConn) Close() (err error) { |
| 204 | old := statsConn.closed.Swap(1) |
| 205 | if old != 1 { |
| 206 | err = statsConn.Conn.Close() |
| 207 | if statsConn.statsFunc != nil { |
| 208 | statsConn.statsFunc(statsConn.totalRead, statsConn.totalWrite) |
| 209 | } |
| 210 | } |
| 211 | return |
| 212 | } |
| 213 |
| 214 | type wrapQuicStream struct { |
| 215 | *quic.Stream |
| 216 | c *quic.Conn |
| 217 | } |
| 218 |
| 219 | func QuicStreamToNetConn(s *quic.Stream, c *quic.Conn) net.Conn { |
| 220 | return &wrapQuicStream{ |
| 221 | Stream: s, |
| 222 | c: c, |
| 223 | } |
| 224 | } |
| 225 |
| 226 | func (conn *wrapQuicStream) LocalAddr() net.Addr { |
| 227 | if conn.c != nil { |
| 228 | return conn.c.LocalAddr() |
| 229 | } |
| 230 | return (*net.TCPAddr)(nil) |
| 231 | } |
| 232 |
| 233 | func (conn *wrapQuicStream) RemoteAddr() net.Addr { |
| 234 | if conn.c != nil { |
| 235 | return conn.c.RemoteAddr() |
| 236 | } |
| 237 | return (*net.TCPAddr)(nil) |
| 238 | } |
| 239 |
| 240 | func (conn *wrapQuicStream) Close() error { |
| 241 | conn.CancelRead(0) |
| 242 | return conn.Stream.Close() |
| 243 | } |
| 244 |
| 245 | func NewCryptoReadWriter(rw io.ReadWriter, key []byte) (io.ReadWriter, error) { |
| 246 | encReader := libcrypto.NewReader(rw, key) |
| 247 | encWriter, err := libcrypto.NewWriter(rw, key) |
| 248 | if err != nil { |
| 249 | return nil, err |
| 250 | } |
| 251 | return struct { |
| 252 | io.Reader |
| 253 | io.Writer |
| 254 | }{ |
| 255 | Reader: encReader, |
| 256 | Writer: encWriter, |
| 257 | }, nil |
| 258 | } |
| 259 |
| 260 | type AEADCryptoRole int |
| 261 |
| 262 | const ( |
| 263 | AEADCryptoRoleClient AEADCryptoRole = iota + 1 |
| 264 | AEADCryptoRoleServer |
| 265 | ) |
| 266 |
| 267 | const ( |
| 268 | aeadControlHKDFInfoPrefix = "frp wire v2 control aead" |
| 269 | aeadDirectionClientToServer = "client-to-server" |
| 270 | aeadDirectionServerToClient = "server-to-client" |
| 271 | ) |
| 272 |
| 273 | // NewAEADCryptoReadWriter wraps rw with framed AEAD encryption for the v2 |
| 274 | // control channel. Frames and their order are authenticated, but end-of-stream |
| 275 | // is not: a clean EOF at a frame boundary is returned as normal EOF by the |
| 276 | // underlying AEAD stream. Protocols that need truncation detection for finite |
| 277 | // objects must add their own authenticated final message. |
| 278 | func NewAEADCryptoReadWriter( |
| 279 | rw io.ReadWriter, |
| 280 | key []byte, |
| 281 | role AEADCryptoRole, |
| 282 | algorithm string, |
| 283 | transcriptHash []byte, |
| 284 | ) (io.ReadWriter, error) { |
| 285 | clientToServerKey, serverToClientKey, err := deriveAEADControlKeys(key, algorithm, transcriptHash) |
| 286 | if err != nil { |
| 287 | return nil, err |
| 288 | } |
| 289 |
| 290 | var readKey, writeKey []byte |
| 291 | switch role { |
| 292 | case AEADCryptoRoleClient: |
| 293 | readKey = serverToClientKey |
| 294 | writeKey = clientToServerKey |
| 295 | case AEADCryptoRoleServer: |
| 296 | readKey = clientToServerKey |
| 297 | writeKey = serverToClientKey |
| 298 | default: |
| 299 | return nil, errors.New("invalid aead crypto role") |
| 300 | } |
| 301 |
| 302 | encReader, err := libcrypto.NewAEADStreamReader(rw, libcrypto.AEADStreamOptions{ |
| 303 | Algorithm: libcrypto.AEADAlgorithm(algorithm), |
| 304 | Key: readKey, |
| 305 | }) |
| 306 | if err != nil { |
| 307 | return nil, err |
| 308 | } |
| 309 | encWriter, err := libcrypto.NewAEADStreamWriter(rw, libcrypto.AEADStreamOptions{ |
| 310 | Algorithm: libcrypto.AEADAlgorithm(algorithm), |
| 311 | Key: writeKey, |
| 312 | }) |
| 313 | if err != nil { |
| 314 | return nil, err |
| 315 | } |
| 316 | return struct { |
| 317 | io.Reader |
| 318 | io.Writer |
| 319 | }{ |
| 320 | Reader: encReader, |
| 321 | Writer: encWriter, |
| 322 | }, nil |
| 323 | } |
| 324 |
| 325 | func deriveAEADControlKeys(key []byte, algorithm string, transcriptHash []byte) (clientToServerKey, serverToClientKey []byte, err error) { |
| 326 | clientToServerKey, err = deriveAEADControlKey(key, algorithm, transcriptHash, aeadDirectionClientToServer) |
| 327 | if err != nil { |
| 328 | return nil, nil, err |
| 329 | } |
| 330 | serverToClientKey, err = deriveAEADControlKey(key, algorithm, transcriptHash, aeadDirectionServerToClient) |
| 331 | if err != nil { |
| 332 | return nil, nil, err |
| 333 | } |
| 334 | return clientToServerKey, serverToClientKey, nil |
| 335 | } |
| 336 |
| 337 | func deriveAEADControlKey(key []byte, algorithm string, transcriptHash []byte, direction string) ([]byte, error) { |
| 338 | info := []byte(aeadControlHKDFInfoPrefix + " " + algorithm + " " + direction) |
| 339 | reader := hkdf.New(sha256.New, key, transcriptHash, info) |
| 340 | out := make([]byte, libcrypto.AEADKeySize) |
| 341 | if _, err := io.ReadFull(reader, out); err != nil { |
| 342 | return nil, err |
| 343 | } |
| 344 | return out, nil |
| 345 | } |