admin_page_server.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. """DWC Network Server Emulator
  2. Copyright (C) 2014 SMTDDR
  3. Copyright (C) 2014 kyle95wm
  4. Copyright (C) 2014 AdmiralCurtiss
  5. Copyright (C) 2015 Sepalani
  6. This program is free software: you can redistribute it and/or modify
  7. it under the terms of the GNU Affero General Public License as
  8. published by the Free Software Foundation, either version 3 of the
  9. License, or (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU Affero General Public License for more details.
  14. You should have received a copy of the GNU Affero General Public License
  15. along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. """
  17. from twisted.web import server, resource
  18. from twisted.internet import reactor
  19. from twisted.internet.error import ReactorAlreadyRunning
  20. import base64
  21. import codecs
  22. import sqlite3
  23. import collections
  24. import json
  25. import os.path
  26. import logging
  27. import other.utils as utils
  28. import gamespy.gs_utility as gs_utils
  29. import dwc_config
  30. logger = dwc_config.get_logger('AdminPage')
  31. _, port = dwc_config.get_ip_port('AdminPage')
  32. # Example of adminpageconf.json
  33. #
  34. # {"username":"admin","password":"opensesame"}
  35. #
  36. # NOTE: Must use double-quotes or json module will fail
  37. # NOTE2: Do not check the .json file into public git!
  38. adminpageconf = None
  39. admin_username = None
  40. admin_password = None
  41. if os.path.exists('adminpageconf.json'):
  42. try:
  43. adminpageconf = json.loads(file('adminpageconf.json').read().strip())
  44. admin_username = str(adminpageconf['username'])
  45. admin_password = str(adminpageconf['password'])
  46. except Exception as e:
  47. logger.log(logging.WARNING,
  48. "Couldn't read adminpageconf.json. "
  49. "Admin page will not be available.")
  50. logger.log(logging.WARNING, str(e))
  51. adminpageconf = None
  52. admin_username = None
  53. admin_password = None
  54. else:
  55. logger.log(logging.INFO,
  56. "adminpageconf.json not found. "
  57. "Admin page will not be available.")
  58. class AdminPage(resource.Resource):
  59. isLeaf = True
  60. def __init__(self, adminpage):
  61. self.adminpage = adminpage
  62. def get_header(self, title=None):
  63. if not title:
  64. title = 'AltWfc Admin Page'
  65. s = """
  66. <html>
  67. <head>
  68. <title>%s</title>
  69. </head>
  70. <body>
  71. <p>
  72. %s | %s | %s
  73. </p>
  74. """ % (title,
  75. '<a href="/banhammer">All Users</a>',
  76. '<a href="/consoles">Consoles</a>',
  77. '<a href="/banlist">Active Bans</a>')
  78. return s
  79. def get_footer(self):
  80. s = """
  81. </body>
  82. </html>
  83. """
  84. return s
  85. def is_authorized(self, request):
  86. is_auth = False
  87. response_code = 401
  88. error_message = "Authorization required!"
  89. address = request.getClientIP()
  90. try:
  91. expected_auth = base64.encodestring(
  92. admin_username + ":" + admin_password
  93. ).strip()
  94. actual_auth = request.getAllHeaders()['authorization'] \
  95. .replace("Basic ", "") \
  96. .strip()
  97. if actual_auth == expected_auth:
  98. logger.log(logging.INFO, "%s Auth Success", address)
  99. is_auth = True
  100. except Exception as e:
  101. logger.log(logging.INFO, "%s Auth Error: %s", address, str(e))
  102. if not is_auth:
  103. logger.log(logging.INFO, "%s Auth Failure", address)
  104. request.setResponseCode(response_code)
  105. request.setHeader('WWW-Authenticate', 'Basic realm="ALTWFC"')
  106. request.write(error_message)
  107. return is_auth
  108. def update_banlist(self, request):
  109. address = request.getClientIP()
  110. dbconn = sqlite3.connect('gpcm.db')
  111. gameid = request.args['gameid'][0].upper().strip()
  112. ipaddr = request.args['ipaddr'][0].strip()
  113. actiontype = request.args['action'][0]
  114. if not gameid.isalnum():
  115. request.setResponseCode(500)
  116. logger.log(logging.INFO,
  117. "%s Bad data %s %s",
  118. address, gameid, ipaddr)
  119. return "Bad data"
  120. # This strips the region identifier from game IDs, not sure if this
  121. # actually always accurate but limited testing suggests it is
  122. if len(gameid) > 3:
  123. gameid = gameid[:-1]
  124. if actiontype == 'ban':
  125. dbconn.cursor().execute(
  126. 'INSERT INTO banned VALUES(?,?)',
  127. (gameid, ipaddr)
  128. )
  129. responsedata = "Added gameid=%s, ipaddr=%s" % (gameid, ipaddr)
  130. else:
  131. dbconn.cursor().execute(
  132. 'DELETE FROM banned WHERE gameid=? AND ipaddr=?',
  133. (gameid, ipaddr)
  134. )
  135. responsedata = "Removed gameid=%s, ipaddr=%s" % (gameid, ipaddr)
  136. dbconn.commit()
  137. dbconn.close()
  138. logger.log(logging.INFO, "%s %s", address, responsedata)
  139. request.setHeader("Content-Type", "text/html; charset=utf-8")
  140. referer = request.getHeader('referer')
  141. if not referer:
  142. referer = "/banhammer"
  143. request.setHeader("Location", referer)
  144. request.setResponseCode(303)
  145. return responsedata
  146. def update_consolelist(self, request):
  147. address = request.getClientIP()
  148. dbconn = sqlite3.connect('gpcm.db')
  149. macadr = request.args['macadr'][0].strip()
  150. actiontype = request.args['action'][0]
  151. if not macadr.isalnum():
  152. request.setResponseCode(500)
  153. logger.log(logging.INFO, "%s Bad data %s", address, macadr)
  154. return "Bad data"
  155. if actiontype == 'add':
  156. dbconn.cursor().execute(
  157. 'INSERT INTO pending VALUES(?)',
  158. (macadr,)
  159. )
  160. dbconn.cursor().execute(
  161. 'INSERT INTO registered VALUES(?)',
  162. (macadr,)
  163. )
  164. responsedata = "Added macadr=%s" % (macadr)
  165. elif actiontype == 'activate':
  166. dbconn.cursor().execute(
  167. 'INSERT INTO registered VALUES(?)',
  168. (macadr,)
  169. )
  170. responsedata = "Activated console belonging to %s" % (macadr)
  171. else:
  172. dbconn.cursor().execute(
  173. 'DELETE FROM pending WHERE macadr=?',
  174. (macadr,)
  175. )
  176. dbconn.cursor().execute(
  177. 'DELETE FROM registered WHERE macadr=?',
  178. (macadr,)
  179. )
  180. responsedata = "Removed macadr=%s" % (macadr)
  181. dbconn.commit()
  182. dbconn.close()
  183. logger.log(logging.INFO, "%s %s", address, responsedata)
  184. request.setHeader("Content-Type", "text/html; charset=utf-8")
  185. request.setHeader("Location", "/consoles")
  186. referer = request.getHeader('referer')
  187. request.setResponseCode(303)
  188. if not referer:
  189. referer = "/banhammer"
  190. request.setHeader("Location", referer)
  191. request.setResponseCode(303)
  192. return responsedata
  193. def render_banlist(self, request):
  194. address = request.getClientIP()
  195. dbconn = sqlite3.connect('gpcm.db')
  196. logger.log(logging.INFO, "%s Viewed banlist", address)
  197. responsedata = """
  198. <a href="http://%%20:%%20@%s">[CLICK HERE TO LOG OUT]</a>
  199. <table border='1'>
  200. <tr>
  201. <td>gameid</td>
  202. <td>ipAddr</td>
  203. </tr>""" % (request.getHeader('host'))
  204. for row in dbconn.cursor().execute("SELECT * FROM banned"):
  205. gameid = str(row[0])
  206. ipaddr = str(row[1])
  207. # TODO: Use .format()/positional arguments
  208. responsedata += """
  209. <tr>
  210. <td>%s</td>
  211. <td>%s</td>
  212. <td>
  213. <form action='updatebanlist' method='POST'>
  214. <input type='hidden' name='gameid' value='%s'>
  215. <input type='hidden' name='ipaddr' value='%s'>
  216. <input type='hidden' name='action' value='unban'>
  217. <input type='submit' value='----- UNBAN -----'>
  218. </form>
  219. </td>
  220. </tr>""" % (gameid, ipaddr, gameid, ipaddr)
  221. responsedata += "</table>"
  222. dbconn.close()
  223. request.setHeader("Content-Type", "text/html; charset=utf-8")
  224. return responsedata
  225. def render_not_available(self, request):
  226. request.setResponseCode(403)
  227. request.setHeader('WWW-Authenticate', 'Basic realm="ALTWFC"')
  228. request.write('No admin credentials set. Admin page is not available.')
  229. def render_blacklist(self, request):
  230. sqlstatement = """
  231. SELECT users.profileid, enabled, data, users.gameid, console,
  232. users.userid
  233. FROM nas_logins
  234. INNER JOIN users
  235. ON users.userid = nas_logins.userid
  236. INNER JOIN (
  237. SELECT max(profileid) newestpid, userid, gameid, devname
  238. FROM users
  239. GROUP BY userid, gameid
  240. ) ij
  241. ON ij.userid = users.userid
  242. AND users.profileid = ij.newestpid
  243. ORDER BY users.gameid"""
  244. dbconn = sqlite3.connect('gpcm.db')
  245. banned_list = []
  246. for row in dbconn.cursor().execute("SELECT * FROM BANNED"):
  247. banned_list.append(str(row[0])+":"+str(row[1]))
  248. responsedata = """
  249. <a href="http://%%20:%%20@%s">[CLICK HERE TO LOG OUT]</a>
  250. <br><br>
  251. <table border='1'>"
  252. <tr>
  253. <td>ingamesn or devname</td>
  254. <td>gameid</td>
  255. <td>Enabled</td>
  256. <td>newest dwc_pid</td>"
  257. <td>gsbrcd</td>
  258. <td>userid</td>
  259. <td>ipAddr</td>
  260. </tr>""" % request.getHeader('host')
  261. for row in dbconn.cursor().execute(sqlstatement):
  262. dwc_pid = str(row[0])
  263. enabled = str(row[1])
  264. nasdata = collections.defaultdict(lambda: '', json.loads(row[2]))
  265. gameid = str(row[3])
  266. is_console = int(str(row[4]))
  267. userid = str(row[5])
  268. gsbrcd = str(nasdata['gsbrcd'])
  269. ipaddr = str(nasdata['ipaddr'])
  270. ingamesn = ''
  271. if 'ingamesn' in nasdata:
  272. ingamesn = str(nasdata['ingamesn'])
  273. elif 'devname' in nasdata:
  274. ingamesn = str(nasdata['devname'])
  275. if ingamesn:
  276. ingamesn = gs_utils.base64_decode(ingamesn)
  277. if is_console:
  278. ingamesn = codecs.utf_16_be_decode(ingamesn)[0]
  279. else:
  280. ingamesn = codecs.utf_16_le_decode(ingamesn)[0]
  281. else:
  282. ingamesn = '[NOT AVAILABLE]'
  283. responsedata += """
  284. <tr>
  285. <td>%s</td>
  286. <td>%s</td>
  287. <td>%s</td>
  288. <td>%s</td>
  289. <td>%s</td>
  290. <td>%s</td>
  291. <td>%s</td>
  292. """ % (ingamesn,
  293. gameid,
  294. enabled,
  295. dwc_pid,
  296. gsbrcd,
  297. userid,
  298. ipaddr)
  299. if gameid[:-1] + ":" + ipaddr in banned_list:
  300. responsedata += """
  301. <td>
  302. <form action='updatebanlist' method='POST'>
  303. <input type='hidden' name='gameid' value='%s'>
  304. <input type='hidden' name='ipaddr' value='%s'>
  305. <input type='hidden' name='action' value='unban'>
  306. <input type='submit' value='----- unban -----'>
  307. </form>
  308. </td>
  309. </tr>""" % (gameid, ipaddr)
  310. else:
  311. responsedata += """
  312. <td>
  313. <form action='updatebanlist' method='POST'>
  314. <input type='hidden' name='gameid' value='%s'>
  315. <input type='hidden' name='ipaddr' value='%s'>
  316. <input type='hidden' name='action' value='ban'>
  317. <input type='submit' value='Ban'>
  318. </form>
  319. </td>
  320. </tr>
  321. """ % (gameid, ipaddr)
  322. responsedata += "</table>"
  323. dbconn.close()
  324. request.setHeader("Content-Type", "text/html; charset=utf-8")
  325. return responsedata.encode('utf-8')
  326. def enable_disable_user(self, request, enable=True):
  327. address = request.getClientIP()
  328. responsedata = ""
  329. userid = request.args['userid'][0]
  330. gameid = request.args['gameid'][0].upper()
  331. ingamesn = request.args['ingamesn'][0]
  332. if not userid.isdigit() or not gameid.isalnum():
  333. logger.log(logging.INFO,
  334. "%s Bad data %s %s",
  335. address, userid, gameid)
  336. return "Bad data"
  337. dbconn = sqlite3.connect('gpcm.db')
  338. if enable:
  339. dbconn.cursor().execute(
  340. 'UPDATE users SET enabled=1 '
  341. 'WHERE gameid=? AND userid=?',
  342. (gameid, userid)
  343. )
  344. responsedata = "Enabled %s with gameid=%s, userid=%s" % \
  345. (ingamesn, gameid, userid)
  346. else:
  347. dbconn.cursor().execute(
  348. 'UPDATE users SET enabled=0 '
  349. 'WHERE gameid=? AND userid=?',
  350. (gameid, userid)
  351. )
  352. responsedata = "Disabled %s with gameid=%s, userid=%s" % \
  353. (ingamesn, gameid, userid)
  354. dbconn.commit()
  355. dbconn.close()
  356. logger.log(logging.INFO, "%s %s", address, responsedata)
  357. request.setHeader("Content-Type", "text/html; charset=utf-8")
  358. request.setHeader("Location", "/banhammer")
  359. request.setResponseCode(303)
  360. return responsedata
  361. def render_consolelist(self, request):
  362. address = request.getClientIP()
  363. dbconn = sqlite3.connect('gpcm.db')
  364. active_list = []
  365. for row in dbconn.cursor().execute("SELECT * FROM REGISTERED"):
  366. active_list.append(str(row[0]))
  367. logger.log(logging.INFO, "%s Viewed console list", address)
  368. responsedata = (
  369. '<a href="http://%20:%20@' + request.getHeader('host') +
  370. '">[CLICK HERE TO LOG OUT]</a>'
  371. "<form action='updateconsolelist' method='POST'>"
  372. "macadr:<input type='text' name='macadr'>\r\n"
  373. "<input type='hidden' name='action' value='add'>\r\n"
  374. "<input type='submit' value='Register and activate console'>"
  375. "</form>\r\n"
  376. "<table border='1'>"
  377. "<tr><td>macadr</td></tr>\r\n"
  378. )
  379. for row in dbconn.cursor().execute("SELECT * FROM pending"):
  380. macadr = str(row[0])
  381. if macadr in active_list:
  382. responsedata += """
  383. <tr>
  384. <td>%s</td>
  385. <td>
  386. <form action='updateconsolelist' method='POST'>
  387. <input type='hidden' name='macadr' value='%s'>
  388. <input type='hidden' name='action' value='remove'>
  389. <input type='submit' value='Un-register console'>
  390. </form>
  391. </td>
  392. </tr>""" % (macadr, macadr)
  393. else:
  394. responsedata += """
  395. <tr>
  396. <td>%s</td>
  397. <td>
  398. <form action='updateconsolelist' method='POST'>
  399. <input type='hidden' name='macadr' value='%s'>
  400. <input type='hidden' name='action' value='activate'>
  401. <input type='submit' value='Activate console'>
  402. </form>
  403. </td>
  404. </tr>""" % (macadr, macadr)
  405. responsedata += "</table>"
  406. dbconn.close()
  407. request.setHeader("Content-Type", "text/html; charset=utf-8")
  408. return responsedata
  409. def render_GET(self, request):
  410. if not adminpageconf:
  411. self.render_not_available(request)
  412. return ""
  413. if not self.is_authorized(request):
  414. return ""
  415. title = None
  416. response = ''
  417. if request.path == "/banlist":
  418. title = 'AltWfc Banned Users'
  419. response = self.render_banlist(request)
  420. elif request.path == "/banhammer":
  421. title = 'AltWfc Users'
  422. response = self.render_blacklist(request)
  423. elif request.path == "/consoles":
  424. title = "AltWfc Console List"
  425. response = self.render_consolelist(request)
  426. return self.get_header(title) + response + self.get_footer()
  427. def render_POST(self, request):
  428. if not adminpageconf:
  429. self.render_not_available(request)
  430. return ""
  431. if not self.is_authorized(request):
  432. return ""
  433. if request.path == "/updatebanlist":
  434. return self.update_banlist(request)
  435. if request.path == "/updateconsolelist":
  436. return self.update_consolelist(request)
  437. else:
  438. return self.get_header() + self.get_footer()
  439. class AdminPageServer(object):
  440. def start(self):
  441. site = server.Site(AdminPage(self))
  442. reactor.listenTCP(port, site)
  443. logger.log(logging.INFO,
  444. "Now listening for connections on port %d...",
  445. port)
  446. try:
  447. if not reactor.running:
  448. reactor.run(installSignalHandlers=0)
  449. except ReactorAlreadyRunning:
  450. pass
  451. if __name__ == "__main__":
  452. AdminPageServer().start()