security.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. #!/usr/bin/env python
  2. # Licensed to the Apache Software Foundation (ASF) under one or more
  3. # contributor license agreements. See the NOTICE file distributed with
  4. # this work for additional information regarding copyright ownership.
  5. # The ASF licenses this file to You under the Apache License, Version 2.0
  6. # (the "License"); you may not use this file except in compliance with
  7. # the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import httplib
  17. import urllib2
  18. import socket
  19. import ssl
  20. import os
  21. import logging
  22. import subprocess
  23. import json
  24. import pprint
  25. import traceback
  26. import hostname
  27. import platform
  28. logger = logging.getLogger()
  29. GEN_AGENT_KEY = 'openssl req -new -newkey rsa:1024 -nodes -keyout "%(keysdir)s'+os.sep+'%(hostname)s.key" '\
  30. '-subj /OU=%(hostname)s/ -out "%(keysdir)s'+os.sep+'%(hostname)s.csr"'
  31. class VerifiedHTTPSConnection(httplib.HTTPSConnection):
  32. """ Connecting using ssl wrapped sockets """
  33. def __init__(self, host, port=None, config=None):
  34. httplib.HTTPSConnection.__init__(self, host, port=port)
  35. self.two_way_ssl_required = False
  36. self.config = config
  37. def connect(self):
  38. self.two_way_ssl_required = self.config.isTwoWaySSLConnection()
  39. logger.debug("Server two-way SSL authentication required: %s" % str(self.two_way_ssl_required))
  40. if self.two_way_ssl_required is True:
  41. logger.info('Server require two-way SSL authentication. Use it instead of one-way...')
  42. if not self.two_way_ssl_required:
  43. try:
  44. sock = self.create_connection()
  45. self.sock = ssl.wrap_socket(sock, cert_reqs=ssl.CERT_NONE)
  46. logger.info('SSL connection established. Two-way SSL authentication is '
  47. 'turned off on the server.')
  48. except (ssl.SSLError, AttributeError):
  49. self.two_way_ssl_required = True
  50. logger.info('Insecure connection to https://' + self.host + ':' + self.port +
  51. '/ failed. Reconnecting using two-way SSL authentication..')
  52. if self.two_way_ssl_required:
  53. self.certMan = CertificateManager(self.config)
  54. self.certMan.initSecurity()
  55. agent_key = self.certMan.getAgentKeyName()
  56. agent_crt = self.certMan.getAgentCrtName()
  57. server_crt = self.certMan.getSrvrCrtName()
  58. sock = self.create_connection()
  59. try:
  60. self.sock = ssl.wrap_socket(sock,
  61. keyfile=agent_key,
  62. certfile=agent_crt,
  63. cert_reqs=ssl.CERT_REQUIRED,
  64. ca_certs=server_crt)
  65. logger.info('SSL connection established. Two-way SSL authentication '
  66. 'completed successfully.')
  67. except ssl.SSLError as err:
  68. logger.error('Two-way SSL authentication failed. Ensure that '
  69. 'server and agent certificates were signed by the same CA '
  70. 'and restart the agent. '
  71. '\nIn order to receive a new agent certificate, remove '
  72. 'existing certificate file from keys directory. As a '
  73. 'workaround you can turn off two-way SSL authentication in '
  74. 'server configuration(ambari.properties) '
  75. '\nExiting..')
  76. raise err
  77. def create_connection(self):
  78. if self.sock:
  79. self.sock.close()
  80. logger.info("SSL Connect being called.. connecting to the server")
  81. sock = socket.create_connection((self.host, self.port), 60)
  82. sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
  83. if self._tunnel_host:
  84. self.sock = sock
  85. self._tunnel()
  86. return sock
  87. class CachedHTTPSConnection:
  88. """ Caches a ssl socket and uses a single https connection to the server. """
  89. def __init__(self, config):
  90. self.connected = False
  91. self.config = config
  92. self.server = hostname.server_hostname(config)
  93. self.port = config.get('server', 'secured_url_port')
  94. self.connect()
  95. def connect(self):
  96. if not self.connected:
  97. self.httpsconn = VerifiedHTTPSConnection(self.server, self.port, self.config)
  98. self.httpsconn.connect()
  99. self.connected = True
  100. # possible exceptions are caught and processed in Controller
  101. def forceClear(self):
  102. self.httpsconn = VerifiedHTTPSConnection(self.server, self.port, self.config)
  103. self.connect()
  104. def request(self, req):
  105. self.connect()
  106. try:
  107. self.httpsconn.request(req.get_method(), req.get_full_url(),
  108. req.get_data(), req.headers)
  109. response = self.httpsconn.getresponse()
  110. readResponse = response.read()
  111. except Exception as ex:
  112. # This exception is caught later in Controller
  113. logger.debug("Error in sending/receving data from the server " +
  114. traceback.format_exc())
  115. logger.info("Encountered communication error. Details: " + repr(ex))
  116. self.connected = False
  117. raise IOError("Error occured during connecting to the server: " + str(ex))
  118. return readResponse
  119. class CertificateManager():
  120. def __init__(self, config):
  121. self.config = config
  122. self.keysdir = os.path.abspath(self.config.get('security', 'keysdir'))
  123. self.server_crt = self.config.get('security', 'server_crt')
  124. self.server_url = 'https://' + hostname.server_hostname(config) + ':' \
  125. + self.config.get('server', 'url_port')
  126. def getAgentKeyName(self):
  127. keysdir = os.path.abspath(self.config.get('security', 'keysdir'))
  128. return keysdir + os.sep + hostname.hostname(self.config) + ".key"
  129. def getAgentCrtName(self):
  130. keysdir = os.path.abspath(self.config.get('security', 'keysdir'))
  131. return keysdir + os.sep + hostname.hostname(self.config) + ".crt"
  132. def getAgentCrtReqName(self):
  133. keysdir = os.path.abspath(self.config.get('security', 'keysdir'))
  134. return keysdir + os.sep + hostname.hostname(self.config) + ".csr"
  135. def getSrvrCrtName(self):
  136. keysdir = os.path.abspath(self.config.get('security', 'keysdir'))
  137. return keysdir + os.sep + "ca.crt"
  138. def checkCertExists(self):
  139. s = os.path.abspath(self.config.get('security', 'keysdir')) + os.sep + "ca.crt"
  140. server_crt_exists = os.path.exists(s)
  141. if not server_crt_exists:
  142. logger.info("Server certicate not exists, downloading")
  143. self.loadSrvrCrt()
  144. else:
  145. logger.info("Server certicate exists, ok")
  146. agent_key_exists = os.path.exists(self.getAgentKeyName())
  147. if not agent_key_exists:
  148. logger.info("Agent key not exists, generating request")
  149. self.genAgentCrtReq()
  150. else:
  151. logger.info("Agent key exists, ok")
  152. agent_crt_exists = os.path.exists(self.getAgentCrtName())
  153. if not agent_crt_exists:
  154. logger.info("Agent certificate not exists, sending sign request")
  155. self.reqSignCrt()
  156. else:
  157. logger.info("Agent certificate exists, ok")
  158. def loadSrvrCrt(self):
  159. get_ca_url = self.server_url + '/cert/ca/'
  160. logger.info("Downloading server cert from " + get_ca_url)
  161. proxy_handler = urllib2.ProxyHandler({})
  162. opener = urllib2.build_opener(proxy_handler)
  163. stream = opener.open(get_ca_url)
  164. response = stream.read()
  165. stream.close()
  166. srvr_crt_f = open(self.getSrvrCrtName(), 'w+')
  167. srvr_crt_f.write(response)
  168. def reqSignCrt(self):
  169. sign_crt_req_url = self.server_url + '/certs/' + hostname.hostname(self.config)
  170. agent_crt_req_f = open(self.getAgentCrtReqName())
  171. agent_crt_req_content = agent_crt_req_f.read()
  172. passphrase_env_var = self.config.get('security', 'passphrase_env_var_name')
  173. passphrase = os.environ[passphrase_env_var]
  174. register_data = {'csr': agent_crt_req_content,
  175. 'passphrase': passphrase}
  176. data = json.dumps(register_data)
  177. proxy_handler = urllib2.ProxyHandler({})
  178. opener = urllib2.build_opener(proxy_handler)
  179. urllib2.install_opener(opener)
  180. req = urllib2.Request(sign_crt_req_url, data, {'Content-Type': 'application/json'})
  181. f = urllib2.urlopen(req)
  182. response = f.read()
  183. f.close()
  184. try:
  185. data = json.loads(response)
  186. logger.debug("Sign response from Server: \n" + pprint.pformat(data))
  187. except Exception:
  188. logger.warn("Malformed response! data: " + str(data))
  189. data = {'result': 'ERROR'}
  190. result = data['result']
  191. if result == 'OK':
  192. agentCrtContent = data['signedCa']
  193. agentCrtF = open(self.getAgentCrtName(), "w")
  194. agentCrtF.write(agentCrtContent)
  195. else:
  196. # Possible exception is catched higher at Controller
  197. logger.error('Certificate signing failed.'
  198. '\nIn order to receive a new agent'
  199. ' certificate, remove existing certificate file from keys '
  200. 'directory. As a workaround you can turn off two-way SSL '
  201. 'authentication in server configuration(ambari.properties) '
  202. '\nExiting..')
  203. raise ssl.SSLError
  204. def genAgentCrtReq(self):
  205. generate_script = GEN_AGENT_KEY % {'hostname': hostname.hostname(self.config),
  206. 'keysdir' : os.path.abspath(self.config.get('security', 'keysdir'))}
  207. logger.info(generate_script)
  208. if platform.system() == 'Windows':
  209. p = subprocess.Popen(generate_script, stdout=subprocess.PIPE)
  210. p.communicate()
  211. else:
  212. p = subprocess.Popen([generate_script], shell=True, stdout=subprocess.PIPE)
  213. p.communicate()
  214. def initSecurity(self):
  215. self.checkCertExists()