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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package mtglib
  2. import (
  3. "crypto/rand"
  4. "encoding/base64"
  5. "encoding/hex"
  6. "fmt"
  7. )
  8. const secretFakeTLSFirstByte byte = 0xee
  9. var secretEmptyKey [SecretKeyLength]byte
  10. type Secret struct {
  11. Key [SecretKeyLength]byte
  12. Host string
  13. }
  14. func (s Secret) MarshalText() ([]byte, error) {
  15. if s.Valid() {
  16. return []byte(s.String()), nil
  17. }
  18. return nil, nil
  19. }
  20. func (s *Secret) UnmarshalText(data []byte) error {
  21. text := string(data)
  22. if text == "" {
  23. return ErrSecretEmpty
  24. }
  25. decoded, err := hex.DecodeString(text)
  26. if err != nil {
  27. decoded, err = base64.RawURLEncoding.DecodeString(text)
  28. }
  29. if err != nil {
  30. return fmt.Errorf("incorrect secret format: %w", err)
  31. }
  32. if len(decoded) < 2 { // nolint: gomnd // we need at least 1 byte here
  33. return fmt.Errorf("secret is truncated, length=%d", len(decoded))
  34. }
  35. if decoded[0] != secretFakeTLSFirstByte {
  36. return fmt.Errorf("incorrect first byte of secret: %#x", decoded[0])
  37. }
  38. decoded = decoded[1:]
  39. if len(decoded) < SecretKeyLength {
  40. return fmt.Errorf("secret has incorrect length %d", len(decoded))
  41. }
  42. copy(s.Key[:], decoded[:SecretKeyLength])
  43. s.Host = string(decoded[SecretKeyLength:])
  44. if s.Host == "" {
  45. return fmt.Errorf("hostname cannot be empty: %s", text)
  46. }
  47. return nil
  48. }
  49. func (s Secret) Valid() bool {
  50. return s.Key != secretEmptyKey && s.Host != ""
  51. }
  52. func (s Secret) String() string {
  53. return s.Base64()
  54. }
  55. func (s Secret) Base64() string {
  56. return base64.RawURLEncoding.EncodeToString(s.makeBytes())
  57. }
  58. func (s Secret) Hex() string {
  59. return hex.EncodeToString(s.makeBytes())
  60. }
  61. func (s *Secret) makeBytes() []byte {
  62. data := append([]byte{secretFakeTLSFirstByte}, s.Key[:]...)
  63. data = append(data, s.Host...)
  64. return data
  65. }
  66. func GenerateSecret(hostname string) Secret {
  67. s := Secret{
  68. Host: hostname,
  69. }
  70. if _, err := rand.Read(s.Key[:]); err != nil {
  71. panic(err)
  72. }
  73. return s
  74. }
  75. func ParseSecret(secret string) (Secret, error) {
  76. s := Secret{}
  77. return s, s.UnmarshalText([]byte(secret))
  78. }