cmdctl.py.in 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. #!@PYTHON@
  2. # Copyright (C) 2010 Internet Systems Consortium.
  3. #
  4. # Permission to use, copy, modify, and distribute this software for any
  5. # purpose with or without fee is hereby granted, provided that the above
  6. # copyright notice and this permission notice appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  9. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  10. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  11. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  12. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  13. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  14. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  15. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. ''' cmdctl module is the configuration entry point for all commands from bindctl
  17. or some other web tools client of bind10. cmdctl is pure https server which provi-
  18. des RESTful API. When command client connecting with cmdctl, it should first login
  19. with legal username and password.
  20. When cmdctl starting up, it will collect command specification and
  21. configuration specification/data of other available modules from configmanager, then
  22. wait for receiving request from client, parse the request and resend the request to
  23. the proper module. When getting the request result from the module, send back the
  24. resut to client.
  25. '''
  26. import sys; sys.path.append ('@@PYTHONPATH@@')
  27. import os
  28. import socketserver
  29. import http.server
  30. import urllib.parse
  31. import json
  32. import re
  33. import ssl, socket
  34. import isc
  35. import pprint
  36. import select
  37. import csv
  38. import random
  39. import time
  40. import signal
  41. from isc.config import ccsession
  42. from optparse import OptionParser, OptionValueError
  43. from hashlib import sha1
  44. try:
  45. import threading
  46. except ImportError:
  47. import dummy_threading as threading
  48. __version__ = 'BIND10'
  49. URL_PATTERN = re.compile('/([\w]+)(?:/([\w]+))?/?')
  50. CONFIG_DATA_URL = 'config_data'
  51. MODULE_SPEC_URL = 'module_spec'
  52. # If B10_FROM_BUILD is set in the environment, we use data files
  53. # from a directory relative to that, otherwise we use the ones
  54. # installed on the system
  55. if "B10_FROM_BUILD" in os.environ:
  56. SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/cmdctl"
  57. else:
  58. PREFIX = "@prefix@"
  59. DATAROOTDIR = "@datarootdir@"
  60. SPECFILE_PATH = "@datadir@/@PACKAGE@".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  61. SPECFILE_LOCATION = SPECFILE_PATH + os.sep + "cmdctl.spec"
  62. class CmdctlException(Exception):
  63. pass
  64. class SecureHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
  65. '''https connection request handler.
  66. Currently only GET and POST are supported. '''
  67. def do_GET(self):
  68. '''The client should send its session id in header with
  69. the name 'cookie'
  70. '''
  71. self.session_id = self.headers.get('cookie')
  72. rcode, reply = http.client.OK, []
  73. if self._is_session_valid():
  74. if self._is_user_logged_in():
  75. rcode, reply = self._handle_get_request()
  76. else:
  77. rcode, reply = http.client.UNAUTHORIZED, ["please login"]
  78. else:
  79. rcode = http.client.BAD_REQUEST
  80. self.send_response(rcode)
  81. self.end_headers()
  82. self.wfile.write(json.dumps(reply).encode())
  83. def _handle_get_request(self):
  84. '''Currently only support the following three url GET request '''
  85. id, module = self._parse_request_path()
  86. return self.server.get_reply_data_for_GET(id, module)
  87. def _is_session_valid(self):
  88. return self.session_id
  89. def _is_user_logged_in(self):
  90. login_time = self.server.user_sessions.get(self.session_id)
  91. if not login_time:
  92. return False
  93. idle_time = time.time() - login_time
  94. if idle_time > self.server.idle_timeout:
  95. return False
  96. # Update idle time
  97. self.server.user_sessions[self.session_id] = time.time()
  98. return True
  99. def _parse_request_path(self):
  100. '''Parse the url, the legal url should like /ldh or /ldh/ldh '''
  101. groups = URL_PATTERN.match(self.path)
  102. if not groups:
  103. return (None, None)
  104. else:
  105. return (groups.group(1), groups.group(2))
  106. def do_POST(self):
  107. '''Process POST request. '''
  108. '''Process user login and send command to proper module
  109. The client should send its session id in header with
  110. the name 'cookie'
  111. '''
  112. self.session_id = self.headers.get('cookie')
  113. rcode, reply = http.client.OK, []
  114. if self._is_session_valid():
  115. if self.path == '/login':
  116. rcode, reply = self._handle_login()
  117. elif self._is_user_logged_in():
  118. rcode, reply = self._handle_post_request()
  119. else:
  120. rcode, reply = http.client.UNAUTHORIZED, ["please login"]
  121. else:
  122. rcode, reply = http.client.BAD_REQUEST, ["session isn't valid"]
  123. self.send_response(rcode)
  124. self.end_headers()
  125. self.wfile.write(json.dumps(reply).encode())
  126. def _handle_login(self):
  127. if self._is_user_logged_in():
  128. return http.client.OK, ["user has already login"]
  129. is_user_valid, error_info = self._check_user_name_and_pwd()
  130. if is_user_valid:
  131. self.server.save_user_session_id(self.session_id)
  132. return http.client.OK, ["login success "]
  133. else:
  134. return http.client.UNAUTHORIZED, error_info
  135. def _check_user_name_and_pwd(self):
  136. '''Check user name and its password '''
  137. length = self.headers.get('Content-Length')
  138. if not length:
  139. return False, ["invalid username or password"]
  140. try:
  141. user_info = json.loads((self.rfile.read(int(length))).decode())
  142. except:
  143. return False, ["invalid username or password"]
  144. user_name = user_info.get('username')
  145. if not user_name:
  146. return False, ["need user name"]
  147. if not self.server.get_user_info(user_name):
  148. return False, ["user doesn't exist"]
  149. user_pwd = user_info.get('password')
  150. if not user_pwd:
  151. return False, ["need password"]
  152. local_info = self.server.get_user_info(user_name)
  153. pwd_hashval = sha1((user_pwd + local_info[1]).encode())
  154. if pwd_hashval.hexdigest() != local_info[0]:
  155. return False, ["password doesn't match"]
  156. return True, None
  157. def _handle_post_request(self):
  158. '''Handle all the post request from client. '''
  159. mod, cmd = self._parse_request_path()
  160. if (not mod) or (not cmd):
  161. return http.client.BAD_REQUEST, ['malformed url']
  162. param = None
  163. len = self.headers.get('Content-Length')
  164. if len:
  165. try:
  166. post_str = str(self.rfile.read(int(len)).decode())
  167. param = json.loads(post_str)
  168. except:
  169. pass
  170. rcode, reply = self.server.send_command_to_module(mod, cmd, param)
  171. ret = http.client.OK
  172. if rcode != 0:
  173. ret = http.client.BAD_REQUEST
  174. return ret, reply
  175. def log_request(self, code='-', size='-'):
  176. '''Rewrite the log request function, log nothing.'''
  177. pass
  178. class CommandControl():
  179. '''Get all modules' config data/specification from configmanager.
  180. receive command from client and resend it to proper module.
  181. '''
  182. def __init__(self, httpserver, verbose = False):
  183. ''' httpserver: the http server which use the object of
  184. CommandControl to communicate with other modules. '''
  185. self._verbose = verbose
  186. self._httpserver = httpserver
  187. self._lock = threading.Lock()
  188. self._setup_session()
  189. self.modules_spec = self._get_modules_specification()
  190. self._config_data = self._get_config_data_from_config_manager()
  191. self._serving = True
  192. self._start_msg_handle_thread()
  193. def _setup_session(self):
  194. '''Setup the session for receving the commands
  195. sent from other modules. There are two sessions
  196. for cmdctl, one(self.module_cc) is used for receiving
  197. commands sent from other modules, another one (self._cc)
  198. is used to send the command from Bindctl or other tools
  199. to proper modules.'''
  200. self._cc = isc.cc.Session()
  201. self._module_cc = isc.config.ModuleCCSession(SPECFILE_LOCATION,
  202. self.config_handler,
  203. self.command_handler)
  204. self._module_name = self._module_cc.get_module_spec().get_module_name()
  205. self._cmdctl_config_data = self._module_cc.get_full_config()
  206. self._module_cc.start()
  207. def _accounts_file_check(self, filepath):
  208. ''' Check whether the accounts file is valid, each row
  209. should be a list with 3 items.'''
  210. csvfile = None
  211. errstr = None
  212. try:
  213. csvfile = open(filepath)
  214. reader = csv.reader(csvfile)
  215. for row in reader:
  216. a = (row[0], row[1], row[2])
  217. except (IOError, IndexError) as e:
  218. errstr = 'Invalid accounts file: ' + str(e)
  219. finally:
  220. if csvfile:
  221. csvfile.close()
  222. return errstr
  223. def _config_data_check(self, new_config):
  224. ''' Check whether the new config data is valid or
  225. not. '''
  226. errstr = None
  227. for key in new_config:
  228. if key == 'version':
  229. continue
  230. elif key in ['key_file', 'cert_file']:
  231. #TODO, only check whether the file exist,
  232. # further check need to be done: eg. whether
  233. # the private/certificate is valid.
  234. path = new_config[key]
  235. if not os.path.exists(path):
  236. errstr = "the file doesn't exist: " + path
  237. elif key == 'accounts_file':
  238. errstr = self._accounts_file_check(new_config[key])
  239. else:
  240. errstr = 'unknown config item: ' + key
  241. if errstr != None:
  242. self.log_info('Fail to apply config data, ' + errstr)
  243. return ccsession.create_answer(1, errstr)
  244. return ccsession.create_answer(0)
  245. def config_handler(self, new_config):
  246. answer = self._config_data_check(new_config)
  247. rcode, val = ccsession.parse_answer(answer)
  248. if rcode != 0:
  249. return answer
  250. with self._lock:
  251. for key in new_config:
  252. if key in self._cmdctl_config_data:
  253. self._cmdctl_config_data[key] = new_config[key]
  254. return answer
  255. def command_handler(self, command, args):
  256. answer = ccsession.create_answer(0)
  257. if command == ccsession.COMMAND_MODULE_SPECIFICATION_UPDATE:
  258. with self._lock:
  259. self.modules_spec[args[0]] = args[1]
  260. elif command == ccsession.COMMAND_SHUTDOWN:
  261. #When cmdctl get 'shutdown' command from boss,
  262. #shutdown the outer httpserver.
  263. self._httpserver.shutdown()
  264. self._serving = False
  265. elif command == 'print_settings':
  266. answer = ccsession.create_answer(0, self._cmdctl_config_data)
  267. else:
  268. answer = ccsession.create_answer(1, 'unknown command: ' + command)
  269. return answer
  270. def _start_msg_handle_thread(self):
  271. ''' Start one thread to handle received message from msgq.'''
  272. td = threading.Thread(target=self._handle_msg_from_msgq)
  273. td.daemon = True
  274. td.start()
  275. def _handle_msg_from_msgq(self):
  276. '''Process all the received commands with module session. '''
  277. while self._serving:
  278. self._module_cc.check_command()
  279. def _parse_command_result(self, rcode, reply):
  280. '''Ignore the error reason when command rcode isn't 0, '''
  281. if rcode != 0:
  282. return {}
  283. return reply
  284. def _get_config_data_from_config_manager(self):
  285. '''Get config data for all modules from configmanager '''
  286. rcode, reply = self.send_command('ConfigManager', ccsession.COMMAND_GET_CONFIG)
  287. return self._parse_command_result(rcode, reply)
  288. def _update_config_data(self, module_name, command_name):
  289. '''Get lastest config data for all modules from configmanager '''
  290. if module_name == 'ConfigManager' and command_name == ccsession.COMMAND_SET_CONFIG:
  291. data = self._get_config_data_from_config_manager()
  292. with self._lock:
  293. self._config_data = data
  294. def get_config_data(self):
  295. with self._lock:
  296. data = self._config_data
  297. return data
  298. def get_modules_spec(self):
  299. with self._lock:
  300. spec = self.modules_spec
  301. return spec
  302. def _get_modules_specification(self):
  303. '''Get all the modules' specification files. '''
  304. rcode, reply = self.send_command('ConfigManager', ccsession.COMMAND_GET_MODULE_SPEC)
  305. return self._parse_command_result(rcode, reply)
  306. def send_command_with_check(self, module_name, command_name, params = None):
  307. '''Before send the command to modules, check if module_name, command_name
  308. parameters are legal according the spec file of the module.
  309. Return rcode, dict. TODO, the rcode should be defined properly.
  310. rcode = 0: dict is the correct returned value.
  311. rcode > 0: dict is : { 'error' : 'error reason' }
  312. '''
  313. # core module ConfigManager does not have a specification file
  314. if module_name == 'ConfigManager':
  315. return self.send_command(module_name, command_name, params)
  316. specs = self.get_modules_spec()
  317. if module_name not in specs.keys():
  318. return 1, {'error' : 'unknown module'}
  319. spec_obj = isc.config.module_spec.ModuleSpec(specs[module_name], False)
  320. errors = []
  321. if not spec_obj.validate_command(command_name, params, errors):
  322. return 1, {'error': errors[0]}
  323. return self.send_command(module_name, command_name, params)
  324. def send_command(self, module_name, command_name, params = None):
  325. '''Send the command from bindctl to proper module. '''
  326. errstr = 'unknown error'
  327. if self._verbose:
  328. self.log_info("Begin send command '%s' to module '%s'" %(command_name, module_name))
  329. if module_name == self._module_name:
  330. # Process the command sent to cmdctl directly.
  331. answer = self.command_handler(command_name, params)
  332. else:
  333. msg = ccsession.create_command(command_name, params)
  334. seq = self._cc.group_sendmsg(msg, module_name)
  335. #TODO, it may be blocked, msqg need to add a new interface waiting in timeout.
  336. answer, env = self._cc.group_recvmsg(False, seq)
  337. if self._verbose:
  338. self.log_info("Finish send command '%s' to module '%s'" % (command_name, module_name))
  339. if answer:
  340. try:
  341. rcode, arg = ccsession.parse_answer(answer)
  342. if rcode == 0:
  343. self._update_config_data(module_name, command_name)
  344. if arg != None:
  345. return rcode, arg
  346. else:
  347. return rcode, {}
  348. else:
  349. # TODO: exception
  350. errstr = str(answer['result'][1])
  351. except ccsession.ModuleCCSessionError as mcse:
  352. errstr = str("Error in ccsession answer:") + str(mcse)
  353. self.log_info(errstr)
  354. return 1, {'error': errstr}
  355. def log_info(self, msg):
  356. sys.stdout.write("[b10-cmdctl] %s\n" % str(msg))
  357. def get_cmdctl_config_data(self):
  358. ''' If running in source code tree, use keyfile, certificate
  359. and user accounts file in source code. '''
  360. if "B10_FROM_SOURCE" in os.environ:
  361. sysconf_path = os.environ["B10_FROM_SOURCE"] + "/src/bin/cmdctl/"
  362. accountsfile = sysconf_path + "cmdctl-accounts.csv"
  363. keyfile = sysconf_path + "cmdctl-keyfile.pem"
  364. certfile = sysconf_path + "cmdctl-certfile.pem"
  365. return (keyfile, certfile, accountsfile)
  366. with self._lock:
  367. keyfile = self._cmdctl_config_data.get('key_file')
  368. certfile = self._cmdctl_config_data.get('cert_file')
  369. accountsfile = self._cmdctl_config_data.get('accounts_file')
  370. return (keyfile, certfile, accountsfile)
  371. class SecureHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
  372. '''Make the server address can be reused.'''
  373. allow_reuse_address = True
  374. def __init__(self, server_address, RequestHandlerClass,
  375. CommandControlClass,
  376. idle_timeout = 1200, verbose = False):
  377. '''idle_timeout: the max idle time for login'''
  378. try:
  379. http.server.HTTPServer.__init__(self, server_address, RequestHandlerClass)
  380. except socket.error as err:
  381. raise CmdctlException("Error creating server, because: %s \n" % str(err))
  382. self.user_sessions = {}
  383. self.idle_timeout = idle_timeout
  384. self.cmdctl = CommandControlClass(self, verbose)
  385. self._verbose = verbose
  386. self._lock = threading.Lock()
  387. self._user_infos = {}
  388. self._accounts_file = None
  389. def _create_user_info(self, accounts_file):
  390. '''Read all user's name and its' salt, hashed password
  391. from accounts file.'''
  392. if (self._accounts_file == accounts_file) and (len(self._user_infos) > 0):
  393. return
  394. with self._lock:
  395. self._user_infos = {}
  396. csvfile = None
  397. try:
  398. csvfile = open(accounts_file)
  399. reader = csv.reader(csvfile)
  400. for row in reader:
  401. self._user_infos[row[0]] = [row[1], row[2]]
  402. except (IOError, IndexError) as e:
  403. self.log_info("Fail to read user database, %s" % e)
  404. finally:
  405. if csvfile:
  406. csvfile.close()
  407. self._accounts_file = accounts_file
  408. if len(self._user_infos) == 0:
  409. self.log_info("Fail to get user information, will deny any user")
  410. def get_user_info(self, username):
  411. '''Get user's salt and hashed string. If the user
  412. doesn't exist, return None, or else, the list
  413. [salt, hashed password] will be returned.'''
  414. with self._lock:
  415. info = self._user_infos.get(username)
  416. return info
  417. def save_user_session_id(self, session_id):
  418. ''' Record user's id and login time. '''
  419. self.user_sessions[session_id] = time.time()
  420. def _check_key_and_cert(self, key, cert):
  421. # TODO, check the content of key/certificate file
  422. if not os.path.exists(key):
  423. raise CmdctlException("key file '%s' doesn't exist " % key)
  424. if not os.path.exists(cert):
  425. raise CmdctlException("certificate file '%s' doesn't exist " % cert)
  426. def _wrap_socket_in_ssl_context(self, sock, key, cert):
  427. try:
  428. self._check_key_and_cert(key, cert)
  429. ssl_sock = ssl.wrap_socket(sock,
  430. server_side = True,
  431. certfile = cert,
  432. keyfile = key,
  433. ssl_version = ssl.PROTOCOL_SSLv23)
  434. return ssl_sock
  435. except (ssl.SSLError, CmdctlException) as err :
  436. self.log_info("Deny client's connection because %s" % str(err))
  437. self.close_request(sock)
  438. # raise socket error to finish the request
  439. raise socket.error
  440. def get_request(self):
  441. '''Get client request socket and wrap it in SSL context. '''
  442. key, cert, account_file = self.cmdctl.get_cmdctl_config_data()
  443. self._create_user_info(account_file)
  444. newsocket, fromaddr = self.socket.accept()
  445. ssl_sock = self._wrap_socket_in_ssl_context(newsocket, key, cert)
  446. return (ssl_sock, fromaddr)
  447. def get_reply_data_for_GET(self, id, module):
  448. '''Currently only support the following three url GET request '''
  449. rcode, reply = http.client.NO_CONTENT, []
  450. if not module:
  451. if id == CONFIG_DATA_URL:
  452. rcode, reply = http.client.OK, self.cmdctl.get_config_data()
  453. elif id == MODULE_SPEC_URL:
  454. rcode, reply = http.client.OK, self.cmdctl.get_modules_spec()
  455. return rcode, reply
  456. def send_command_to_module(self, module_name, command_name, params):
  457. return self.cmdctl.send_command_with_check(module_name, command_name, params)
  458. def log_info(self, msg):
  459. sys.stdout.write("[b10-cmdctl] %s\n" % str(msg))
  460. httpd = None
  461. def signal_handler(signal, frame):
  462. if httpd:
  463. httpd.shutdown()
  464. sys.exit(0)
  465. def set_signal_handler():
  466. signal.signal(signal.SIGTERM, signal_handler)
  467. signal.signal(signal.SIGINT, signal_handler)
  468. def run(addr = 'localhost', port = 8080, idle_timeout = 1200, verbose = False):
  469. ''' Start cmdctl as one https server. '''
  470. if verbose:
  471. sys.stdout.write("[b10-cmdctl] starting on %s port:%d\n" %(addr, port))
  472. httpd = SecureHTTPServer((addr, port), SecureHTTPRequestHandler,
  473. CommandControl, idle_timeout, verbose)
  474. httpd.serve_forever()
  475. def check_port(option, opt_str, value, parser):
  476. if (value < 0) or (value > 65535):
  477. raise OptionValueError('%s requires a port number (0-65535)' % opt_str)
  478. parser.values.port = value
  479. def check_addr(option, opt_str, value, parser):
  480. ipstr = value
  481. ip_family = socket.AF_INET
  482. if (ipstr.find(':') != -1):
  483. ip_family = socket.AF_INET6
  484. try:
  485. socket.inet_pton(ip_family, ipstr)
  486. except:
  487. raise OptionValueError("%s invalid ip address" % ipstr)
  488. parser.values.addr = value
  489. def set_cmd_options(parser):
  490. parser.add_option('-p', '--port', dest = 'port', type = 'int',
  491. action = 'callback', callback=check_port,
  492. default = '8080', help = 'port cmdctl will use')
  493. parser.add_option('-a', '--address', dest = 'addr', type = 'string',
  494. action = 'callback', callback=check_addr,
  495. default = '127.0.0.1', help = 'IP address cmdctl will use')
  496. parser.add_option('-i', '--idle-timeout', dest = 'idle_timeout', type = 'int',
  497. default = '1200', help = 'login idle time out')
  498. parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
  499. help="display more about what is going on")
  500. if __name__ == '__main__':
  501. set_signal_handler()
  502. parser = OptionParser(version = __version__)
  503. set_cmd_options(parser)
  504. (options, args) = parser.parse_args()
  505. result = 1 # in case of failure
  506. try:
  507. run(options.addr, options.port, options.idle_timeout, options.verbose)
  508. result = 0
  509. except isc.cc.SessionError as err:
  510. sys.stderr.write("[b10-cmdctl] Error creating b10-cmdctl, "
  511. "is the command channel daemon running?\n")
  512. except KeyboardInterrupt:
  513. sys.stderr.write("[b10-cmdctl] exit from Cmdctl\n")
  514. except CmdctlException as err:
  515. sys.stderr.write("[b10-cmdctl] " + str(err) + "\n")
  516. if httpd:
  517. httpd.shutdown()
  518. sys.exit(result)