@@ -45,7 +45,7 @@ def generate_callback_data():
4545 c = ctx ()
4646
4747 name = "%s:%s" % (c .component_name (), callback )
48- return get_callback_data (c .bot , name , data )
48+ return get_callback_data (c .bot , c . chat (), name , data )
4949
5050 self ._content .append ({
5151 "text" : label ,
@@ -105,7 +105,7 @@ def buttons():
105105 return Buttons ()
106106
107107
108- def parse_callback_data (bot , raw ):
108+ def parse_callback_data (bot , chat , raw ):
109109 """Parse the callback data generated by botogram and return it"""
110110 raw = raw .encode ("utf-8" )
111111
@@ -121,7 +121,8 @@ def parse_callback_data(bot, raw):
121121 name = prelude [16 :]
122122 data = raw [32 :]
123123
124- if not crypto .compare (crypto .get_hmac (bot , name + data ), signature ):
124+ correct = get_signature (bot , chat , name , data )
125+ if not crypto .compare (correct , signature ):
125126 raise crypto .TamperedMessageError
126127
127128 if data :
@@ -130,7 +131,7 @@ def parse_callback_data(bot, raw):
130131 return name , None
131132
132133
133- def get_callback_data (bot , name , data = None ):
134+ def get_callback_data (bot , chat , name , data = None ):
134135 """Get the callback data for the provided name and data"""
135136 name = hashed_callback_name (name )
136137
@@ -145,12 +146,18 @@ def get_callback_data(bot, name, data=None):
145146 )
146147
147148 # Get the signature of the hook name and data
148- signature = crypto . get_hmac (bot , name + data )
149+ signature = get_signature (bot , chat , name , data )
149150
150151 # Base64 the signature and the hook name together to save space
151152 return (base64 .b64encode (signature + name ) + data ).decode ("utf-8" )
152153
153154
155+ def get_signature (bot , chat , name , data ):
156+ """Generate a signature for the provided information"""
157+ chat_id = str (chat .id ).encode ("utf-8" )
158+ return crypto .get_hmac (bot , name + b'\0 ' + chat_id + b'\0 ' + data )
159+
160+
154161def hashed_callback_name (name ):
155162 """Get the hashed name of a callback"""
156163 # Get only the first 8 bytes of the hash to fit it into the payload
@@ -159,8 +166,11 @@ def hashed_callback_name(name):
159166
160167def process (bot , chains , update ):
161168 """Process a callback sent to the bot"""
169+ chat = update .callback_query .message .chat
170+ raw = update .callback_query ._data
171+
162172 try :
163- name , data = parse_callback_data (bot , update . callback_query . _data )
173+ name , data = parse_callback_data (bot , chat , raw )
164174 except crypto .TamperedMessageError :
165175 bot .logger .warn (
166176 "The user tampered with the #%s update's data. Skipped it."
0 commit comments