telethon 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,168 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "zlib"
4
+
5
+ module Telethon
6
+ module Network
7
+ # Sends requests over one encrypted connection and waits for their results. Telethon's sender is
8
+ # asynchronous; a CLI calls one request at a time, so this one is synchronous: it sends, then reads
9
+ # until the answer to that message comes, handling everything else the server says on the way
10
+ # (salts, clock, acks, containers, updates).
11
+ class Sender
12
+ INIT_LAYER = "invokeWithLayer"
13
+ MAX_RESENDS = 5
14
+
15
+ attr_reader :state, :transport, :updates
16
+
17
+ def initialize(transport, state)
18
+ @transport = transport
19
+ @state = state
20
+ @pending_acks = []
21
+ @updates = []
22
+ @answers = {}
23
+ @wrapper = nil
24
+ end
25
+
26
+ # Every request goes inside this one until the first succeeds (invokeWithLayer(initConnection)).
27
+ def wrap_first(&block)
28
+ @wrapper = block
29
+ end
30
+
31
+ # Calls a TL function and answers its result, or raises RPCError.
32
+ def call(request)
33
+ body = TL.encode(request)
34
+ if @wrapper
35
+ body = @wrapper.call(body)
36
+ result = send_and_wait(body, request.name)
37
+ @wrapper = nil
38
+ return result
39
+ end
40
+ send_and_wait(body, request.name)
41
+ end
42
+
43
+ # Reads what the server sends for up to timeout seconds (updates, for QR login). Answers the
44
+ # updates gathered so far, and clears them.
45
+ def poll(timeout)
46
+ deadline = Time.now.to_f + timeout
47
+ while Time.now.to_f < deadline
48
+ break unless @transport.ready?([deadline - Time.now.to_f, 0.05].max)
49
+
50
+ receive_one
51
+ end
52
+ flush_acks
53
+ taken = @updates
54
+ @updates = []
55
+ taken
56
+ end
57
+
58
+ private
59
+
60
+ def send_and_wait(body, function_name)
61
+ resends = 0
62
+ loop do
63
+ flush_acks
64
+ msg_id = @state.next_msg_id
65
+ @transport.send_packet(@state.encrypt(msg_id, @state.next_seq_no(true), gzip_if_smaller(body)))
66
+ @answers.delete(msg_id)
67
+ receive_one until @answers.key?(msg_id)
68
+ answer = @answers.delete(msg_id)
69
+ return read_answer(answer, function_name) unless answer.is_a?(Symbol)
70
+
71
+ resends += 1
72
+ raise TransportError, "gave up on #{function_name} after #{resends} resends" if resends > MAX_RESENDS
73
+ end
74
+ end
75
+
76
+ def read_answer(answer, function_name)
77
+ data = answer
78
+ if data.byteslice(0, 4).unpack1("L<") == TL::GZIP_PACKED
79
+ data = Zlib.gunzip(TL::Reader.new(data.byteslice(4, data.bytesize - 4)).tl_bytes)
80
+ end
81
+ reader = TL::Reader.new(data)
82
+ if data.byteslice(0, 4).unpack1("L<") == 0x2144ca19 # rpc_error
83
+ reader.uint
84
+ code = reader.int
85
+ raise RPCError.new(code, reader.tl_string, function_name)
86
+ end
87
+ TL.read_result(reader, function_name)
88
+ rescue Zlib::Error => e
89
+ raise TransportError, "bad gzip in the answer to #{function_name}: #{e.message}"
90
+ end
91
+
92
+ def receive_one
93
+ msg_id, seq_no, body = @state.decrypt(@transport.recv_packet)
94
+ handle(msg_id, seq_no, body)
95
+ end
96
+
97
+ def handle(msg_id, seq_no, body)
98
+ @pending_acks << msg_id if seq_no.odd?
99
+ handle_body(msg_id, body)
100
+ end
101
+
102
+ def handle_body(msg_id, body)
103
+ reader = TL::Reader.new(body)
104
+ id = reader.uint
105
+ case id
106
+ when TL::MSG_CONTAINER
107
+ reader.int.times do
108
+ inner_id = reader.long
109
+ inner_seq = reader.int
110
+ length = reader.int
111
+ handle(inner_id, inner_seq, reader.bytes(length))
112
+ end
113
+ when TL::RPC_RESULT
114
+ req_msg_id = reader.long
115
+ @answers[req_msg_id] = reader.rest
116
+ when TL::GZIP_PACKED
117
+ handle_body(msg_id, Zlib.gunzip(reader.tl_bytes))
118
+ else
119
+ handle_service(msg_id, TL.read_with_id(reader, id))
120
+ end
121
+ end
122
+
123
+ def handle_service(msg_id, object)
124
+ return @updates << object unless object.is_a?(TL::Object)
125
+
126
+ case object.name
127
+ when "bad_server_salt"
128
+ @state.salt = object["new_server_salt"]
129
+ @answers[object["bad_msg_id"]] = :resend
130
+ when "bad_msg_notification"
131
+ code = object["error_code"]
132
+ if [16, 17].include?(code)
133
+ @state.update_time_offset(msg_id)
134
+ elsif [32, 33].include?(code)
135
+ @state.reset
136
+ else
137
+ raise SecurityError, "bad_msg_notification #{code}"
138
+ end
139
+ @answers[object["bad_msg_id"]] = :resend
140
+ when "new_session_created"
141
+ @state.salt = object["server_salt"]
142
+ when "pong"
143
+ # A ping is answered with a bare pong rather than an rpc_result; its msg_id names the ping.
144
+ @answers[object["msg_id"]] = TL.encode(object)
145
+ when "msgs_ack", "msg_detailed_info", "msg_new_detailed_info", "future_salts"
146
+ nil
147
+ else
148
+ @updates << object
149
+ end
150
+ end
151
+
152
+ def flush_acks
153
+ return if @pending_acks.empty?
154
+
155
+ ack = TL.encode(TL.make("msgs_ack", "msg_ids" => @pending_acks))
156
+ @pending_acks = []
157
+ @transport.send_packet(@state.encrypt(@state.next_msg_id, @state.next_seq_no(false), ack))
158
+ end
159
+
160
+ def gzip_if_smaller(body)
161
+ return body if body.bytesize < 512
162
+
163
+ packed = TL::Writer.new.uint(TL::GZIP_PACKED).tl_bytes(Zlib.gzip(body)).to_s
164
+ packed.bytesize < body.bytesize ? packed : body
165
+ end
166
+ end
167
+ end
168
+ end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Telethon
4
+ module Network
5
+ # Encryption, message ids and sequence numbers of one MTProto 2.0 session, ported from Telethon's
6
+ # network/mtprotostate.py.
7
+ class State
8
+ attr_accessor :salt, :time_offset
9
+ attr_reader :auth_key
10
+ attr_accessor :session_id
11
+
12
+ def initialize(auth_key, time_offset = 0)
13
+ @auth_key = auth_key
14
+ @time_offset = time_offset
15
+ @salt = 0
16
+ reset
17
+ end
18
+
19
+ def reset
20
+ @session_id = Crypto.random_bytes(8)
21
+ @sequence = 0
22
+ @last_msg_id = 0
23
+ end
24
+
25
+ def next_msg_id
26
+ now = Time.now
27
+ id = ((now.to_i + @time_offset) << 32) | ((now.nsec / 1000) << 2)
28
+ id = @last_msg_id + 4 if id <= @last_msg_id
29
+ @last_msg_id = id
30
+ end
31
+
32
+ def next_seq_no(content_related)
33
+ return @sequence * 2 unless content_related
34
+
35
+ value = (@sequence * 2) + 1
36
+ @sequence += 1
37
+ value
38
+ end
39
+
40
+ # Sets the clock offset from a msg_id the server sent, which carries its time in the high half.
41
+ def update_time_offset(server_msg_id)
42
+ offset = (server_msg_id >> 32) - Time.now.to_i
43
+ @last_msg_id = 0 if offset != @time_offset
44
+ @time_offset = offset
45
+ end
46
+
47
+ # One message (msg_id, seq_no, length, body) as its encrypted packet.
48
+ # padding is for tests; it is 12 to 27 random bytes otherwise.
49
+ def encrypt(msg_id, seq_no, body, padding: nil)
50
+ data = [@salt].pack("q<") + @session_id + [msg_id, seq_no, body.bytesize].pack("q<l<l<") + body
51
+ padding ||= Crypto.random_bytes(((-(data.bytesize + 12)) % 16) + 12)
52
+ key = @auth_key.key
53
+ msg_key = Crypto.sha256(key.byteslice(88, 32) + data + padding).byteslice(8, 16)
54
+ aes_key, aes_iv = derive(msg_key, 0)
55
+ @auth_key.id + msg_key + Crypto.ige_encrypt(data + padding, aes_key, aes_iv)
56
+ end
57
+
58
+ # Answers [msg_id, seq_no, body] of a packet from the server.
59
+ def decrypt(packet)
60
+ raise SecurityError, "short packet" if packet.bytesize < 24
61
+ raise SecurityError, "server answered with another auth key" unless packet.byteslice(0, 8) == @auth_key.id
62
+
63
+ msg_key = packet.byteslice(8, 16)
64
+ aes_key, aes_iv = derive(msg_key, 8)
65
+ plain = Crypto.ige_decrypt(packet.byteslice(24, packet.bytesize - 24), aes_key, aes_iv)
66
+ ours = Crypto.sha256(@auth_key.key.byteslice(96, 32) + plain).byteslice(8, 16)
67
+ raise SecurityError, "msg_key mismatch" unless ours == msg_key
68
+
69
+ reader = TL::Reader.new(plain)
70
+ reader.long # server salt
71
+ raise SecurityError, "wrong session id" unless reader.bytes(8) == @session_id
72
+
73
+ msg_id = reader.long
74
+ raise SecurityError, "server sent an even msg_id" if msg_id.even?
75
+
76
+ seq_no = reader.int
77
+ length = reader.int
78
+ raise SecurityError, "message longer than its packet" if length > reader.remaining
79
+
80
+ [msg_id, seq_no, reader.bytes(length)]
81
+ end
82
+
83
+ # The AES key and iv for a msg_key: x is 0 for what the client sends, 8 for what the server sends.
84
+ def derive(msg_key, x)
85
+ key = @auth_key.key
86
+ a = Crypto.sha256(msg_key + key.byteslice(x, 36))
87
+ b = Crypto.sha256(key.byteslice(x + 40, 36) + msg_key)
88
+ aes_key = a.byteslice(0, 8) + b.byteslice(8, 16) + a.byteslice(24, 8)
89
+ aes_iv = b.byteslice(0, 8) + a.byteslice(8, 16) + b.byteslice(24, 8)
90
+ [aes_key, aes_iv]
91
+ end
92
+
93
+ # What a server would send: for tests, which play the server.
94
+ def encrypt_as_server(msg_id, seq_no, body)
95
+ data = [@salt].pack("q<") + @session_id + [msg_id, seq_no, body.bytesize].pack("q<l<l<") + body
96
+ data += Crypto.random_bytes(((-(data.bytesize + 12)) % 16) + 12)
97
+ msg_key = Crypto.sha256(@auth_key.key.byteslice(96, 32) + data).byteslice(8, 16)
98
+ aes_key, aes_iv = derive(msg_key, 8)
99
+ @auth_key.id + msg_key + Crypto.ige_encrypt(data, aes_key, aes_iv)
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+ require "io/wait"
5
+
6
+ module Telethon
7
+ module Network
8
+ # TCP to a data center in the obfuscated intermediate mode (Telethon's tcpobfuscated with the
9
+ # intermediate codec): a 64-byte random header sets up an AES-CTR stream per direction, and every
10
+ # packet is its little-endian length and then the data.
11
+ class Transport
12
+ TAG = "\xee\xee\xee\xee".b
13
+ FORBIDDEN = ["PVrG".b, "GET ".b, "POST".b, TAG].freeze
14
+
15
+ attr_reader :host, :port
16
+
17
+ def initialize(host, port, timeout: 15)
18
+ @host = host
19
+ @port = port
20
+ @timeout = timeout
21
+ @socket = nil
22
+ end
23
+
24
+ def connect
25
+ @socket = TCPSocket.new(@host, @port, connect_timeout: @timeout)
26
+ @socket.timeout = @timeout * 4
27
+ header = random_header
28
+ reversed = header.byteslice(8, 48).unpack("C*").reverse.pack("C*") # not String#reverse: see DEVELOPING.md
29
+ @encrypt = Crypto::Ctr.new(header.byteslice(8, 32), header.byteslice(40, 16))
30
+ @decrypt = Crypto::Ctr.new(reversed.byteslice(0, 32), reversed.byteslice(32, 16))
31
+ tagged = header.byteslice(0, 56) + TAG + header.byteslice(60, 4)
32
+ sealed = @encrypt.update(tagged)
33
+ @socket.write(tagged.byteslice(0, 56) + sealed.byteslice(56, 8))
34
+ self
35
+ end
36
+
37
+ def connected?
38
+ !@socket.nil?
39
+ end
40
+
41
+ def close
42
+ @socket&.close
43
+ rescue IOError
44
+ nil
45
+ ensure
46
+ @socket = nil
47
+ end
48
+
49
+ def send_packet(data)
50
+ @socket.write(@encrypt.update([data.bytesize].pack("l<") + data))
51
+ end
52
+
53
+ # Waits up to timeout seconds for data. wait_readable, unlike IO.select, sees bytes Ruby has
54
+ # already buffered, which a previous read may have pulled in with the packet before.
55
+ def ready?(timeout)
56
+ !@socket.wait_readable(timeout).nil?
57
+ end
58
+
59
+ def recv_packet
60
+ length = @decrypt.update(read_exactly(4)).unpack1("l<")
61
+ raise TransportError.new("transport error #{length}", length) if length.negative?
62
+
63
+ data = @decrypt.update(read_exactly(length))
64
+ if length == 4
65
+ code = data.unpack1("l<")
66
+ raise TransportError.new("transport error #{code}", code) if code.negative?
67
+ end
68
+ data
69
+ end
70
+
71
+ private
72
+
73
+ def read_exactly(count)
74
+ data = @socket.read(count)
75
+ raise TransportError, "#{@host} closed the connection" if data.nil? || data.bytesize < count
76
+
77
+ data.b
78
+ rescue IO::TimeoutError
79
+ raise TransportError, "timed out reading from #{@host}"
80
+ end
81
+
82
+ def random_header
83
+ loop do
84
+ header = Crypto.random_bytes(64)
85
+ next if header.getbyte(0) == 0xef
86
+ next if FORBIDDEN.include?(header.byteslice(0, 4))
87
+ next if header.byteslice(4, 4) == "\0\0\0\0".b
88
+
89
+ return header
90
+ end
91
+ end
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Telethon
4
+ # Files only their owner may read, created that way so that no content is ever written world-readable.
5
+ module PrivateFiles
6
+ module_function
7
+
8
+ def directory(path)
9
+ Dir.mkdir(path, 0o700) unless Dir.exist?(path)
10
+ File.chmod(0o700, path)
11
+ path
12
+ end
13
+
14
+ # Writes through a temporary file and a rename, so a crash leaves the old file whole.
15
+ def write(path, content)
16
+ temporary = "#{path}.tmp"
17
+ File.open(temporary, File::WRONLY | File::CREAT | File::TRUNC, 0o600) do |file|
18
+ file.chmod(0o600)
19
+ file.write(content)
20
+ end
21
+ File.rename(temporary, path)
22
+ path
23
+ end
24
+ end
25
+ end