1 # ============LICENSE_START=======================================================
2 # Copyright (C) 2019 Nordix Foundation.
3 # ================================================================================
4 # extended by highstreet technologies GmbH (c) 2020
5 # ================================================================================
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
18 # SPDX-License-Identifier: Apache-2.0
19 # ============LICENSE_END=========================================================
33 odl_home = os.environ['ODL_HOME']
34 log_directory = odl_home + '/data/log/'
35 log_file = log_directory + 'installCerts.log'
36 log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
37 if not os.path.exists(log_directory):
38 os.makedirs(log_directory)
39 logging.basicConfig(filename=log_file,level=logging.DEBUG,filemode='w',format=log_format)
40 print 'Start cert provisioning. Log file: ' + log_file;
42 Path = os.environ['ODL_CERT_DIR']
46 username = os.environ['ODL_ADMIN_USERNAME']
47 password = os.environ['ODL_ADMIN_PASSWORD']
52 postKeystore= "/restconf/operations/netconf-keystore:add-keystore-entry"
53 postPrivateKey= "/restconf/operations/netconf-keystore:add-private-key"
54 postTrustedCertificate= "/restconf/operations/netconf-keystore:add-trusted-certificate"
56 envOdlFeaturesBoot='ODL_FEATURES_BOOT'
57 # Strategy sli-api is default
59 certreadyUrl="/restconf/operations/SLI-API:healthcheck"
60 odlFeaturesBoot=os.environ.get(envOdlFeaturesBoot)
61 if odlFeaturesBoot is not None:
62 odlFeaturesBoot=odlFeaturesBoot.lower()
63 if 'odl-netconf-topology' in odlFeaturesBoot or 'odl-netconf-clustered-topology' in odlFeaturesBoot:
65 certreadyUrl="/restconf/operational/network-topology:network-topology"
66 logging.info('ODL ready strategy with command %s and url %s', certreadyCmd, certreadyUrl)
70 headers = {'Authorization':'Basic %s' % base64.b64encode(username + ":" + password),
71 'X-FromAppId': 'csit-sdnc',
72 'X-TransactionId': 'csit-sdnc',
73 'Accept':"application/json",
74 'Content-type':"application/json"}
76 def readFile(folder, file):
77 key = open(Path + "/" + folder + "/" + file, "r")
80 fileRead = "\n".join(fileRead.splitlines()[1:-1])
83 def readTrustedCertificate(folder, file):
87 key = open(folder + "/" + file, "r")
88 lines = key.readlines()
90 if not "BEGIN CERTIFICATE" in line and not "END CERTIFICATE" in line and startCa:
92 elif "BEGIN CERTIFICATE" in line:
94 elif "END CERTIFICATE" in line:
96 listCert.append(caPem)
100 def makeKeystoreKey(clientKey, count):
101 odl_private_key="ODL_private_key_%d" %count
103 json_keystore_key='{{\"input\": {{ \"key-credential\": {{\"key-id\": \"{odl_private_key}\", \"private-key\" : ' \
104 '\"{clientKey}\",\"passphrase\" : \"\"}}}}}}'.format(
105 odl_private_key=odl_private_key,
108 return json_keystore_key
112 def makePrivateKey(clientKey, clientCrt, certList, count):
115 for cert in certList:
116 caPem += '\"%s\",' % cert
117 caPem = caPem.rsplit(',', 1)[0]
118 odl_private_key="ODL_private_key_%d" %count
120 json_private_key='{{\"input\": {{ \"private-key\":{{\"name\": \"{odl_private_key}\", \"data\" : ' \
121 '\"{clientKey}\",\"certificate-chain\":[\"{clientCrt}\",{caPem}]}}}}}}'.format(
122 odl_private_key=odl_private_key,
127 return json_private_key
129 def makeTrustedCertificate(certList, count):
131 json_cert_format = ""
132 for cert in certList:
133 cert_name = "xNF_CA_certificate_%d_%d" %(count, number)
134 json_cert_format += '{{\"name\": \"{trusted_name}\",\"certificate\":\"{cert}\"}},\n'.format(
135 trusted_name=cert_name,
139 json_cert_format = json_cert_format.rsplit(',', 1)[0]
140 json_trusted_cert='{{\"input\": {{ \"trusted-certificate\": [{certificates}]}}}}'.format(
141 certificates=json_cert_format)
142 return json_trusted_cert
145 def makeRestconfPost(conn, json_file, apiCall):
146 req = conn.request("POST", apiCall, json_file, headers=headers)
147 res = conn.getresponse()
149 if res.status != 200:
150 logging.error("Error here, response back wasnt 200: Response was : %d , %s" % (res.status, res.reason))
152 logging.debug("Response :%s Reason :%s ",res.status, res.reason)
154 def extractZipFiles(zipFileList, count):
155 for zipFolder in zipFileList:
156 with zipfile.ZipFile(Path + "/" + zipFolder.strip(),"r") as zip_ref:
157 zip_ref.extractall(Path)
158 folder = zipFolder.rsplit(".")[0]
159 processFiles(folder, count)
161 def processFiles(folder, count):
162 logging.info('Process folder: %d %s', count, folder)
163 for file in os.listdir(Path + "/" + folder):
164 if os.path.isfile(Path + "/" + folder + "/" + file.strip()):
166 clientKey = readFile(folder, file.strip())
167 elif "trustedCertificate" in file:
168 certList = readTrustedCertificate(Path + "/" + folder, file.strip())
170 clientCrt = readFile(folder, file.strip())
172 logging.error("Could not find file %s" % file.strip())
173 shutil.rmtree(Path + "/" + folder)
174 post_content(clientKey, clientCrt, certList, count)
176 def post_content(clientKey, clientCrt, certList, count):
177 logging.info('Post content: %d', count)
178 conn = httplib.HTTPConnection("localhost",odl_port)
180 json_keystore_key = makeKeystoreKey(clientKey, count)
181 logging.debug("Posting private key in to ODL keystore")
182 makeRestconfPost(conn, json_keystore_key, postKeystore)
185 json_trusted_cert = makeTrustedCertificate(certList, count)
186 logging.debug("Posting trusted cert list in to ODL")
187 makeRestconfPost(conn, json_trusted_cert, postTrustedCertificate)
189 if clientKey and clientCrt and certList:
190 json_private_key = makePrivateKey(clientKey, clientCrt, certList, count)
191 logging.debug("Posting the cert in to ODL")
192 makeRestconfPost(conn, json_private_key, postPrivateKey)
195 def makeHealthcheckCall(headers, timePassed):
197 # WAIT 10 minutes maximum and test every 30 seconds if HealthCheck API is returning 200
198 while timePassed < TIMEOUT:
200 conn = httplib.HTTPConnection("localhost",odl_port)
201 req = conn.request(certreadyCmd, certreadyUrl,headers=headers)
202 res = conn.getresponse()
204 httpStatus = res.status
205 if httpStatus == 200:
206 logging.debug("Healthcheck Passed in %d seconds." %timePassed)
210 logging.debug("Sleep: %d seconds before testing if Healthcheck worked. Total wait time up now is: %d seconds. Timeout is: %d seconds. Problem code was: %d" %(INTERVAL, timePassed, TIMEOUT, httpStatus))
212 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))
213 timePassed = timeIncrement(timePassed)
215 if timePassed > TIMEOUT:
216 logging.error("TIME OUT: Healthcheck not passed in %d seconds... Could cause problems for testing activities..." %TIMEOUT)
221 def timeIncrement(timePassed):
223 timePassed = timePassed + INTERVAL
226 def get_cadi_password():
228 with open(Path + '/' + cadi_file , 'r') as file_obj:
229 cadi_pass = file_obj.read().split('=', 1)[1].strip()
231 except Exception as e:
232 logging.error("Error occurred while fetching password : %s", e)
236 for file in os.listdir(Path):
237 if os.path.isfile(Path + '/' + file):
238 logging.debug("Cleaning up the file %s", Path + '/'+ file)
239 os.remove(Path + '/'+ file)
241 def extract_content(file, password, count):
246 if (file.endswith('.jks')):
247 p12_file = file.replace('.jks', '.p12')
248 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)
249 logging.debug("Converting %s into p12 format", file)
253 clcrt_cmd = 'openssl pkcs12 -in {src_file} -clcerts -nokeys -passin pass:{src_pass}'.format(src_file=file, src_pass=password)
254 clkey_cmd = 'openssl pkcs12 -in {src_file} -nocerts -nodes -passin pass:{src_pass}'.format(src_file=file, src_pass=password)
255 trust_file = file.split('/')[2] + '.trust'
256 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)
258 result_key = subprocess.check_output(clkey_cmd , shell=True)
260 key = result_key.split('-----BEGIN PRIVATE KEY-----', 1)[1].lstrip().split('-----END PRIVATE KEY-----')[0]
262 os.system(trustCerts_cmd)
263 if os.path.exists(Path + '/' + trust_file):
264 certList = readTrustedCertificate(Path, trust_file)
266 result_crt = subprocess.check_output(clcrt_cmd , shell=True)
268 cert = result_crt.split('-----BEGIN CERTIFICATE-----', 1)[1].lstrip().split('-----END CERTIFICATE-----')[0]
270 To-do: Posting the key, cert, certList might need modification
271 based on how AAF distributes the files.
274 post_content(key, cert, certList, count)
275 except Exception as e:
276 logging.error("Error occurred while processing the file %s : %s", file,e)
280 for file in os.listdir(Path):
281 if (file.endswith(('.p12', '.jks'))):
282 if os.path.exists(Path + '/' + cadi_file):
283 cert_password = get_cadi_password()
284 logging.debug("Extracting contents from the file %s", file)
285 extract_content(Path + '/' + file, cert_password, count)
288 logging.error("Cadi password file %s not present under cert directory", cadi_file)
293 logging.debug("No jks/p12 files found under cert directory %s", Path)
296 def readCertProperties():
297 connected = makeHealthcheckCall(headers, timePassed)
298 logging.info('Connected status: %s', connected)
301 if os.path.isfile(Path + "/certs.properties"):
302 with open(Path + "/certs.properties", "r") as f:
304 if not "*****" in line:
305 zipFileList.append(line)
307 extractZipFiles(zipFileList, count)
311 logging.debug("No zipfiles present under cert directory")
313 logging.info("Looking for jks/p12 files under cert directory")
317 logging.info('Cert installation ending')