-
Notifications
You must be signed in to change notification settings - Fork 2
/
twittrouter.py
299 lines (264 loc) · 12.2 KB
/
twittrouter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#!/usr/bin/env python
#coding=utf-8
from __future__ import with_statement
from __future__ import unicode_literals
import sys
if sys.version_info < (2, 6):
import simplejson as json
else:
import json
try:
import gevent, gevent.monkey
gevent.monkey.patch_all(dns=gevent.version_info[0]>=1)
except ImportError:
gevent = None
print >>sys.stderr, 'warning: gevent not found, using threading instead'
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SimpleHTTPServer import SimpleHTTPRequestHandler
from SocketServer import ThreadingMixIn
#from twfoller import check_friendship,get_oauth,setup_oauth
from requests_oauthlib import OAuth1
from urlparse import parse_qs
import requests
import cgi
import threading
import os
import time
import re
import logging
import Queue
import signal
REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token"
AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize?oauth_token="
ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token"
def setup_oauth(CONSUMER_KEY,CONSUMER_SECRET):
while True:
"""Authorize your app via identifier."""
# Request token
oauth = OAuth1(CONSUMER_KEY, client_secret=CONSUMER_SECRET)
r = requests.post(url=REQUEST_TOKEN_URL, auth=oauth)
credentials = parse_qs(r.content)
resource_owner_key = credentials.get('oauth_token')[0]
resource_owner_secret = credentials.get('oauth_token_secret')[0]
# Authorize
authorize_url = AUTHORIZE_URL + resource_owner_key
#print 'Please go here and authorize: ' + authorize_url
#verifier = raw_input('Please input the verifier: ')
yield authorize_url
try:
verifier = verifier_queue.get(timeout=1)
except Empty:
continue
logging.info("get verifier = %s" %verifier)
oauth = OAuth1(CONSUMER_KEY,
client_secret=CONSUMER_SECRET,
resource_owner_key=resource_owner_key,
resource_owner_secret=resource_owner_secret,
verifier=verifier)
# Finally, Obtain the Access Token
r = requests.post(url=ACCESS_TOKEN_URL, auth=oauth)
credentials = parse_qs(r.content)
token = credentials.get('oauth_token')[0]
secret = credentials.get('oauth_token_secret')[0]
screen_name = credentials.get('screen_name')[0]
logging.info("get token=%s secret=%s screen_name=%s" %(token,secret,screen_name))
yield token, secret, screen_name
def get_oauth(CONSUMER_KEY,CONSUMER_SECRET,OAUTH_TOKEN,OAUTH_TOKEN_SECRET):
oauth = OAuth1(CONSUMER_KEY,
client_secret=CONSUMER_SECRET,
resource_owner_key=OAUTH_TOKEN,
resource_owner_secret=OAUTH_TOKEN_SECRET)
return oauth
def check_friendship(master,friend,auth):
r = requests.get(url="https://api.twitter.com/1.1/friendships/lookup.json?screen_name=%s,%s" %(master,friend), auth=auth).json()
return len(r) == 2 and (r[1]['connections'] != ['none'] or r[0]['connections'] != ['none'])
class RequestHandler(BaseHTTPRequestHandler,SimpleHTTPRequestHandler):
oauth_verifier = None
oauth_request_url = None
def send_to_client(self,filename):
self._writeheaders()
with open(filename,'r') as f:
self.wfile.write(f.read().decode('utf-8').replace('twitterid',TwitterID).encode('utf-8'))
self.wfile.close()
def _writeheaders(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def _write_redirect_headers(self,redirect_url):
self.send_response(301)
self.send_header('Location', redirect_url)
self.end_headers()
def do_HEAD(self):
self._writeheaders()
def do_GET(self):
if '.ico' in self.path or '.png' in self.path:
SimpleHTTPRequestHandler.do_GET(self)
if '/echo' == self.path and self.client_address[0] == '127.0.0.1':
logging.info("echo to test the server")
self._writeheaders()
self.wfile.write("helloworld")
self.wfile.close()
elif "&oauth_verifier=" in self.path and self.client_address[0] == '127.0.0.1':
if RequestHandler.oauth_verifier:
while RequestHandler.oauth_request_url:
logging.info("waiting for oauth finish")
time.sleep(1)
self.send_to_client("config_done.html")
return
RequestHandler.oauth_verifier = self.path.split('=')[-1]
logging.info("get oauth_verifier=%s" %RequestHandler.oauth_verifier)
verifier_queue.put(self.path.split('=')[-1])
global oauth,TwitterID
OAUTH_TOKEN,OAUTH_TOKEN_SECRET,screen_name = gen.next()
if TwitterID == screen_name:
self.send_to_client("config_done.html")
RequestHandler.oauth_verifier = None
RequestHandler.oauth_request_url = None
return
oauth = get_oauth(CONSUMER_KEY,CONSUMER_SECRET,OAUTH_TOKEN,OAUTH_TOKEN_SECRET)
TwitterID = screen_name
if config["TwitterID"] == screen_name:
self.send_to_client("config_done.html")
RequestHandler.oauth_verifier = None
RequestHandler.oauth_request_url = None
return
elif screen_name in config.keys():
config["TwitterID"] = TwitterID
else:
config["TwitterID"] = TwitterID
new_auth = {}
new_auth["OAUTH_TOKEN"] = OAUTH_TOKEN
new_auth["OAUTH_TOKEN_SECRET"] = OAUTH_TOKEN_SECRET
config[TwitterID] = new_auth
with open(pathconfig, 'wb') as f:
json.dump(config,f)
self.send_to_client("config_done.html")
RequestHandler.oauth_verifier = None
RequestHandler.oauth_request_url = None
elif "/config" == self.path and self.client_address[0] == "127.0.0.1":
if TwitterID == "twitrouter":
self.send_to_client("config.html")
else:
self.send_to_client("config_done.html")
else:
self.send_to_client("BASEHTML.html")
def do_POST(self):
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
keep_blank_values=True,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':'text/html',
})
if self.client_address[0] == "127.0.0.1" and form and 'twitter_auth' in form:
logging.info("auth input %s" %form['twitter_auth'].value)
twitter_auth = form['twitter_auth'].value.strip()
if twitter_auth == TwitterID:
self.send_to_client("config_done.html")
return
if re.match(r'^\w+$', twitter_auth.replace('_','')) and twitter_auth in config.keys():
global oauth,TwitterID
TwitterID = twitter_auth
OAUTH_TOKEN = config[twitter_auth]["OAUTH_TOKEN"]
OAUTH_TOKEN_SECRET = config[twitter_auth]["OAUTH_TOKEN_SECRET"]
oauth = get_oauth(CONSUMER_KEY,CONSUMER_SECRET,OAUTH_TOKEN,OAUTH_TOKEN_SECRET)
self.send_to_client("config_done.html")
return
elif RequestHandler.oauth_request_url == None:
RequestHandler.oauth_request_url = gen.next()
self._write_redirect_headers(RequestHandler.oauth_request_url)
else:
self._write_redirect_headers(RequestHandler.oauth_request_url)
return
if not form or 'uname' not in form:
return
post_name = form['uname'].value.strip()
if not re.match(r'^\w+$', post_name.replace('_','')):
logging.warning("you input invalid username %s" %form['uname'].value)
self.send_to_client("VERIFY_FAILED.html")
return
if check_friendship(TwitterID, post_name, auth=oauth):
logging.info("auth success %s" %form['uname'].value)
self.send_to_client("VERIFY_OK.html")
if self.client_address[0] in blocklist:
logging.info("unblock the ip,feel free to use the wifi")
os.system('iptables -t nat -D PREROUTING -s %s -p tcp --dport 80 -j REDIRECT --to-ports 8888' %self.client_address[0])
blocklist.remove(self.client_address[0])
authlist.append(self.client_address[0])
else:
self.send_to_client("VERIFY_FAILED.html")
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
allow_reuse_address = True
def clear_iptables():
logging.info("clearing iptables")
iptables_list = os.popen('iptables -t nat -L PREROUTING').read().strip().split('\n')
ip_port = lambda s: re.findall(r'\d+\.\d+\.\d+\.\d+|8888',s)
ip_port_list = map(ip_port,iptables_list)
for ip_port in ip_port_list:
if len(ip_port) == 2:
print ip_port[0]
os.system('iptables -t nat -D PREROUTING -s %s -p tcp --dport 80 -j REDIRECT --to-ports 8888' %ip_port[0])
def createThread(target,args):
t = threading.Thread(target=target,args=args)
t.setDaemon(1)
t.start()
return t
def getarplist():
time.sleep(5)
clear_iptables()
while event.isSet():
#client = os.popen('arp -n').read().strip().split('\n')
with open('/proc/net/arp', 'r') as f:
client = f.read().strip().split('\n')
ip_mac = lambda s: re.findall(r'\d+\.\d+\.\d+\.\d+|\w+:\w+:\w+:\w+:\w+:\w+',s)
ip_mac_list = map(ip_mac,client)
logging.info('scan the arp list')
for ipmac in ip_mac_list:
if len(ipmac)==2 and (ipmac[1] in whitelist or ipmac[0] in authlist or ipmac[0] in blocklist):
continue
elif len(ipmac)==2:
logging.info("the new client should be blocked.ip == %s,mac == %s" %(ipmac[0],ipmac[1]))
blocklist.append(ipmac[0])
os.system('iptables -t nat -I PREROUTING -s %s -p tcp --dport 80 -j REDIRECT --to-ports 8888' %ipmac[0])
time.sleep(10)
def on_exit(no, info):
logging.warning("on exit")
event.clear()
for ip in blocklist:
os.system('iptables -t nat -D PREROUTING -s %s -p tcp --dport 80 -j REDIRECT --to-ports 8888' %ip)
clear_iptables()
os.kill(os.getpid(),signal.SIGINT)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')
os.chdir(os.path.dirname(__file__) or '.')
pathhome = os.path.join(os.path.dirname(__file__), os.pardir)
pathconfig = os.path.join(pathhome,"twittrouter.json")
if os.path.isfile(pathconfig):
with open(pathconfig, 'rb') as f:
config = json.load(f)
else:
with open('config.json', 'rb') as f:
config = json.load(f)
whitelist = config['whitelist'].split('|')
TwitterID = config['TwitterID']
CONSUMER_KEY = config['CONSUMER_KEY']
CONSUMER_SECRET = config['CONSUMER_SECRET']
OAUTH_TOKEN = config[TwitterID]["OAUTH_TOKEN"]
OAUTH_TOKEN_SECRET = config[TwitterID]['OAUTH_TOKEN_SECRET']
blocklist = []
authlist = []
verifier_queue = Queue.Queue(1)
event = threading.Event()
event.set()
if not (TwitterID and CONSUMER_KEY and CONSUMER_SECRET):
logging.critical("please add TwitterID,CONSUMER_KEY and CONSUMER_SECRET into config.json file")
sys.exit(-1)
print "Hi,@%s,thanks for sharing your wifi to your twitter friends" %TwitterID
oauth = get_oauth(CONSUMER_KEY,CONSUMER_SECRET,OAUTH_TOKEN,OAUTH_TOKEN_SECRET)
gen = setup_oauth(CONSUMER_KEY,CONSUMER_SECRET)
signal.signal(signal.SIGTERM, on_exit)
t = createThread(target = getarplist,args=tuple())
serveraddr = ('', 8888)
srvr = ThreadingHTTPServer(serveraddr, RequestHandler)
srvr.serve_forever()