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. "io/ioutil"
  10. "net"
  11. "go.uber.org/zap"
  12. "github.com/9seconds/mtg/conntypes"
  13. )
  14. const (
  15. mtprotoFrameMinMessageLength = 12
  16. mtprotoFrameMaxMessageLength = 16777216
  17. )
  18. var mtprotoFramePadding = []byte{0x04, 0x00, 0x00, 0x00}
  19. // MTProtoFrame is a wrapper which converts written data to the MTProtoFrame.
  20. // The format of the frame:
  21. //
  22. // [ MSGLEN(4) | SEQNO(4) | MSG(...) | CRC32(4) | PADDING(4*x) ]
  23. //
  24. // MSGLEN is the length of the message + len of seqno and msglen.
  25. // SEQNO is the number of frame in the receive/send sequence. If client
  26. // sends a message with SeqNo 18, it has to receive message with SeqNo 18.
  27. // MSG is the data which has to be written
  28. // CRC32 is the CRC32 checksum of MSGLEN + SEQNO + MSG
  29. // PADDING is custom padding schema to complete frame length to such that
  30. // len(frame) % 16 == 0
  31. type wrapperMtprotoFrame struct {
  32. parent conntypes.StreamReadWriteCloser
  33. logger *zap.SugaredLogger
  34. readSeqNo int32
  35. writeSeqNo int32
  36. }
  37. func (w *wrapperMtprotoFrame) Read() (conntypes.Packet, error) { // nolint: funlen
  38. buf := &bytes.Buffer{}
  39. sum := crc32.NewIEEE()
  40. writer := io.MultiWriter(buf, sum)
  41. for {
  42. buf.Reset()
  43. sum.Reset()
  44. if _, err := io.CopyN(writer, w.parent, 4); err != nil {
  45. return nil, fmt.Errorf("cannot read frame padding: %w", err)
  46. }
  47. if !bytes.Equal(buf.Bytes(), mtprotoFramePadding) {
  48. break
  49. }
  50. }
  51. messageLength := binary.LittleEndian.Uint32(buf.Bytes())
  52. w.logger.Debugw("Read MTProto frame",
  53. "messageLength", messageLength,
  54. "sequence_number", w.readSeqNo,
  55. )
  56. if messageLength%4 != 0 || messageLength < mtprotoFrameMinMessageLength ||
  57. messageLength > mtprotoFrameMaxMessageLength {
  58. return nil, fmt.Errorf("incorrect frame message length %d", messageLength)
  59. }
  60. buf.Reset()
  61. buf.Grow(int(messageLength) - 4 - 4)
  62. if _, err := io.CopyN(writer, w.parent, int64(messageLength)-4-4); err != nil {
  63. return nil, fmt.Errorf("cannot read the message frame: %w", err)
  64. }
  65. var seqNo int32
  66. binary.Read(buf, binary.LittleEndian, &seqNo) // nolint: errcheck
  67. if seqNo != w.readSeqNo {
  68. return nil, fmt.Errorf("unexpected sequence number %d (wait for %d)", seqNo, w.readSeqNo)
  69. }
  70. data, _ := ioutil.ReadAll(buf) // nolint: gosec
  71. buf.Reset()
  72. // write to buf, not to writer. This is because we are going to fetch
  73. // crc32 checksum.
  74. if _, err := io.CopyN(buf, w.parent, 4); err != nil {
  75. return nil, fmt.Errorf("cannot read checksum: %w", err)
  76. }
  77. checksum := binary.LittleEndian.Uint32(buf.Bytes())
  78. if checksum != sum.Sum32() {
  79. return nil, fmt.Errorf("CRC32 checksum mismatch. wait for %d, got %d", sum.Sum32(), checksum)
  80. }
  81. w.logger.Debugw("Read MTProto frame",
  82. "messageLength", messageLength,
  83. "sequence_number", w.readSeqNo,
  84. "dataLength", len(data),
  85. "checksum", checksum,
  86. )
  87. w.readSeqNo++
  88. return data, nil
  89. }
  90. func (w *wrapperMtprotoFrame) Write(p conntypes.Packet) error {
  91. messageLength := 4 + 4 + len(p) + 4
  92. paddingLength := (aes.BlockSize - messageLength%aes.BlockSize) % aes.BlockSize
  93. buf := &bytes.Buffer{}
  94. buf.Grow(messageLength + paddingLength)
  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))
  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
  110. }
  111. func (w *wrapperMtprotoFrame) Close() error {
  112. return w.parent.Close()
  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. }