Highly-opinionated (ex-bullshit-free) MTPROTO proxy for Telegram. If you use v1.0 or upgrade broke you proxy, please read the chapter Version 2
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mtproto_frame.go 4.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. package packet
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "encoding/binary"
  6. "fmt"
  7. "hash/crc32"
  8. "io"
  9. "net"
  10. "github.com/9seconds/mtg/conntypes"
  11. "go.uber.org/zap"
  12. )
  13. const (
  14. mtprotoFrameMinMessageLength = 12
  15. mtprotoFrameMaxMessageLength = 16777216
  16. )
  17. var mtprotoFramePadding = []byte{0x04, 0x00, 0x00, 0x00}
  18. // MTProtoFrame is a wrapper which converts written data to the MTProtoFrame.
  19. // The format of the frame:
  20. //
  21. // [ MSGLEN(4) | SEQNO(4) | MSG(...) | CRC32(4) | PADDING(4*x) ]
  22. //
  23. // MSGLEN is the length of the message + len of seqno and msglen.
  24. // SEQNO is the number of frame in the receive/send sequence. If client
  25. //
  26. // sends a message with SeqNo 18, it has to receive message with SeqNo 18.
  27. //
  28. // MSG is the data which has to be written
  29. // CRC32 is the CRC32 checksum of MSGLEN + SEQNO + MSG
  30. // PADDING is custom padding schema to complete frame length to such that
  31. //
  32. // len(frame) % 16 == 0
  33. type wrapperMtprotoFrame struct {
  34. parent conntypes.StreamReadWriteCloser
  35. logger *zap.SugaredLogger
  36. readSeqNo int32
  37. writeSeqNo int32
  38. }
  39. func (w *wrapperMtprotoFrame) Read() (conntypes.Packet, error) { //nolint: funlen, cyclop
  40. buf := &bytes.Buffer{}
  41. sum := crc32.NewIEEE()
  42. writer := io.MultiWriter(buf, sum)
  43. for {
  44. buf.Reset()
  45. sum.Reset()
  46. if _, err := io.CopyN(writer, w.parent, 4); err != nil { //nolint: gomnd
  47. return nil, fmt.Errorf("cannot read frame padding: %w", err)
  48. }
  49. if !bytes.Equal(buf.Bytes(), mtprotoFramePadding) {
  50. break
  51. }
  52. }
  53. messageLength := binary.LittleEndian.Uint32(buf.Bytes())
  54. w.logger.Debugw("Read MTProto frame",
  55. "messageLength", messageLength,
  56. "sequence_number", w.readSeqNo,
  57. )
  58. if messageLength%4 != 0 || messageLength < mtprotoFrameMinMessageLength ||
  59. messageLength > mtprotoFrameMaxMessageLength {
  60. return nil, fmt.Errorf("incorrect frame message length %d", messageLength)
  61. }
  62. buf.Reset()
  63. if _, err := io.CopyN(writer, w.parent, int64(messageLength)-4-4); err != nil { //nolint: gomnd
  64. return nil, fmt.Errorf("cannot read the message frame: %w", err)
  65. }
  66. var seqNo int32
  67. binary.Read(buf, binary.LittleEndian, &seqNo) //nolint: errcheck
  68. if seqNo != w.readSeqNo {
  69. return nil, fmt.Errorf("unexpected sequence number %d (wait for %d)", seqNo, w.readSeqNo)
  70. }
  71. data, _ := io.ReadAll(buf)
  72. buf.Reset()
  73. // write to buf, not to writer. This is because we are going to fetch
  74. // crc32 checksum.
  75. if _, err := io.CopyN(buf, w.parent, 4); err != nil { //nolint: gomnd
  76. return nil, fmt.Errorf("cannot read checksum: %w", err)
  77. }
  78. checksum := binary.LittleEndian.Uint32(buf.Bytes())
  79. if checksum != sum.Sum32() {
  80. return nil, fmt.Errorf("CRC32 checksum mismatch. wait for %d, got %d", sum.Sum32(), checksum)
  81. }
  82. w.logger.Debugw("Read MTProto frame",
  83. "messageLength", messageLength,
  84. "sequence_number", w.readSeqNo,
  85. "dataLength", len(data),
  86. "checksum", checksum,
  87. )
  88. w.readSeqNo++
  89. return data, nil
  90. }
  91. func (w *wrapperMtprotoFrame) Write(p conntypes.Packet) error {
  92. messageLength := 4 + 4 + len(p) + 4 //nolint: gomnd
  93. paddingLength := (aes.BlockSize - messageLength%aes.BlockSize) % aes.BlockSize
  94. buf := &bytes.Buffer{}
  95. binary.Write(buf, binary.LittleEndian, uint32(messageLength)) //nolint: errcheck
  96. binary.Write(buf, binary.LittleEndian, w.writeSeqNo) //nolint: errcheck
  97. buf.Write(p)
  98. checksum := crc32.ChecksumIEEE(buf.Bytes())
  99. binary.Write(buf, binary.LittleEndian, checksum) //nolint: errcheck
  100. buf.Write(bytes.Repeat(mtprotoFramePadding, paddingLength/4)) //nolint: gomnd
  101. w.logger.Debugw("Write MTProto frame",
  102. "length", len(p),
  103. "sequence_number", w.writeSeqNo,
  104. "crc32", checksum,
  105. "frame_length", buf.Len(),
  106. )
  107. w.writeSeqNo++
  108. _, err := w.parent.Write(buf.Bytes())
  109. return err //nolint: wrapcheck
  110. }
  111. func (w *wrapperMtprotoFrame) Close() error {
  112. return w.parent.Close() //nolint: wrapcheck
  113. }
  114. func (w *wrapperMtprotoFrame) Conn() net.Conn {
  115. return w.parent.Conn()
  116. }
  117. func (w *wrapperMtprotoFrame) Logger() *zap.SugaredLogger {
  118. return w.logger
  119. }
  120. func (w *wrapperMtprotoFrame) LocalAddr() *net.TCPAddr {
  121. return w.parent.LocalAddr()
  122. }
  123. func (w *wrapperMtprotoFrame) RemoteAddr() *net.TCPAddr {
  124. return w.parent.RemoteAddr()
  125. }
  126. func NewMtprotoFrame(parent conntypes.StreamReadWriteCloser, seqNo int32) conntypes.PacketReadWriteCloser {
  127. return &wrapperMtprotoFrame{
  128. parent: parent,
  129. logger: parent.Logger().Named("mtproto-frame"),
  130. readSeqNo: seqNo,
  131. writeSeqNo: seqNo,
  132. }
  133. }