1 # ============LICENSE_START=======================================================
2 # Copyright (C) 2019 Nordix Foundation.
3 # ================================================================================
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
16 # SPDX-License-Identifier: Apache-2.0
17 # ============LICENSE_END=========================================================
31 log_file = '/opt/opendaylight/data/log/installCerts.log'
32 log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
33 logging.basicConfig(filename=log_file,level=logging.DEBUG,filemode='w',format=log_format)
35 Path = os.environ['ODL_CERT_DIR']
39 username = os.environ['ODL_ADMIN_USERNAME']
40 password = os.environ['ODL_ADMIN_PASSWORD']
45 postKeystore= "/restconf/operations/netconf-keystore:add-keystore-entry"
46 postPrivateKey= "/restconf/operations/netconf-keystore:add-private-key"
47 postTrustedCertificate= "/restconf/operations/netconf-keystore:add-trusted-certificate"
51 headers = {'Authorization':'Basic %s' % base64.b64encode(username + ":" + password),
52 'X-FromAppId': 'csit-sdnc',
53 'X-TransactionId': 'csit-sdnc',
54 'Accept':"application/json",
55 'Content-type':"application/json"}
57 def readFile(folder, file):
58 key = open(Path + "/" + folder + "/" + file, "r")
61 fileRead = "\n".join(fileRead.splitlines()[1:-1])
64 def readTrustedCertificate(folder, file):
68 key = open(folder + "/" + file, "r")
69 lines = key.readlines()
71 if not "BEGIN CERTIFICATE" in line and not "END CERTIFICATE" in line and startCa:
73 elif "BEGIN CERTIFICATE" in line:
75 elif "END CERTIFICATE" in line:
77 listCert.append(caPem)
81 def makeKeystoreKey(clientKey, count):
82 odl_private_key="ODL_private_key_%d" %count
84 json_keystore_key='{{\"input\": {{ \"key-credential\": {{\"key-id\": \"{odl_private_key}\", \"private-key\" : ' \
85 '\"{clientKey}\",\"passphrase\" : \"\"}}}}}}'.format(
86 odl_private_key=odl_private_key,
89 return json_keystore_key
93 def makePrivateKey(clientKey, clientCrt, certList, count):
97 caPem += '\"%s\",' % cert
98 caPem = caPem.rsplit(',', 1)[0]
99 odl_private_key="ODL_private_key_%d" %count
101 json_private_key='{{\"input\": {{ \"private-key\":{{\"name\": \"{odl_private_key}\", \"data\" : ' \
102 '\"{clientKey}\",\"certificate-chain\":[\"{clientCrt}\",{caPem}]}}}}}}'.format(
103 odl_private_key=odl_private_key,
108 return json_private_key
110 def makeTrustedCertificate(certList, count):
112 json_cert_format = ""
113 for cert in certList:
114 cert_name = "xNF_CA_certificate_%d_%d" %(count, number)
115 json_cert_format += '{{\"name\": \"{trusted_name}\",\"certificate\":\"{cert}\"}},\n'.format(
116 trusted_name=cert_name,
120 json_cert_format = json_cert_format.rsplit(',', 1)[0]
121 json_trusted_cert='{{\"input\": {{ \"trusted-certificate\": [{certificates}]}}}}'.format(
122 certificates=json_cert_format)
123 return json_trusted_cert
126 def makeRestconfPost(conn, json_file, apiCall):
127 req = conn.request("POST", apiCall, json_file, headers=headers)
128 res = conn.getresponse()
130 if res.status != 200:
131 logging.error("Error here, response back wasnt 200: Response was : %d , %s" % (res.status, res.reason))
133 logging.debug("Response :%s Reason :%s ",res.status, res.reason)
135 def extractZipFiles(zipFileList, count):
136 for zipFolder in zipFileList:
137 with zipfile.ZipFile(Path + "/" + zipFolder.strip(),"r") as zip_ref:
138 zip_ref.extractall(Path)
139 folder = zipFolder.rsplit(".")[0]
140 processFiles(folder, count)
142 def processFiles(folder, count):
143 for file in os.listdir(Path + "/" + folder):
144 if os.path.isfile(Path + "/" + folder + "/" + file.strip()):
146 clientKey = readFile(folder, file.strip())
147 elif "trustedCertificate" in file:
148 certList = readTrustedCertificate(Path + "/" + folder, file.strip())
150 clientCrt = readFile(folder, file.strip())
152 logging.error("Could not find file %s" % file.strip())
153 shutil.rmtree(Path + "/" + folder)
154 post_content(clientKey, clientCrt, certList, count)
156 def post_content(clientKey, clientCrt, certList, count):
157 conn = httplib.HTTPConnection("localhost",odl_port)
159 json_keystore_key = makeKeystoreKey(clientKey, count)
160 logging.debug("Posting private key in to ODL keystore")
161 makeRestconfPost(conn, json_keystore_key, postKeystore)
164 json_trusted_cert = makeTrustedCertificate(certList, count)
165 logging.debug("Posting trusted cert list in to ODL")
166 makeRestconfPost(conn, json_trusted_cert, postTrustedCertificate)
168 if clientKey and clientCrt and certList:
169 json_private_key = makePrivateKey(clientKey, clientCrt, certList, count)
170 logging.debug("Posting the cert in to ODL")
171 makeRestconfPost(conn, json_private_key, postPrivateKey)
174 def makeHealthcheckCall(headers, timePassed):
176 # WAIT 10 minutes maximum and test every 30 seconds if HealthCheck API is returning 200
177 while timePassed < TIMEOUT:
179 conn = httplib.HTTPConnection("localhost",odl_port)
180 req = conn.request("POST", "/restconf/operations/SLI-API:healthcheck",headers=headers)
181 res = conn.getresponse()
183 if res.status == 200:
184 logging.debug("Healthcheck Passed in %d seconds." %timePassed)
188 logging.debug("Sleep: %d seconds before testing if Healthcheck worked. Total wait time up now is: %d seconds. Timeout is: %d seconds" %(INTERVAL, timePassed, TIMEOUT))
190 logging.error("Cannot execute REST call. Sleep: %d seconds before testing if Healthcheck worked. Total wait time up now is: %d seconds. Timeout is: %d seconds" %(INTERVAL, timePassed, TIMEOUT))
191 timePassed = timeIncrement(timePassed)
193 if timePassed > TIMEOUT:
194 logging.error("TIME OUT: Healthcheck not passed in %d seconds... Could cause problems for testing activities..." %TIMEOUT)
198 def timeIncrement(timePassed):
200 timePassed = timePassed + INTERVAL
203 def get_cadi_password():
205 with open(Path + '/' + cadi_file , 'r') as file_obj:
206 cadi_pass = file_obj.read().split('=', 1)[1].strip()
208 except Exception as e:
209 logging.error("Error occurred while fetching password : %s", e)
213 for file in os.listdir(Path):
214 if os.path.isfile(Path + '/' + file):
215 logging.debug("Cleaning up the file %s", Path + '/'+ file)
216 os.remove(Path + '/'+ file)
218 def extract_content(file, password, count):
223 if (file.endswith('.jks')):
224 p12_file = file.replace('.jks', '.p12')
225 jks_cmd = 'keytool -importkeystore -srckeystore {src_file} -destkeystore {dest_file} -srcstoretype JKS -srcstorepass {src_pass} -deststoretype PKCS12 -deststorepass {dest_pass}'.format(src_file=file, dest_file=p12_file, src_pass=password, dest_pass=password)
226 logging.debug("Converting %s into p12 format", file)
230 clcrt_cmd = 'openssl pkcs12 -in {src_file} -clcerts -nokeys -passin pass:{src_pass}'.format(src_file=file, src_pass=password)
231 clkey_cmd = 'openssl pkcs12 -in {src_file} -nocerts -nodes -passin pass:{src_pass}'.format(src_file=file, src_pass=password)
232 trust_file = file.split('/')[2] + '.trust'
233 trustCerts_cmd = 'openssl pkcs12 -in {src_file} -out {out_file} -cacerts -nokeys -passin pass:{src_pass} '.format(src_file=file, out_file=Path + '/' + trust_file, src_pass=password)
235 result_key = subprocess.check_output(clkey_cmd , shell=True)
237 key = result_key.split('-----BEGIN PRIVATE KEY-----', 1)[1].lstrip().split('-----END PRIVATE KEY-----')[0]
239 os.system(trustCerts_cmd)
240 if os.path.exists(Path + '/' + trust_file):
241 certList = readTrustedCertificate(Path, trust_file)
243 result_crt = subprocess.check_output(clcrt_cmd , shell=True)
245 cert = result_crt.split('-----BEGIN CERTIFICATE-----', 1)[1].lstrip().split('-----END CERTIFICATE-----')[0]
247 To-do: Posting the key, cert, certList might need modification
248 based on how AAF distributes the files.
251 post_content(key, cert, certList, count)
252 except Exception as e:
253 logging.error("Error occurred while processing the file %s : %s", file,e)
257 for file in os.listdir(Path):
258 if (file.endswith(('.p12', '.jks'))):
259 if os.path.exists(Path + '/' + cadi_file):
260 cert_password = get_cadi_password()
261 logging.debug("Extracting contents from the file %s", file)
262 extract_content(Path + '/' + file, cert_password, count)
265 logging.error("Cadi password file %s not present under cert directory", cadi_file)
270 logging.debug("No jks/p12 files found under cert directory %s", Path)
273 def readCertProperties():
274 connected = makeHealthcheckCall(headers, timePassed)
278 if os.path.isfile(Path + "/certs.properties"):
279 with open(Path + "/certs.properties", "r") as f:
281 if not "*****" in line:
282 zipFileList.append(line)
284 extractZipFiles(zipFileList, count)
288 logging.debug("No zipfiles present under cert directory")
290 logging.info("Looking for jks/p12 files under cert directory")