From 7a6695f6c4b9026875195f5fc1b8a2e5fe77bb03 Mon Sep 17 00:00:00 2001 From: 9seconds Date: Mon, 10 Aug 2020 14:39:50 +0300 Subject: [PATCH] Update golangci-lint --- .golangci.toml | 2 +- Makefile | 2 +- antireplay/init.go | 3 +- cli/proxy.go | 5 ++- config/config.go | 2 ++ config/global_ips.go | 2 +- conntypes/protocol.go | 2 ++ conntypes/type.go | 4 ++- faketls/client_protocol.go | 5 +-- faketls/cloak.go | 2 ++ hub/connection.go | 4 +-- hub/connection_list.go | 1 + main.go | 3 +- mtproto/protocol.go | 2 +- mtproto/rpc/consts.go | 2 +- mtproto/rpc/handshake_response.go | 8 ++--- mtproto/rpc/nonce_response.go | 12 +++---- ntp/ntp.go | 6 ++-- obfuscated2/client_protocol.go | 1 + obfuscated2/frame.go | 2 +- protocol/request.go | 3 +- proxy/direct.go | 3 +- proxy/middle.go | 10 +++--- proxy/proxy.go | 6 ++-- stats/stats_prometheus.go | 11 ++++--- stats/stats_statsd.go | 9 ++--- telegram/api/api.go | 6 +++- telegram/base.go | 7 ++-- telegram/middle.go | 3 +- tlstypes/consts.go | 16 +++++---- tlstypes/server_hello.go | 7 ++-- utils/stream_cipher.go | 3 +- wrappers/packet/mtproto_frame.go | 5 ++- wrappers/packetack/client_abridged.go | 3 +- wrappers/packetack/client_intermediate.go | 3 +- .../packetack/client_intermediate_secure.go | 5 ++- wrappers/packetack/proxy.go | 3 +- wrappers/stream/blockcipher.go | 3 +- wrappers/stream/conn.go | 8 +++-- wrappers/stream/ctx.go | 8 +++-- wrappers/stream/faketls.go | 6 ++-- wrappers/stream/mtproto_cipher.go | 33 +++++++++---------- wrappers/stream/obfuscated2.go | 3 +- wrappers/stream/rewind.go | 4 +-- wrappers/stream/stats_telegram.go | 3 +- wrappers/stream/stats_traffic.go | 3 +- wrappers/stream/timeout.go | 3 +- 47 files changed, 133 insertions(+), 114 deletions(-) diff --git a/.golangci.toml b/.golangci.toml index 23d0095..558b5f2 100644 --- a/.golangci.toml +++ b/.golangci.toml @@ -10,4 +10,4 @@ format = "colored-line-number" [linters] enable-all = true -disable = ["gochecknoglobals", "gomnd"] +disable = ["gochecknoglobals", "gas", "gomnd", "goerr113"] diff --git a/Makefile b/Makefile index 7aa09b6..c7bf8c7 100644 --- a/Makefile +++ b/Makefile @@ -71,4 +71,4 @@ prepare: install-lint .PHONY: install-lint install-lint: @curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh \ - | $(MOD_OFF) bash -s -- -b $(GOPATH)/bin $(GOLANGCI_LINT_VERSION) + | $(MOD_OFF) bash -s -- -b . $(GOLANGCI_LINT_VERSION) diff --git a/antireplay/init.go b/antireplay/init.go index 3fa30f8..4ad9950 100644 --- a/antireplay/init.go +++ b/antireplay/init.go @@ -3,9 +3,8 @@ package antireplay import ( "sync" - "github.com/VictoriaMetrics/fastcache" - "github.com/9seconds/mtg/config" + "github.com/VictoriaMetrics/fastcache" ) type CacheInterface interface { diff --git a/cli/proxy.go b/cli/proxy.go index a42a780..b54d09e 100644 --- a/cli/proxy.go +++ b/cli/proxy.go @@ -5,9 +5,6 @@ import ( "os" "time" - "go.uber.org/zap" - "go.uber.org/zap/zapcore" - "github.com/9seconds/mtg/antireplay" "github.com/9seconds/mtg/config" "github.com/9seconds/mtg/faketls" @@ -18,6 +15,8 @@ import ( "github.com/9seconds/mtg/stats" "github.com/9seconds/mtg/telegram" "github.com/9seconds/mtg/utils" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" ) func Proxy() error { // nolint: funlen diff --git a/config/config.go b/config/config.go index 68fc717..a56c34c 100644 --- a/config/config.go +++ b/config/config.go @@ -22,6 +22,8 @@ func (s SecretMode) String() string { return "simple" case SecretModeSecured: return "secured" + case SecretModeTLS: + return "tls" } return "tls" diff --git a/config/global_ips.go b/config/global_ips.go index e27b969..0dd78da 100644 --- a/config/global_ips.go +++ b/config/global_ips.go @@ -60,7 +60,7 @@ func fetchIP(ctx context.Context, network string) (net.IP, error) { return nil, fmt.Errorf("cannot perform a request: %w", err) } - defer resp.Body.Close() // nolint: errcheck + defer resp.Body.Close() respDataBytes, err := ioutil.ReadAll(resp.Body) if err != nil { diff --git a/conntypes/protocol.go b/conntypes/protocol.go index 15a1c69..b89ac65 100644 --- a/conntypes/protocol.go +++ b/conntypes/protocol.go @@ -8,6 +8,8 @@ func (c ConnectionProtocol) String() string { return "any" case ConnectionProtocolIPv4: return "ipv4" + case ConnectionProtocolIPv6: + return "ipv6" } return "ipv6" diff --git a/conntypes/type.go b/conntypes/type.go index 11634f2..c41d42f 100644 --- a/conntypes/type.go +++ b/conntypes/type.go @@ -21,7 +21,9 @@ func (t ConnectionType) Tag() []byte { return ConnectionTagAbridged case ConnectionTypeIntermediate: return ConnectionTagIntermediate - default: + case ConnectionTypeSecure, ConnectionTypeUnknown: return ConnectionTagSecure } + + return ConnectionTagSecure } diff --git a/faketls/client_protocol.go b/faketls/client_protocol.go index 08e896d..b95b7d6 100644 --- a/faketls/client_protocol.go +++ b/faketls/client_protocol.go @@ -49,8 +49,8 @@ func (c *ClientProtocol) Handshake(socket conntypes.StreamReadWriteCloser) (conn } conn := stream.NewFakeTLS(socket) - conn, err := c.ClientProtocol.Handshake(conn) + conn, err := c.ClientProtocol.Handshake(conn) if err != nil { return nil, err } @@ -89,6 +89,7 @@ func (c *ClientProtocol) tlsHandshake(conn io.ReadWriter) error { if antireplay.Cache.HasTLS(clientHello.Random[:]) { stats.Stats.ReplayDetected() + return errors.New("replay attack is detected") } @@ -107,8 +108,8 @@ func (c *ClientProtocol) cloakHost(clientConn io.ReadWriteCloser) { stats.Stats.CloakedRequest() addr := net.JoinHostPort(config.C.CloakHost, strconv.Itoa(config.C.CloakPort)) - hostConn, err := net.Dial("tcp", addr) + hostConn, err := net.Dial("tcp", addr) if err != nil { return } diff --git a/faketls/cloak.go b/faketls/cloak.go index 1e3a5b0..b134de8 100644 --- a/faketls/cloak.go +++ b/faketls/cloak.go @@ -53,9 +53,11 @@ func cloak(one, another io.ReadWriteCloser) { return case <-lastActivityTimer.C: cancel() + return case <-maxTimer.C: cancel() + return } } diff --git a/hub/connection.go b/hub/connection.go index 8769514..9f1d5e8 100644 --- a/hub/connection.go +++ b/hub/connection.go @@ -6,12 +6,11 @@ import ( "sync" "time" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/mtproto" "github.com/9seconds/mtg/mtproto/rpc" "github.com/9seconds/mtg/protocol" + "go.uber.org/zap" ) const connectionTTL = time.Hour @@ -90,6 +89,7 @@ func (c *connection) readLoop() { response, err := rpc.ParseProxyResponse(packet) if err != nil { c.logger.Debugw("Failed response", "error", err) + continue } diff --git a/hub/connection_list.go b/hub/connection_list.go index 7b5f2a8..d1d6a61 100644 --- a/hub/connection_list.go +++ b/hub/connection_list.go @@ -25,6 +25,7 @@ func (c *connectionList) get(conn *ProxyConn) (*connection, error) { if err = newConn.Attach(conn); err != nil { newConn.Close() + return nil, fmt.Errorf("cannot attach to the newly created connection: %w", err) } diff --git a/main.go b/main.go index 3e87f14..b16f040 100644 --- a/main.go +++ b/main.go @@ -7,11 +7,10 @@ import ( "strings" "time" - kingpin "gopkg.in/alecthomas/kingpin.v2" - "github.com/9seconds/mtg/cli" "github.com/9seconds/mtg/config" "github.com/9seconds/mtg/utils" + kingpin "gopkg.in/alecthomas/kingpin.v2" ) var version = "dev" // has to be set by ldflags diff --git a/mtproto/protocol.go b/mtproto/protocol.go index b7dae2e..c37a847 100644 --- a/mtproto/protocol.go +++ b/mtproto/protocol.go @@ -19,8 +19,8 @@ func TelegramProtocol(req *protocol.TelegramRequest) (conntypes.PacketReadWriteC } rpcNonceConn := packet.NewMtprotoFrame(conn, rpc.SeqNoNonce) - rpcNonceReq, err := doRPCNonceRequest(rpcNonceConn) + rpcNonceReq, err := doRPCNonceRequest(rpcNonceConn) if err != nil { return nil, fmt.Errorf("cannot do nonce request: %w", err) } diff --git a/mtproto/rpc/consts.go b/mtproto/rpc/consts.go index 59512a3..9cb7ed4 100644 --- a/mtproto/rpc/consts.go +++ b/mtproto/rpc/consts.go @@ -7,7 +7,7 @@ const ( SeqNoHandshake = -1 ) -// Different constants for RPC protocol +// Different constants for RPC protocol. var ( TagCloseExt = []byte{0xa2, 0x34, 0xb6, 0x5e} TagProxyAns = []byte{0x0d, 0xda, 0x03, 0x44} diff --git a/mtproto/rpc/handshake_response.go b/mtproto/rpc/handshake_response.go index 1f1d509..dc25109 100644 --- a/mtproto/rpc/handshake_response.go +++ b/mtproto/rpc/handshake_response.go @@ -17,10 +17,10 @@ type HandshakeResponse struct { func (r *HandshakeResponse) Bytes() []byte { buf := &bytes.Buffer{} - buf.Write(r.Type) // nolint: gosec - buf.Write(r.Flags) // nolint: gosec - buf.Write(r.SenderPID) // nolint: gosec - buf.Write(r.PeerPID) // nolint: gosec + buf.Write(r.Type) + buf.Write(r.Flags) + buf.Write(r.SenderPID) + buf.Write(r.PeerPID) return buf.Bytes() } diff --git a/mtproto/rpc/nonce_response.go b/mtproto/rpc/nonce_response.go index b214eb5..a6d831e 100644 --- a/mtproto/rpc/nonce_response.go +++ b/mtproto/rpc/nonce_response.go @@ -15,13 +15,13 @@ type NonceResponse struct { // Bytes returns serialized form of the nonce response. func (r *NonceResponse) Bytes() []byte { - buf := &bytes.Buffer{} + buf := bytes.Buffer{} - buf.Write(r.Type) // nolint: gosec - buf.Write(r.KeySelector) // nolint: gosec - buf.Write(r.Crypto) // nolint: gosec - buf.Write(r.CryptoTS) // nolint: gosec - buf.Write(r.Nonce) // nolint: gosec + buf.Write(r.Type) + buf.Write(r.KeySelector) + buf.Write(r.Crypto) + buf.Write(r.CryptoTS) + buf.Write(r.Nonce) return buf.Bytes() } diff --git a/ntp/ntp.go b/ntp/ntp.go index d50e6a7..97d5d63 100644 --- a/ntp/ntp.go +++ b/ntp/ntp.go @@ -5,17 +5,16 @@ import ( "math/rand" "time" + "github.com/9seconds/mtg/config" "github.com/beevik/ntp" "go.uber.org/zap" - - "github.com/9seconds/mtg/config" ) const autoUpdatePeriod = time.Minute // Fetch fetches the data on time drift. func Fetch() (time.Duration, error) { - url := config.C.NTPServers[rand.Intn(len(config.C.NTPServers))] + url := config.C.NTPServers[rand.Intn(len(config.C.NTPServers))] // nolint: gosec resp, err := ntp.Query(url) if err != nil { @@ -40,6 +39,7 @@ func AutoUpdate() { diff, err := Fetch() if err != nil { logger.Debugw("Cannot fetch time from NTP", "error", err) + continue } diff --git a/obfuscated2/client_protocol.go b/obfuscated2/client_protocol.go index d85387c..955ae9e 100644 --- a/obfuscated2/client_protocol.go +++ b/obfuscated2/client_protocol.go @@ -84,6 +84,7 @@ func (c *ClientProtocol) Handshake(socket conntypes.StreamReadWriteCloser) (conn replayKey := decryptedFrame.Unique() if antireplay.Cache.HasObfuscated2(replayKey) { stats.Stats.ReplayDetected() + return nil, errors.New("replay attack is detected") } diff --git a/obfuscated2/frame.go b/obfuscated2/frame.go index 6df81c8..e05cbd0 100644 --- a/obfuscated2/frame.go +++ b/obfuscated2/frame.go @@ -15,7 +15,7 @@ const ( frameLen = 64 ) -// [frameOffsetFirst:frameOffsetKey:frameOffsetIV:frameOffsetMagic:frameOffsetDC:frameOffsetEnd] +// [frameOffsetFirst:frameOffsetKey:frameOffsetIV:frameOffsetMagic:frameOffsetDC:frameOffsetEnd]. type Frame struct { data [frameLen]byte } diff --git a/protocol/request.go b/protocol/request.go index 00a33f8..5f5d98d 100644 --- a/protocol/request.go +++ b/protocol/request.go @@ -3,9 +3,8 @@ package protocol import ( "context" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" + "go.uber.org/zap" ) type TelegramRequest struct { diff --git a/proxy/direct.go b/proxy/direct.go index 2d13a13..f304147 100644 --- a/proxy/direct.go +++ b/proxy/direct.go @@ -4,11 +4,10 @@ import ( "io" "sync" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/obfuscated2" "github.com/9seconds/mtg/protocol" + "go.uber.org/zap" ) const directPipeBufferSize = 1024 diff --git a/proxy/middle.go b/proxy/middle.go index c0995dc..7f56991 100644 --- a/proxy/middle.go +++ b/proxy/middle.go @@ -3,17 +3,17 @@ package proxy import ( "sync" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/protocol" "github.com/9seconds/mtg/wrappers/packetack" + "go.uber.org/zap" ) func middleConnection(request *protocol.TelegramRequest) { telegramConn, err := packetack.NewProxy(request) if err != nil { request.Logger.Debugw("Cannot dial to Telegram", "error", err) + return } defer telegramConn.Close() @@ -27,7 +27,7 @@ func middleConnection(request *protocol.TelegramRequest) { clientConn = packetack.NewClientIntermediate(request.ClientConn) case conntypes.ConnectionTypeSecure: clientConn = packetack.NewClientIntermediateSecure(request.ClientConn) - default: + case conntypes.ConnectionTypeUnknown: panic("unknown connection type") } @@ -53,15 +53,17 @@ func middlePipe(dst conntypes.PacketAckWriteCloser, for { acks := conntypes.ConnectionAcks{} - packet, err := src.Read(&acks) + packet, err := src.Read(&acks) if err != nil { logger.Debugw("Cannot read packet", "error", err) + return } if err = dst.Write(packet, &acks); err != nil { logger.Debugw("Cannot send packet", "error", err) + return } } diff --git a/proxy/proxy.go b/proxy/proxy.go index 7bc462d..7be2a19 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -4,14 +4,13 @@ import ( "context" "net" - "go.uber.org/zap" - "github.com/9seconds/mtg/config" "github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/protocol" "github.com/9seconds/mtg/stats" "github.com/9seconds/mtg/utils" "github.com/9seconds/mtg/wrappers/stream" + "go.uber.org/zap" ) type Proxy struct { @@ -53,6 +52,7 @@ func (p *Proxy) accept(conn net.Conn) { if err := utils.InitTCP(conn, config.C.ClientReadBuffer(), config.C.ClientWriteBuffer()); err != nil { logger.Errorw("Cannot initialize client TCP connection", "error", err) + return } @@ -66,8 +66,8 @@ func (p *Proxy) accept(conn net.Conn) { defer clientConn.Close() clientProtocol := p.ClientProtocolMaker() - clientConn, err := clientProtocol.Handshake(clientConn) + clientConn, err := clientProtocol.Handshake(clientConn) if err != nil { stats.Stats.AuthenticationFailed() logger.Warnw("Cannot perform client handshake", "error", err) diff --git a/stats/stats_prometheus.go b/stats/stats_prometheus.go index 7bddbb0..687c635 100644 --- a/stats/stats_prometheus.go +++ b/stats/stats_prometheus.go @@ -5,11 +5,10 @@ import ( "net/http" "strconv" - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" - "github.com/9seconds/mtg/config" "github.com/9seconds/mtg/conntypes" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" ) type statsPrometheus struct { @@ -51,10 +50,14 @@ func (s *statsPrometheus) changeConnections(connectionType conntypes.ConnectionT labels[0] = "abridged" case conntypes.ConnectionTypeSecure: labels[0] = "secured" + case conntypes.ConnectionTypeIntermediate: + labels[0] = "intermediate" + case conntypes.ConnectionTypeUnknown: + panic("unknown connection type") } if addr.IP.To4() == nil { - labels[1] = "ipv6" // nolint: goconst + labels[1] = "ipv6" } s.connections.WithLabelValues(labels[:]...).Add(increment) diff --git a/stats/stats_statsd.go b/stats/stats_statsd.go index 4c89344..f7106f3 100644 --- a/stats/stats_statsd.go +++ b/stats/stats_statsd.go @@ -8,11 +8,10 @@ import ( "sync" "time" - statsd "github.com/smira/go-statsd" - "go.uber.org/zap" - "github.com/9seconds/mtg/config" "github.com/9seconds/mtg/conntypes" + statsd "github.com/smira/go-statsd" + "go.uber.org/zap" ) var ( @@ -91,8 +90,10 @@ func (s *statsStatsd) changeConnections(connectionType conntypes.ConnectionType, tags = append(tags, tagConnectionTypeAbridged) case conntypes.ConnectionTypeIntermediate: tags = append(tags, tagConnectionTypeIntermediate) - default: + case conntypes.ConnectionTypeSecure: tags = append(tags, tagConnectionTypeSecured) + case conntypes.ConnectionTypeUnknown: + panic("Unknown connection type") } if addr.IP.To4() == nil { diff --git a/telegram/api/api.go b/telegram/api/api.go index de989db..ab02acb 100644 --- a/telegram/api/api.go +++ b/telegram/api/api.go @@ -1,6 +1,7 @@ package api import ( + "context" "fmt" "io" "io/ioutil" @@ -18,7 +19,10 @@ var httpClient = http.Client{ } func request(url string) (io.ReadCloser, error) { - req, err := http.NewRequest("GET", url, nil) + ctx, cancel := context.WithTimeout(context.Background(), apiHTTPTimeout) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, "GET", url, nil) if err != nil { panic(err) } diff --git a/telegram/base.go b/telegram/base.go index d454983..4a6c383 100644 --- a/telegram/base.go +++ b/telegram/base.go @@ -5,12 +5,11 @@ import ( "math/rand" "net" - "go.uber.org/zap" - "github.com/9seconds/mtg/config" "github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/utils" "github.com/9seconds/mtg/wrappers/stream" + "go.uber.org/zap" ) type baseTelegram struct { @@ -34,11 +33,13 @@ func (b *baseTelegram) dial(dc conntypes.DC, conn, err := b.dialer.Dial("tcp", addr) if err != nil { b.logger.Infow("Cannot dial to Telegram", "address", addr, "error", err) + continue } if err := utils.InitTCP(conn, config.C.ProxyReadBuffer(), config.C.ProxyWriteBuffer()); err != nil { b.logger.Infow("Cannot initialize TCP socket", "address", addr, "error", err) + continue } @@ -83,7 +84,7 @@ func (b *baseTelegram) chooseAddress(addresses map[conntypes.DC][]string, case len(addrs) == 1: return addrs[0] case len(addrs) > 1: - return addrs[rand.Intn(len(addrs))] + return addrs[rand.Intn(len(addrs))] // nolint: gosec } return "" diff --git a/telegram/middle.go b/telegram/middle.go index d0917a9..3683f4d 100644 --- a/telegram/middle.go +++ b/telegram/middle.go @@ -5,10 +5,9 @@ import ( "sync" "time" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/telegram/api" + "go.uber.org/zap" ) const middleTelegramBackgroundUpdateEvery = time.Hour diff --git a/tlstypes/consts.go b/tlstypes/consts.go index 6e4156a..c69c0e3 100644 --- a/tlstypes/consts.go +++ b/tlstypes/consts.go @@ -20,9 +20,9 @@ const ( type CipherSuiteType uint8 const ( - CipherSuiteType_TLS_AES_128_GCM_SHA256 CipherSuiteType = iota // nolint: stylecheck, golint - CipherSuiteType_TLS_AES_256_GCM_SHA384 // nolint: stylecheck, golint - CipherSuiteType_TLS_CHACHA20_POLY1305_SHA256 // nolint: stylecheck, golint + CipherSuiteType_TLS_AES_128_GCM_SHA256 CipherSuiteType = iota // nolint: stylecheck,golint + CipherSuiteType_TLS_AES_256_GCM_SHA384 // nolint: stylecheck,golint + CipherSuiteType_TLS_CHACHA20_POLY1305_SHA256 // nolint: stylecheck,golint ) func (c CipherSuiteType) Bytes() []byte { @@ -31,6 +31,8 @@ func (c CipherSuiteType) Bytes() []byte { return CipherSuiteType_TLS_AES_128_GCM_SHA256_Bytes case CipherSuiteType_TLS_AES_256_GCM_SHA384: return CipherSuiteType_TLS_AES_256_GCM_SHA384_Bytes + case CipherSuiteType_TLS_CHACHA20_POLY1305_SHA256: + return CipherSuiteType_TLS_CHACHA20_POLY1305_SHA256_Bytes } return CipherSuiteType_TLS_CHACHA20_POLY1305_SHA256_Bytes @@ -46,6 +48,8 @@ func (v Version) Bytes() []byte { return Version12Bytes case Version11: return Version11Bytes + case Version10, VersionUnknown: + return Version10Bytes } return Version10Bytes @@ -65,9 +69,9 @@ var ( Version12Bytes = []byte{0x03, 0x03} Version13Bytes = []byte{0x03, 0x04} - CipherSuiteType_TLS_AES_128_GCM_SHA256_Bytes = []byte{0x13, 0x01} // nolint: stylecheck, golint - CipherSuiteType_TLS_AES_256_GCM_SHA384_Bytes = []byte{0x13, 0x02} // nolint: stylecheck, golint - CipherSuiteType_TLS_CHACHA20_POLY1305_SHA256_Bytes = []byte{0x13, 0x03} // nolint; stylecheck, golint + CipherSuiteType_TLS_AES_128_GCM_SHA256_Bytes = []byte{0x13, 0x01} // nolint: stylecheck,golint + CipherSuiteType_TLS_AES_256_GCM_SHA384_Bytes = []byte{0x13, 0x02} // nolint: stylecheck,golint + CipherSuiteType_TLS_CHACHA20_POLY1305_SHA256_Bytes = []byte{0x13, 0x03} // nolint: stylecheck,golint ) type Byter interface { diff --git a/tlstypes/server_hello.go b/tlstypes/server_hello.go index a92325c..efd624c 100644 --- a/tlstypes/server_hello.go +++ b/tlstypes/server_hello.go @@ -8,9 +8,8 @@ import ( "io" mrand "math/rand" - "golang.org/x/crypto/curve25519" - "github.com/9seconds/mtg/config" + "golang.org/x/crypto/curve25519" ) type ServerHello struct { @@ -37,8 +36,8 @@ func (s ServerHello) WelcomePacket() []byte { } recChangeCipher.WriteBytes(buf) - hostCert := make([]byte, 1024+mrand.Intn(3092)) - rand.Read(hostCert) // nolint: errcheck + hostCert := make([]byte, 1024+mrand.Intn(3092)) // nolint: gosec + rand.Read(hostCert) // nolint: errcheck recData := Record{ Type: RecordTypeApplicationData, diff --git a/utils/stream_cipher.go b/utils/stream_cipher.go index 072d607..44f0b27 100644 --- a/utils/stream_cipher.go +++ b/utils/stream_cipher.go @@ -6,6 +6,7 @@ import ( ) func MakeStreamCipher(key, iv []byte) cipher.Stream { - block, _ := aes.NewCipher(key) // nolint: gosec + block, _ := aes.NewCipher(key) + return cipher.NewCTR(block, iv) } diff --git a/wrappers/packet/mtproto_frame.go b/wrappers/packet/mtproto_frame.go index dd51a71..119b733 100644 --- a/wrappers/packet/mtproto_frame.go +++ b/wrappers/packet/mtproto_frame.go @@ -10,9 +10,8 @@ import ( "io/ioutil" "net" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" + "go.uber.org/zap" ) const ( @@ -85,7 +84,7 @@ func (w *wrapperMtprotoFrame) Read() (conntypes.Packet, error) { // nolint: funl return nil, fmt.Errorf("unexpected sequence number %d (wait for %d)", seqNo, w.readSeqNo) } - data, _ := ioutil.ReadAll(buf) // nolint: gosec + data, _ := ioutil.ReadAll(buf) buf.Reset() // write to buf, not to writer. This is because we are going to fetch // crc32 checksum. diff --git a/wrappers/packetack/client_abridged.go b/wrappers/packetack/client_abridged.go index 1b8aa9a..2952de0 100644 --- a/wrappers/packetack/client_abridged.go +++ b/wrappers/packetack/client_abridged.go @@ -6,10 +6,9 @@ import ( "io" "net" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/utils" + "go.uber.org/zap" ) const ( diff --git a/wrappers/packetack/client_intermediate.go b/wrappers/packetack/client_intermediate.go index 71ca5f5..ac60fb4 100644 --- a/wrappers/packetack/client_intermediate.go +++ b/wrappers/packetack/client_intermediate.go @@ -7,9 +7,8 @@ import ( "io" "net" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" + "go.uber.org/zap" ) const clientIntermediateQuickAckLength = 0x80000000 diff --git a/wrappers/packetack/client_intermediate_secure.go b/wrappers/packetack/client_intermediate_secure.go index 2af15ab..1151a37 100644 --- a/wrappers/packetack/client_intermediate_secure.go +++ b/wrappers/packetack/client_intermediate_secure.go @@ -6,9 +6,8 @@ import ( "fmt" "math/rand" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" + "go.uber.org/zap" ) type wrapperClientIntermediateSecure struct { @@ -36,7 +35,7 @@ func (w *wrapperClientIntermediateSecure) Write(packet conntypes.Packet, acks *c } buf := &bytes.Buffer{} - paddingLength := rand.Intn(4) + paddingLength := rand.Intn(4) // nolint: gosec buf.Grow(4 + len(packet) + paddingLength) diff --git a/wrappers/packetack/proxy.go b/wrappers/packetack/proxy.go index bd98edf..facbaa4 100644 --- a/wrappers/packetack/proxy.go +++ b/wrappers/packetack/proxy.go @@ -64,6 +64,7 @@ func (w *wrapperProxy) Read(acks *conntypes.ConnectionAcks) (conntypes.Packet, e func (w *wrapperProxy) Close() error { w.proxy.Close() + return nil } @@ -77,7 +78,7 @@ func NewProxy(request *protocol.TelegramRequest) (conntypes.PacketAckReadWriteCl flags |= rpc.ProxyRequestFlagsIntermediate case conntypes.ConnectionTypeSecure: flags |= rpc.ProxyRequestFlagsIntermediate | rpc.ProxyRequestFlagsPad - default: + case conntypes.ConnectionTypeUnknown: panic("unknown connection type") } diff --git a/wrappers/stream/blockcipher.go b/wrappers/stream/blockcipher.go index 3fc7a40..6503e4f 100644 --- a/wrappers/stream/blockcipher.go +++ b/wrappers/stream/blockcipher.go @@ -7,10 +7,9 @@ import ( "net" "time" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/utils" + "go.uber.org/zap" ) type wrapperBlockCipher struct { diff --git a/wrappers/stream/conn.go b/wrappers/stream/conn.go index 5724839..47e1867 100644 --- a/wrappers/stream/conn.go +++ b/wrappers/stream/conn.go @@ -5,10 +5,9 @@ import ( "net" "time" - "go.uber.org/zap" - "github.com/9seconds/mtg/config" "github.com/9seconds/mtg/conntypes" + "go.uber.org/zap" ) type connPurpose uint8 @@ -29,6 +28,7 @@ type wrapperConn struct { func (w *wrapperConn) WriteTimeout(p []byte, timeout time.Duration) (int, error) { if err := w.parent.SetWriteDeadline(time.Now().Add(timeout)); err != nil { w.Close() + return 0, fmt.Errorf("cannot set write deadline to the socket: %w", err) } @@ -40,7 +40,7 @@ func (w *wrapperConn) Write(p []byte) (int, error) { w.logger.Debugw("write to stream", "bytes", n, "error", err) if err != nil { - w.Close() // nolint: gosec + w.Close() } return n, err @@ -49,6 +49,7 @@ func (w *wrapperConn) Write(p []byte) (int, error) { func (w *wrapperConn) ReadTimeout(p []byte, timeout time.Duration) (int, error) { if err := w.parent.SetReadDeadline(time.Now().Add(timeout)); err != nil { w.Close() + return 0, fmt.Errorf("cannot set read deadline to the socket: %w", err) } @@ -68,6 +69,7 @@ func (w *wrapperConn) Read(p []byte) (int, error) { func (w *wrapperConn) Close() error { w.logger.Debugw("Close connection") + return w.parent.Close() } diff --git a/wrappers/stream/ctx.go b/wrappers/stream/ctx.go index c744062..86e7359 100644 --- a/wrappers/stream/ctx.go +++ b/wrappers/stream/ctx.go @@ -6,9 +6,8 @@ import ( "net" "time" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" + "go.uber.org/zap" ) type wrapperCtx struct { @@ -21,6 +20,7 @@ func (w *wrapperCtx) WriteTimeout(p []byte, timeout time.Duration) (int, error) select { case <-w.ctx.Done(): w.Close() + return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err()) default: return w.parent.WriteTimeout(p, timeout) @@ -31,6 +31,7 @@ func (w *wrapperCtx) Write(p []byte) (int, error) { select { case <-w.ctx.Done(): w.Close() + return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err()) default: return w.parent.Write(p) @@ -41,6 +42,7 @@ func (w *wrapperCtx) ReadTimeout(p []byte, timeout time.Duration) (int, error) { select { case <-w.ctx.Done(): w.Close() + return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err()) default: return w.parent.ReadTimeout(p, timeout) @@ -51,6 +53,7 @@ func (w *wrapperCtx) Read(p []byte) (int, error) { select { case <-w.ctx.Done(): w.Close() + return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err()) default: return w.parent.Read(p) @@ -59,6 +62,7 @@ func (w *wrapperCtx) Read(p []byte) (int, error) { func (w *wrapperCtx) Close() error { w.cancel() + return w.parent.Close() } diff --git a/wrappers/stream/faketls.go b/wrappers/stream/faketls.go index 3464935..c0587c6 100644 --- a/wrappers/stream/faketls.go +++ b/wrappers/stream/faketls.go @@ -7,10 +7,9 @@ import ( "net" "time" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/tlstypes" + "go.uber.org/zap" ) type wrapperFakeTLS struct { @@ -33,6 +32,7 @@ func (w *wrapperFakeTLS) WriteTimeout(p []byte, timeout time.Duration) (int, err if elapsed > timeout { return w.parent.WriteTimeout(b, timeout-elapsed) } + return 0, errors.New("timeout") }) } @@ -95,6 +95,8 @@ func NewFakeTLS(socket conntypes.StreamReadWriteCloser) conntypes.StreamReadWrit rec.Data.WriteBytes(buf) return buf.Bytes(), nil + case tlstypes.RecordTypeHandshake: + return nil, errors.New("unsupported record type handshake") default: return nil, fmt.Errorf("unsupported record type %v", rec.Type) } diff --git a/wrappers/stream/mtproto_cipher.go b/wrappers/stream/mtproto_cipher.go index 5cbf203..5a59f7c 100644 --- a/wrappers/stream/mtproto_cipher.go +++ b/wrappers/stream/mtproto_cipher.go @@ -4,8 +4,8 @@ import ( "bytes" "crypto/aes" "crypto/cipher" - "crypto/md5" // nolint: gosec - "crypto/sha1" // nolint: gosec + "crypto/md5" + "crypto/sha1" "encoding/binary" "net" @@ -54,12 +54,11 @@ func mtprotoDeriveKeys(purpose mtprotoCipherPurpose, resp *rpc.NonceResponse, client, remote *net.TCPAddr, secret []byte) ([]byte, []byte) { - message := bytes.Buffer{} - message.Write(resp.Nonce) // nolint: gosec - message.Write(req.Nonce) // nolint: gosec - message.Write(req.CryptoTS) // nolint: gosec + message.Write(resp.Nonce) + message.Write(req.Nonce) + message.Write(req.CryptoTS) clientIPv4 := mtprotoEmptyIP[:] serverIPv4 := mtprotoEmptyIP[:] @@ -69,34 +68,34 @@ func mtprotoDeriveKeys(purpose mtprotoCipherPurpose, serverIPv4 = utils.ReverseBytes(remote.IP.To4()) } - message.Write(serverIPv4) // nolint: gosec + message.Write(serverIPv4) var port [2]byte binary.LittleEndian.PutUint16(port[:], uint16(client.Port)) - message.Write(port[:]) // nolint: gosec + message.Write(port[:]) switch purpose { case mtprotoCipherPurposeClient: - message.WriteString("CLIENT") // nolint: gosec + message.WriteString("CLIENT") case mtprotoCipherPurposeServer: - message.WriteString("SERVER") // nolint: gosec + message.WriteString("SERVER") default: panic("Unexpected cipher purpose") } - message.Write(clientIPv4) // nolint: gosec + message.Write(clientIPv4) binary.LittleEndian.PutUint16(port[:], uint16(remote.Port)) - message.Write(port[:]) // nolint: gosec - message.Write(secret) // nolint: gosec - message.Write(resp.Nonce) // nolint: gosec + message.Write(port[:]) + message.Write(secret) + message.Write(resp.Nonce) if client.IP.To4() == nil { - message.Write(client.IP.To16()) // nolint: gosec - message.Write(remote.IP.To16()) // nolint: gosec + message.Write(client.IP.To16()) + message.Write(remote.IP.To16()) } - message.Write(req.Nonce) // nolint: gosec + message.Write(req.Nonce) data := message.Bytes() md5sum := md5.Sum(data[1:]) // nolint: gas diff --git a/wrappers/stream/obfuscated2.go b/wrappers/stream/obfuscated2.go index bd9278b..11ec2f8 100644 --- a/wrappers/stream/obfuscated2.go +++ b/wrappers/stream/obfuscated2.go @@ -7,9 +7,8 @@ import ( "net" "time" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" + "go.uber.org/zap" ) type wrapperObfuscated2 struct { diff --git a/wrappers/stream/rewind.go b/wrappers/stream/rewind.go index 1170d9d..e1a0177 100644 --- a/wrappers/stream/rewind.go +++ b/wrappers/stream/rewind.go @@ -7,9 +7,8 @@ import ( "sync" "time" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" + "go.uber.org/zap" ) type ReadWriteCloseRewinder interface { @@ -88,6 +87,7 @@ func (w *wrapperRewind) RemoteAddr() *net.TCPAddr { func (w *wrapperRewind) Close() error { w.buf.Reset() + return w.parent.Close() } diff --git a/wrappers/stream/stats_telegram.go b/wrappers/stream/stats_telegram.go index 064790c..3c1f39d 100644 --- a/wrappers/stream/stats_telegram.go +++ b/wrappers/stream/stats_telegram.go @@ -5,10 +5,9 @@ import ( "sync" "time" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/stats" + "go.uber.org/zap" ) type wrapperTelegramStats struct { diff --git a/wrappers/stream/stats_traffic.go b/wrappers/stream/stats_traffic.go index 911daa2..ab77362 100644 --- a/wrappers/stream/stats_traffic.go +++ b/wrappers/stream/stats_traffic.go @@ -4,10 +4,9 @@ import ( "net" "time" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/stats" + "go.uber.org/zap" ) type wrapperTrafficStats struct { diff --git a/wrappers/stream/timeout.go b/wrappers/stream/timeout.go index 6dee072..2447fe2 100644 --- a/wrappers/stream/timeout.go +++ b/wrappers/stream/timeout.go @@ -4,9 +4,8 @@ import ( "net" "time" - "go.uber.org/zap" - "github.com/9seconds/mtg/conntypes" + "go.uber.org/zap" ) const (