Update golangci-lint

This commit is contained in:
9seconds
2020-08-10 14:39:50 +03:00
parent 8ac786581b
commit 7a6695f6c4
47 changed files with 133 additions and 114 deletions
+1 -1
View File
@@ -10,4 +10,4 @@ format = "colored-line-number"
[linters] [linters]
enable-all = true enable-all = true
disable = ["gochecknoglobals", "gomnd"] disable = ["gochecknoglobals", "gas", "gomnd", "goerr113"]
+1 -1
View File
@@ -71,4 +71,4 @@ prepare: install-lint
.PHONY: install-lint .PHONY: install-lint
install-lint: install-lint:
@curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh \ @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)
+1 -2
View File
@@ -3,9 +3,8 @@ package antireplay
import ( import (
"sync" "sync"
"github.com/VictoriaMetrics/fastcache"
"github.com/9seconds/mtg/config" "github.com/9seconds/mtg/config"
"github.com/VictoriaMetrics/fastcache"
) )
type CacheInterface interface { type CacheInterface interface {
+2 -3
View File
@@ -5,9 +5,6 @@ import (
"os" "os"
"time" "time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/9seconds/mtg/antireplay" "github.com/9seconds/mtg/antireplay"
"github.com/9seconds/mtg/config" "github.com/9seconds/mtg/config"
"github.com/9seconds/mtg/faketls" "github.com/9seconds/mtg/faketls"
@@ -18,6 +15,8 @@ import (
"github.com/9seconds/mtg/stats" "github.com/9seconds/mtg/stats"
"github.com/9seconds/mtg/telegram" "github.com/9seconds/mtg/telegram"
"github.com/9seconds/mtg/utils" "github.com/9seconds/mtg/utils"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
) )
func Proxy() error { // nolint: funlen func Proxy() error { // nolint: funlen
+2
View File
@@ -22,6 +22,8 @@ func (s SecretMode) String() string {
return "simple" return "simple"
case SecretModeSecured: case SecretModeSecured:
return "secured" return "secured"
case SecretModeTLS:
return "tls"
} }
return "tls" return "tls"
+1 -1
View File
@@ -60,7 +60,7 @@ func fetchIP(ctx context.Context, network string) (net.IP, error) {
return nil, fmt.Errorf("cannot perform a request: %w", err) 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) respDataBytes, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
+2
View File
@@ -8,6 +8,8 @@ func (c ConnectionProtocol) String() string {
return "any" return "any"
case ConnectionProtocolIPv4: case ConnectionProtocolIPv4:
return "ipv4" return "ipv4"
case ConnectionProtocolIPv6:
return "ipv6"
} }
return "ipv6" return "ipv6"
+3 -1
View File
@@ -21,7 +21,9 @@ func (t ConnectionType) Tag() []byte {
return ConnectionTagAbridged return ConnectionTagAbridged
case ConnectionTypeIntermediate: case ConnectionTypeIntermediate:
return ConnectionTagIntermediate return ConnectionTagIntermediate
default: case ConnectionTypeSecure, ConnectionTypeUnknown:
return ConnectionTagSecure return ConnectionTagSecure
} }
return ConnectionTagSecure
} }
+3 -2
View File
@@ -49,8 +49,8 @@ func (c *ClientProtocol) Handshake(socket conntypes.StreamReadWriteCloser) (conn
} }
conn := stream.NewFakeTLS(socket) conn := stream.NewFakeTLS(socket)
conn, err := c.ClientProtocol.Handshake(conn)
conn, err := c.ClientProtocol.Handshake(conn)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -89,6 +89,7 @@ func (c *ClientProtocol) tlsHandshake(conn io.ReadWriter) error {
if antireplay.Cache.HasTLS(clientHello.Random[:]) { if antireplay.Cache.HasTLS(clientHello.Random[:]) {
stats.Stats.ReplayDetected() stats.Stats.ReplayDetected()
return errors.New("replay attack is detected") return errors.New("replay attack is detected")
} }
@@ -107,8 +108,8 @@ func (c *ClientProtocol) cloakHost(clientConn io.ReadWriteCloser) {
stats.Stats.CloakedRequest() stats.Stats.CloakedRequest()
addr := net.JoinHostPort(config.C.CloakHost, strconv.Itoa(config.C.CloakPort)) 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 { if err != nil {
return return
} }
+2
View File
@@ -53,9 +53,11 @@ func cloak(one, another io.ReadWriteCloser) {
return return
case <-lastActivityTimer.C: case <-lastActivityTimer.C:
cancel() cancel()
return return
case <-maxTimer.C: case <-maxTimer.C:
cancel() cancel()
return return
} }
} }
+2 -2
View File
@@ -6,12 +6,11 @@ import (
"sync" "sync"
"time" "time"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"github.com/9seconds/mtg/mtproto" "github.com/9seconds/mtg/mtproto"
"github.com/9seconds/mtg/mtproto/rpc" "github.com/9seconds/mtg/mtproto/rpc"
"github.com/9seconds/mtg/protocol" "github.com/9seconds/mtg/protocol"
"go.uber.org/zap"
) )
const connectionTTL = time.Hour const connectionTTL = time.Hour
@@ -90,6 +89,7 @@ func (c *connection) readLoop() {
response, err := rpc.ParseProxyResponse(packet) response, err := rpc.ParseProxyResponse(packet)
if err != nil { if err != nil {
c.logger.Debugw("Failed response", "error", err) c.logger.Debugw("Failed response", "error", err)
continue continue
} }
+1
View File
@@ -25,6 +25,7 @@ func (c *connectionList) get(conn *ProxyConn) (*connection, error) {
if err = newConn.Attach(conn); err != nil { if err = newConn.Attach(conn); err != nil {
newConn.Close() newConn.Close()
return nil, fmt.Errorf("cannot attach to the newly created connection: %w", err) return nil, fmt.Errorf("cannot attach to the newly created connection: %w", err)
} }
+1 -2
View File
@@ -7,11 +7,10 @@ import (
"strings" "strings"
"time" "time"
kingpin "gopkg.in/alecthomas/kingpin.v2"
"github.com/9seconds/mtg/cli" "github.com/9seconds/mtg/cli"
"github.com/9seconds/mtg/config" "github.com/9seconds/mtg/config"
"github.com/9seconds/mtg/utils" "github.com/9seconds/mtg/utils"
kingpin "gopkg.in/alecthomas/kingpin.v2"
) )
var version = "dev" // has to be set by ldflags var version = "dev" // has to be set by ldflags
+1 -1
View File
@@ -19,8 +19,8 @@ func TelegramProtocol(req *protocol.TelegramRequest) (conntypes.PacketReadWriteC
} }
rpcNonceConn := packet.NewMtprotoFrame(conn, rpc.SeqNoNonce) rpcNonceConn := packet.NewMtprotoFrame(conn, rpc.SeqNoNonce)
rpcNonceReq, err := doRPCNonceRequest(rpcNonceConn)
rpcNonceReq, err := doRPCNonceRequest(rpcNonceConn)
if err != nil { if err != nil {
return nil, fmt.Errorf("cannot do nonce request: %w", err) return nil, fmt.Errorf("cannot do nonce request: %w", err)
} }
+1 -1
View File
@@ -7,7 +7,7 @@ const (
SeqNoHandshake = -1 SeqNoHandshake = -1
) )
// Different constants for RPC protocol // Different constants for RPC protocol.
var ( var (
TagCloseExt = []byte{0xa2, 0x34, 0xb6, 0x5e} TagCloseExt = []byte{0xa2, 0x34, 0xb6, 0x5e}
TagProxyAns = []byte{0x0d, 0xda, 0x03, 0x44} TagProxyAns = []byte{0x0d, 0xda, 0x03, 0x44}
+4 -4
View File
@@ -17,10 +17,10 @@ type HandshakeResponse struct {
func (r *HandshakeResponse) Bytes() []byte { func (r *HandshakeResponse) Bytes() []byte {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
buf.Write(r.Type) // nolint: gosec buf.Write(r.Type)
buf.Write(r.Flags) // nolint: gosec buf.Write(r.Flags)
buf.Write(r.SenderPID) // nolint: gosec buf.Write(r.SenderPID)
buf.Write(r.PeerPID) // nolint: gosec buf.Write(r.PeerPID)
return buf.Bytes() return buf.Bytes()
} }
+6 -6
View File
@@ -15,13 +15,13 @@ type NonceResponse struct {
// Bytes returns serialized form of the nonce response. // Bytes returns serialized form of the nonce response.
func (r *NonceResponse) Bytes() []byte { func (r *NonceResponse) Bytes() []byte {
buf := &bytes.Buffer{} buf := bytes.Buffer{}
buf.Write(r.Type) // nolint: gosec buf.Write(r.Type)
buf.Write(r.KeySelector) // nolint: gosec buf.Write(r.KeySelector)
buf.Write(r.Crypto) // nolint: gosec buf.Write(r.Crypto)
buf.Write(r.CryptoTS) // nolint: gosec buf.Write(r.CryptoTS)
buf.Write(r.Nonce) // nolint: gosec buf.Write(r.Nonce)
return buf.Bytes() return buf.Bytes()
} }
+3 -3
View File
@@ -5,17 +5,16 @@ import (
"math/rand" "math/rand"
"time" "time"
"github.com/9seconds/mtg/config"
"github.com/beevik/ntp" "github.com/beevik/ntp"
"go.uber.org/zap" "go.uber.org/zap"
"github.com/9seconds/mtg/config"
) )
const autoUpdatePeriod = time.Minute const autoUpdatePeriod = time.Minute
// Fetch fetches the data on time drift. // Fetch fetches the data on time drift.
func Fetch() (time.Duration, error) { 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) resp, err := ntp.Query(url)
if err != nil { if err != nil {
@@ -40,6 +39,7 @@ func AutoUpdate() {
diff, err := Fetch() diff, err := Fetch()
if err != nil { if err != nil {
logger.Debugw("Cannot fetch time from NTP", "error", err) logger.Debugw("Cannot fetch time from NTP", "error", err)
continue continue
} }
+1
View File
@@ -84,6 +84,7 @@ func (c *ClientProtocol) Handshake(socket conntypes.StreamReadWriteCloser) (conn
replayKey := decryptedFrame.Unique() replayKey := decryptedFrame.Unique()
if antireplay.Cache.HasObfuscated2(replayKey) { if antireplay.Cache.HasObfuscated2(replayKey) {
stats.Stats.ReplayDetected() stats.Stats.ReplayDetected()
return nil, errors.New("replay attack is detected") return nil, errors.New("replay attack is detected")
} }
+1 -1
View File
@@ -15,7 +15,7 @@ const (
frameLen = 64 frameLen = 64
) )
// [frameOffsetFirst:frameOffsetKey:frameOffsetIV:frameOffsetMagic:frameOffsetDC:frameOffsetEnd] // [frameOffsetFirst:frameOffsetKey:frameOffsetIV:frameOffsetMagic:frameOffsetDC:frameOffsetEnd].
type Frame struct { type Frame struct {
data [frameLen]byte data [frameLen]byte
} }
+1 -2
View File
@@ -3,9 +3,8 @@ package protocol
import ( import (
"context" "context"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"go.uber.org/zap"
) )
type TelegramRequest struct { type TelegramRequest struct {
+1 -2
View File
@@ -4,11 +4,10 @@ import (
"io" "io"
"sync" "sync"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"github.com/9seconds/mtg/obfuscated2" "github.com/9seconds/mtg/obfuscated2"
"github.com/9seconds/mtg/protocol" "github.com/9seconds/mtg/protocol"
"go.uber.org/zap"
) )
const directPipeBufferSize = 1024 const directPipeBufferSize = 1024
+6 -4
View File
@@ -3,17 +3,17 @@ package proxy
import ( import (
"sync" "sync"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"github.com/9seconds/mtg/protocol" "github.com/9seconds/mtg/protocol"
"github.com/9seconds/mtg/wrappers/packetack" "github.com/9seconds/mtg/wrappers/packetack"
"go.uber.org/zap"
) )
func middleConnection(request *protocol.TelegramRequest) { func middleConnection(request *protocol.TelegramRequest) {
telegramConn, err := packetack.NewProxy(request) telegramConn, err := packetack.NewProxy(request)
if err != nil { if err != nil {
request.Logger.Debugw("Cannot dial to Telegram", "error", err) request.Logger.Debugw("Cannot dial to Telegram", "error", err)
return return
} }
defer telegramConn.Close() defer telegramConn.Close()
@@ -27,7 +27,7 @@ func middleConnection(request *protocol.TelegramRequest) {
clientConn = packetack.NewClientIntermediate(request.ClientConn) clientConn = packetack.NewClientIntermediate(request.ClientConn)
case conntypes.ConnectionTypeSecure: case conntypes.ConnectionTypeSecure:
clientConn = packetack.NewClientIntermediateSecure(request.ClientConn) clientConn = packetack.NewClientIntermediateSecure(request.ClientConn)
default: case conntypes.ConnectionTypeUnknown:
panic("unknown connection type") panic("unknown connection type")
} }
@@ -53,15 +53,17 @@ func middlePipe(dst conntypes.PacketAckWriteCloser,
for { for {
acks := conntypes.ConnectionAcks{} acks := conntypes.ConnectionAcks{}
packet, err := src.Read(&acks)
packet, err := src.Read(&acks)
if err != nil { if err != nil {
logger.Debugw("Cannot read packet", "error", err) logger.Debugw("Cannot read packet", "error", err)
return return
} }
if err = dst.Write(packet, &acks); err != nil { if err = dst.Write(packet, &acks); err != nil {
logger.Debugw("Cannot send packet", "error", err) logger.Debugw("Cannot send packet", "error", err)
return return
} }
} }
+3 -3
View File
@@ -4,14 +4,13 @@ import (
"context" "context"
"net" "net"
"go.uber.org/zap"
"github.com/9seconds/mtg/config" "github.com/9seconds/mtg/config"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"github.com/9seconds/mtg/protocol" "github.com/9seconds/mtg/protocol"
"github.com/9seconds/mtg/stats" "github.com/9seconds/mtg/stats"
"github.com/9seconds/mtg/utils" "github.com/9seconds/mtg/utils"
"github.com/9seconds/mtg/wrappers/stream" "github.com/9seconds/mtg/wrappers/stream"
"go.uber.org/zap"
) )
type Proxy struct { 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 { if err := utils.InitTCP(conn, config.C.ClientReadBuffer(), config.C.ClientWriteBuffer()); err != nil {
logger.Errorw("Cannot initialize client TCP connection", "error", err) logger.Errorw("Cannot initialize client TCP connection", "error", err)
return return
} }
@@ -66,8 +66,8 @@ func (p *Proxy) accept(conn net.Conn) {
defer clientConn.Close() defer clientConn.Close()
clientProtocol := p.ClientProtocolMaker() clientProtocol := p.ClientProtocolMaker()
clientConn, err := clientProtocol.Handshake(clientConn)
clientConn, err := clientProtocol.Handshake(clientConn)
if err != nil { if err != nil {
stats.Stats.AuthenticationFailed() stats.Stats.AuthenticationFailed()
logger.Warnw("Cannot perform client handshake", "error", err) logger.Warnw("Cannot perform client handshake", "error", err)
+7 -4
View File
@@ -5,11 +5,10 @@ import (
"net/http" "net/http"
"strconv" "strconv"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/9seconds/mtg/config" "github.com/9seconds/mtg/config"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
) )
type statsPrometheus struct { type statsPrometheus struct {
@@ -51,10 +50,14 @@ func (s *statsPrometheus) changeConnections(connectionType conntypes.ConnectionT
labels[0] = "abridged" labels[0] = "abridged"
case conntypes.ConnectionTypeSecure: case conntypes.ConnectionTypeSecure:
labels[0] = "secured" labels[0] = "secured"
case conntypes.ConnectionTypeIntermediate:
labels[0] = "intermediate"
case conntypes.ConnectionTypeUnknown:
panic("unknown connection type")
} }
if addr.IP.To4() == nil { if addr.IP.To4() == nil {
labels[1] = "ipv6" // nolint: goconst labels[1] = "ipv6"
} }
s.connections.WithLabelValues(labels[:]...).Add(increment) s.connections.WithLabelValues(labels[:]...).Add(increment)
+5 -4
View File
@@ -8,11 +8,10 @@ import (
"sync" "sync"
"time" "time"
statsd "github.com/smira/go-statsd"
"go.uber.org/zap"
"github.com/9seconds/mtg/config" "github.com/9seconds/mtg/config"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
statsd "github.com/smira/go-statsd"
"go.uber.org/zap"
) )
var ( var (
@@ -91,8 +90,10 @@ func (s *statsStatsd) changeConnections(connectionType conntypes.ConnectionType,
tags = append(tags, tagConnectionTypeAbridged) tags = append(tags, tagConnectionTypeAbridged)
case conntypes.ConnectionTypeIntermediate: case conntypes.ConnectionTypeIntermediate:
tags = append(tags, tagConnectionTypeIntermediate) tags = append(tags, tagConnectionTypeIntermediate)
default: case conntypes.ConnectionTypeSecure:
tags = append(tags, tagConnectionTypeSecured) tags = append(tags, tagConnectionTypeSecured)
case conntypes.ConnectionTypeUnknown:
panic("Unknown connection type")
} }
if addr.IP.To4() == nil { if addr.IP.To4() == nil {
+5 -1
View File
@@ -1,6 +1,7 @@
package api package api
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@@ -18,7 +19,10 @@ var httpClient = http.Client{
} }
func request(url string) (io.ReadCloser, error) { 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 { if err != nil {
panic(err) panic(err)
} }
+4 -3
View File
@@ -5,12 +5,11 @@ import (
"math/rand" "math/rand"
"net" "net"
"go.uber.org/zap"
"github.com/9seconds/mtg/config" "github.com/9seconds/mtg/config"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"github.com/9seconds/mtg/utils" "github.com/9seconds/mtg/utils"
"github.com/9seconds/mtg/wrappers/stream" "github.com/9seconds/mtg/wrappers/stream"
"go.uber.org/zap"
) )
type baseTelegram struct { type baseTelegram struct {
@@ -34,11 +33,13 @@ func (b *baseTelegram) dial(dc conntypes.DC,
conn, err := b.dialer.Dial("tcp", addr) conn, err := b.dialer.Dial("tcp", addr)
if err != nil { if err != nil {
b.logger.Infow("Cannot dial to Telegram", "address", addr, "error", err) b.logger.Infow("Cannot dial to Telegram", "address", addr, "error", err)
continue continue
} }
if err := utils.InitTCP(conn, config.C.ProxyReadBuffer(), config.C.ProxyWriteBuffer()); err != nil { if err := utils.InitTCP(conn, config.C.ProxyReadBuffer(), config.C.ProxyWriteBuffer()); err != nil {
b.logger.Infow("Cannot initialize TCP socket", "address", addr, "error", err) b.logger.Infow("Cannot initialize TCP socket", "address", addr, "error", err)
continue continue
} }
@@ -83,7 +84,7 @@ func (b *baseTelegram) chooseAddress(addresses map[conntypes.DC][]string,
case len(addrs) == 1: case len(addrs) == 1:
return addrs[0] return addrs[0]
case len(addrs) > 1: case len(addrs) > 1:
return addrs[rand.Intn(len(addrs))] return addrs[rand.Intn(len(addrs))] // nolint: gosec
} }
return "" return ""
+1 -2
View File
@@ -5,10 +5,9 @@ import (
"sync" "sync"
"time" "time"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"github.com/9seconds/mtg/telegram/api" "github.com/9seconds/mtg/telegram/api"
"go.uber.org/zap"
) )
const middleTelegramBackgroundUpdateEvery = time.Hour const middleTelegramBackgroundUpdateEvery = time.Hour
+10 -6
View File
@@ -20,9 +20,9 @@ const (
type CipherSuiteType uint8 type CipherSuiteType uint8
const ( const (
CipherSuiteType_TLS_AES_128_GCM_SHA256 CipherSuiteType = iota // 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_AES_256_GCM_SHA384 // nolint: stylecheck,golint
CipherSuiteType_TLS_CHACHA20_POLY1305_SHA256 // nolint: stylecheck, golint CipherSuiteType_TLS_CHACHA20_POLY1305_SHA256 // nolint: stylecheck,golint
) )
func (c CipherSuiteType) Bytes() []byte { func (c CipherSuiteType) Bytes() []byte {
@@ -31,6 +31,8 @@ func (c CipherSuiteType) Bytes() []byte {
return CipherSuiteType_TLS_AES_128_GCM_SHA256_Bytes return CipherSuiteType_TLS_AES_128_GCM_SHA256_Bytes
case CipherSuiteType_TLS_AES_256_GCM_SHA384: case CipherSuiteType_TLS_AES_256_GCM_SHA384:
return CipherSuiteType_TLS_AES_256_GCM_SHA384_Bytes 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 return CipherSuiteType_TLS_CHACHA20_POLY1305_SHA256_Bytes
@@ -46,6 +48,8 @@ func (v Version) Bytes() []byte {
return Version12Bytes return Version12Bytes
case Version11: case Version11:
return Version11Bytes return Version11Bytes
case Version10, VersionUnknown:
return Version10Bytes
} }
return Version10Bytes return Version10Bytes
@@ -65,9 +69,9 @@ var (
Version12Bytes = []byte{0x03, 0x03} Version12Bytes = []byte{0x03, 0x03}
Version13Bytes = []byte{0x03, 0x04} Version13Bytes = []byte{0x03, 0x04}
CipherSuiteType_TLS_AES_128_GCM_SHA256_Bytes = []byte{0x13, 0x01} // 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_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_CHACHA20_POLY1305_SHA256_Bytes = []byte{0x13, 0x03} // nolint: stylecheck,golint
) )
type Byter interface { type Byter interface {
+3 -4
View File
@@ -8,9 +8,8 @@ import (
"io" "io"
mrand "math/rand" mrand "math/rand"
"golang.org/x/crypto/curve25519"
"github.com/9seconds/mtg/config" "github.com/9seconds/mtg/config"
"golang.org/x/crypto/curve25519"
) )
type ServerHello struct { type ServerHello struct {
@@ -37,8 +36,8 @@ func (s ServerHello) WelcomePacket() []byte {
} }
recChangeCipher.WriteBytes(buf) recChangeCipher.WriteBytes(buf)
hostCert := make([]byte, 1024+mrand.Intn(3092)) hostCert := make([]byte, 1024+mrand.Intn(3092)) // nolint: gosec
rand.Read(hostCert) // nolint: errcheck rand.Read(hostCert) // nolint: errcheck
recData := Record{ recData := Record{
Type: RecordTypeApplicationData, Type: RecordTypeApplicationData,
+2 -1
View File
@@ -6,6 +6,7 @@ import (
) )
func MakeStreamCipher(key, iv []byte) cipher.Stream { func MakeStreamCipher(key, iv []byte) cipher.Stream {
block, _ := aes.NewCipher(key) // nolint: gosec block, _ := aes.NewCipher(key)
return cipher.NewCTR(block, iv) return cipher.NewCTR(block, iv)
} }
+2 -3
View File
@@ -10,9 +10,8 @@ import (
"io/ioutil" "io/ioutil"
"net" "net"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"go.uber.org/zap"
) )
const ( 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) 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() buf.Reset()
// write to buf, not to writer. This is because we are going to fetch // write to buf, not to writer. This is because we are going to fetch
// crc32 checksum. // crc32 checksum.
+1 -2
View File
@@ -6,10 +6,9 @@ import (
"io" "io"
"net" "net"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"github.com/9seconds/mtg/utils" "github.com/9seconds/mtg/utils"
"go.uber.org/zap"
) )
const ( const (
+1 -2
View File
@@ -7,9 +7,8 @@ import (
"io" "io"
"net" "net"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"go.uber.org/zap"
) )
const clientIntermediateQuickAckLength = 0x80000000 const clientIntermediateQuickAckLength = 0x80000000
@@ -6,9 +6,8 @@ import (
"fmt" "fmt"
"math/rand" "math/rand"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"go.uber.org/zap"
) )
type wrapperClientIntermediateSecure struct { type wrapperClientIntermediateSecure struct {
@@ -36,7 +35,7 @@ func (w *wrapperClientIntermediateSecure) Write(packet conntypes.Packet, acks *c
} }
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
paddingLength := rand.Intn(4) paddingLength := rand.Intn(4) // nolint: gosec
buf.Grow(4 + len(packet) + paddingLength) buf.Grow(4 + len(packet) + paddingLength)
+2 -1
View File
@@ -64,6 +64,7 @@ func (w *wrapperProxy) Read(acks *conntypes.ConnectionAcks) (conntypes.Packet, e
func (w *wrapperProxy) Close() error { func (w *wrapperProxy) Close() error {
w.proxy.Close() w.proxy.Close()
return nil return nil
} }
@@ -77,7 +78,7 @@ func NewProxy(request *protocol.TelegramRequest) (conntypes.PacketAckReadWriteCl
flags |= rpc.ProxyRequestFlagsIntermediate flags |= rpc.ProxyRequestFlagsIntermediate
case conntypes.ConnectionTypeSecure: case conntypes.ConnectionTypeSecure:
flags |= rpc.ProxyRequestFlagsIntermediate | rpc.ProxyRequestFlagsPad flags |= rpc.ProxyRequestFlagsIntermediate | rpc.ProxyRequestFlagsPad
default: case conntypes.ConnectionTypeUnknown:
panic("unknown connection type") panic("unknown connection type")
} }
+1 -2
View File
@@ -7,10 +7,9 @@ import (
"net" "net"
"time" "time"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"github.com/9seconds/mtg/utils" "github.com/9seconds/mtg/utils"
"go.uber.org/zap"
) )
type wrapperBlockCipher struct { type wrapperBlockCipher struct {
+5 -3
View File
@@ -5,10 +5,9 @@ import (
"net" "net"
"time" "time"
"go.uber.org/zap"
"github.com/9seconds/mtg/config" "github.com/9seconds/mtg/config"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"go.uber.org/zap"
) )
type connPurpose uint8 type connPurpose uint8
@@ -29,6 +28,7 @@ type wrapperConn struct {
func (w *wrapperConn) WriteTimeout(p []byte, timeout time.Duration) (int, error) { func (w *wrapperConn) WriteTimeout(p []byte, timeout time.Duration) (int, error) {
if err := w.parent.SetWriteDeadline(time.Now().Add(timeout)); err != nil { if err := w.parent.SetWriteDeadline(time.Now().Add(timeout)); err != nil {
w.Close() w.Close()
return 0, fmt.Errorf("cannot set write deadline to the socket: %w", err) 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) w.logger.Debugw("write to stream", "bytes", n, "error", err)
if err != nil { if err != nil {
w.Close() // nolint: gosec w.Close()
} }
return n, err 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) { func (w *wrapperConn) ReadTimeout(p []byte, timeout time.Duration) (int, error) {
if err := w.parent.SetReadDeadline(time.Now().Add(timeout)); err != nil { if err := w.parent.SetReadDeadline(time.Now().Add(timeout)); err != nil {
w.Close() w.Close()
return 0, fmt.Errorf("cannot set read deadline to the socket: %w", err) 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 { func (w *wrapperConn) Close() error {
w.logger.Debugw("Close connection") w.logger.Debugw("Close connection")
return w.parent.Close() return w.parent.Close()
} }
+6 -2
View File
@@ -6,9 +6,8 @@ import (
"net" "net"
"time" "time"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"go.uber.org/zap"
) )
type wrapperCtx struct { type wrapperCtx struct {
@@ -21,6 +20,7 @@ func (w *wrapperCtx) WriteTimeout(p []byte, timeout time.Duration) (int, error)
select { select {
case <-w.ctx.Done(): case <-w.ctx.Done():
w.Close() w.Close()
return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err()) return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err())
default: default:
return w.parent.WriteTimeout(p, timeout) return w.parent.WriteTimeout(p, timeout)
@@ -31,6 +31,7 @@ func (w *wrapperCtx) Write(p []byte) (int, error) {
select { select {
case <-w.ctx.Done(): case <-w.ctx.Done():
w.Close() w.Close()
return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err()) return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err())
default: default:
return w.parent.Write(p) return w.parent.Write(p)
@@ -41,6 +42,7 @@ func (w *wrapperCtx) ReadTimeout(p []byte, timeout time.Duration) (int, error) {
select { select {
case <-w.ctx.Done(): case <-w.ctx.Done():
w.Close() w.Close()
return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err()) return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err())
default: default:
return w.parent.ReadTimeout(p, timeout) return w.parent.ReadTimeout(p, timeout)
@@ -51,6 +53,7 @@ func (w *wrapperCtx) Read(p []byte) (int, error) {
select { select {
case <-w.ctx.Done(): case <-w.ctx.Done():
w.Close() w.Close()
return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err()) return 0, fmt.Errorf("cannot write because context was closed: %w", w.ctx.Err())
default: default:
return w.parent.Read(p) return w.parent.Read(p)
@@ -59,6 +62,7 @@ func (w *wrapperCtx) Read(p []byte) (int, error) {
func (w *wrapperCtx) Close() error { func (w *wrapperCtx) Close() error {
w.cancel() w.cancel()
return w.parent.Close() return w.parent.Close()
} }
+4 -2
View File
@@ -7,10 +7,9 @@ import (
"net" "net"
"time" "time"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"github.com/9seconds/mtg/tlstypes" "github.com/9seconds/mtg/tlstypes"
"go.uber.org/zap"
) )
type wrapperFakeTLS struct { type wrapperFakeTLS struct {
@@ -33,6 +32,7 @@ func (w *wrapperFakeTLS) WriteTimeout(p []byte, timeout time.Duration) (int, err
if elapsed > timeout { if elapsed > timeout {
return w.parent.WriteTimeout(b, timeout-elapsed) return w.parent.WriteTimeout(b, timeout-elapsed)
} }
return 0, errors.New("timeout") return 0, errors.New("timeout")
}) })
} }
@@ -95,6 +95,8 @@ func NewFakeTLS(socket conntypes.StreamReadWriteCloser) conntypes.StreamReadWrit
rec.Data.WriteBytes(buf) rec.Data.WriteBytes(buf)
return buf.Bytes(), nil return buf.Bytes(), nil
case tlstypes.RecordTypeHandshake:
return nil, errors.New("unsupported record type handshake")
default: default:
return nil, fmt.Errorf("unsupported record type %v", rec.Type) return nil, fmt.Errorf("unsupported record type %v", rec.Type)
} }
+16 -17
View File
@@ -4,8 +4,8 @@ import (
"bytes" "bytes"
"crypto/aes" "crypto/aes"
"crypto/cipher" "crypto/cipher"
"crypto/md5" // nolint: gosec "crypto/md5"
"crypto/sha1" // nolint: gosec "crypto/sha1"
"encoding/binary" "encoding/binary"
"net" "net"
@@ -54,12 +54,11 @@ func mtprotoDeriveKeys(purpose mtprotoCipherPurpose,
resp *rpc.NonceResponse, resp *rpc.NonceResponse,
client, remote *net.TCPAddr, client, remote *net.TCPAddr,
secret []byte) ([]byte, []byte) { secret []byte) ([]byte, []byte) {
message := bytes.Buffer{} message := bytes.Buffer{}
message.Write(resp.Nonce) // nolint: gosec message.Write(resp.Nonce)
message.Write(req.Nonce) // nolint: gosec message.Write(req.Nonce)
message.Write(req.CryptoTS) // nolint: gosec message.Write(req.CryptoTS)
clientIPv4 := mtprotoEmptyIP[:] clientIPv4 := mtprotoEmptyIP[:]
serverIPv4 := mtprotoEmptyIP[:] serverIPv4 := mtprotoEmptyIP[:]
@@ -69,34 +68,34 @@ func mtprotoDeriveKeys(purpose mtprotoCipherPurpose,
serverIPv4 = utils.ReverseBytes(remote.IP.To4()) serverIPv4 = utils.ReverseBytes(remote.IP.To4())
} }
message.Write(serverIPv4) // nolint: gosec message.Write(serverIPv4)
var port [2]byte var port [2]byte
binary.LittleEndian.PutUint16(port[:], uint16(client.Port)) binary.LittleEndian.PutUint16(port[:], uint16(client.Port))
message.Write(port[:]) // nolint: gosec message.Write(port[:])
switch purpose { switch purpose {
case mtprotoCipherPurposeClient: case mtprotoCipherPurposeClient:
message.WriteString("CLIENT") // nolint: gosec message.WriteString("CLIENT")
case mtprotoCipherPurposeServer: case mtprotoCipherPurposeServer:
message.WriteString("SERVER") // nolint: gosec message.WriteString("SERVER")
default: default:
panic("Unexpected cipher purpose") panic("Unexpected cipher purpose")
} }
message.Write(clientIPv4) // nolint: gosec message.Write(clientIPv4)
binary.LittleEndian.PutUint16(port[:], uint16(remote.Port)) binary.LittleEndian.PutUint16(port[:], uint16(remote.Port))
message.Write(port[:]) // nolint: gosec message.Write(port[:])
message.Write(secret) // nolint: gosec message.Write(secret)
message.Write(resp.Nonce) // nolint: gosec message.Write(resp.Nonce)
if client.IP.To4() == nil { if client.IP.To4() == nil {
message.Write(client.IP.To16()) // nolint: gosec message.Write(client.IP.To16())
message.Write(remote.IP.To16()) // nolint: gosec message.Write(remote.IP.To16())
} }
message.Write(req.Nonce) // nolint: gosec message.Write(req.Nonce)
data := message.Bytes() data := message.Bytes()
md5sum := md5.Sum(data[1:]) // nolint: gas md5sum := md5.Sum(data[1:]) // nolint: gas
+1 -2
View File
@@ -7,9 +7,8 @@ import (
"net" "net"
"time" "time"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"go.uber.org/zap"
) )
type wrapperObfuscated2 struct { type wrapperObfuscated2 struct {
+2 -2
View File
@@ -7,9 +7,8 @@ import (
"sync" "sync"
"time" "time"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"go.uber.org/zap"
) )
type ReadWriteCloseRewinder interface { type ReadWriteCloseRewinder interface {
@@ -88,6 +87,7 @@ func (w *wrapperRewind) RemoteAddr() *net.TCPAddr {
func (w *wrapperRewind) Close() error { func (w *wrapperRewind) Close() error {
w.buf.Reset() w.buf.Reset()
return w.parent.Close() return w.parent.Close()
} }
+1 -2
View File
@@ -5,10 +5,9 @@ import (
"sync" "sync"
"time" "time"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"github.com/9seconds/mtg/stats" "github.com/9seconds/mtg/stats"
"go.uber.org/zap"
) )
type wrapperTelegramStats struct { type wrapperTelegramStats struct {
+1 -2
View File
@@ -4,10 +4,9 @@ import (
"net" "net"
"time" "time"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"github.com/9seconds/mtg/stats" "github.com/9seconds/mtg/stats"
"go.uber.org/zap"
) )
type wrapperTrafficStats struct { type wrapperTrafficStats struct {
+1 -2
View File
@@ -4,9 +4,8 @@ import (
"net" "net"
"time" "time"
"go.uber.org/zap"
"github.com/9seconds/mtg/conntypes" "github.com/9seconds/mtg/conntypes"
"go.uber.org/zap"
) )
const ( const (