Merge "DG changes for the closed loop and async support in MDONS"
[sdnc/oam.git] / installation / sdnc / src / main / scripts / installCerts.oom.py
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
9 #
10 #      http://www.apache.org/licenses/LICENSE-2.0
11 #
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.
17 #
18 # SPDX-License-Identifier: Apache-2.0
19 # ============LICENSE_END=========================================================
20 #
21
22
23 # coding=utf-8
24 import os
25 import httplib
26 import base64
27 import time
28 import zipfile
29 import shutil
30 import subprocess
31 import logging
32
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;
41
42 Path = os.environ['ODL_CERT_DIR']
43
44 zipFileList = []
45
46 username = os.environ['ODL_ADMIN_USERNAME']
47 password = os.environ['ODL_ADMIN_PASSWORD']
48 TIMEOUT=1000
49 INTERVAL=30
50 timePassed=0
51
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"
55
56 envOdlFeaturesBoot='ODL_FEATURES_BOOT'
57 # Strategy sli-api is default
58 certreadyCmd="POST"
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:
64         certreadyCmd="GET"
65         certreadyUrl="/restconf/operational/network-topology:network-topology"
66 logging.info('ODL ready strategy with command %s and url %s', certreadyCmd, certreadyUrl)
67
68 cadi_file = '.pass'
69 odl_port = 8181
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"}
75
76 def readFile(folder, file):
77     key = open(Path + "/" + folder + "/" + file, "r")
78     fileRead = key.read()
79     key.close()
80     fileRead = "\n".join(fileRead.splitlines()[1:-1])
81     return fileRead
82
83 def readTrustedCertificate(folder, file):
84     listCert = list()
85     caPem = ""
86     startCa = False
87     key = open(folder + "/" + file, "r")
88     lines = key.readlines()
89     for line in lines:
90         if not "BEGIN CERTIFICATE" in line and not "END CERTIFICATE" in line and startCa:
91             caPem += line
92         elif "BEGIN CERTIFICATE" in line:
93             startCa = True
94         elif "END CERTIFICATE" in line:
95             startCa = False
96             listCert.append(caPem)
97             caPem = ""
98     return listCert
99
100 def makeKeystoreKey(clientKey, count):
101     odl_private_key="ODL_private_key_%d" %count
102
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,
106         clientKey=clientKey)
107
108     return json_keystore_key
109
110
111
112 def makePrivateKey(clientKey, clientCrt, certList, count):
113     caPem = ""
114     if certList:
115         for cert in certList:
116             caPem += '\"%s\",' % cert
117         caPem = caPem.rsplit(',', 1)[0]
118     odl_private_key="ODL_private_key_%d" %count
119
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,
123         clientKey=clientKey,
124         clientCrt=clientCrt,
125         caPem=caPem)
126
127     return json_private_key
128
129 def makeTrustedCertificate(certList, count):
130     number = 0
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,
136             cert=cert.strip())
137         number += 1
138
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
143
144
145 def makeRestconfPost(conn, json_file, apiCall):
146     req = conn.request("POST", apiCall, json_file, headers=headers)
147     res = conn.getresponse()
148     res.read()
149     if res.status != 200:
150         logging.error("Error here, response back wasnt 200: Response was : %d , %s" % (res.status, res.reason))
151     else:
152         logging.debug("Response :%s Reason :%s ",res.status, res.reason)
153
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)
160
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()):
165             if ".key" in file:
166                 clientKey = readFile(folder, file.strip())
167             elif "trustedCertificate" in file:
168                 certList = readTrustedCertificate(Path + "/" + folder, file.strip())
169             elif ".crt" in file:
170                 clientCrt = readFile(folder, file.strip())
171         else:
172             logging.error("Could not find file %s" % file.strip())
173     shutil.rmtree(Path + "/" + folder)
174     post_content(clientKey, clientCrt, certList, count)
175
176 def post_content(clientKey, clientCrt, certList, count):
177     logging.info('Post content: %d', count)
178     conn = httplib.HTTPConnection("localhost",odl_port)
179     if clientKey:
180         json_keystore_key = makeKeystoreKey(clientKey, count)
181         logging.debug("Posting private key in to ODL keystore")
182         makeRestconfPost(conn, json_keystore_key, postKeystore)
183
184     if certList:
185         json_trusted_cert = makeTrustedCertificate(certList, count)
186         logging.debug("Posting trusted cert list in to ODL")
187         makeRestconfPost(conn, json_trusted_cert, postTrustedCertificate)
188
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)
193
194
195 def makeHealthcheckCall(headers, timePassed):
196     connected = False
197     # WAIT 10 minutes maximum and test every 30 seconds if HealthCheck API is returning 200
198     while timePassed < TIMEOUT:
199         try:
200             conn = httplib.HTTPConnection("localhost",odl_port)
201             req = conn.request(certreadyCmd, certreadyUrl,headers=headers)
202             res = conn.getresponse()
203             res.read()
204             httpStatus = res.status
205             if httpStatus == 200:
206                 logging.debug("Healthcheck Passed in %d seconds." %timePassed)
207                 connected = True
208                 break
209             else:
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))
211         except:
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)
214
215     if timePassed > TIMEOUT:
216         logging.error("TIME OUT: Healthcheck not passed in  %d seconds... Could cause problems for testing activities..." %TIMEOUT)
217
218     return connected
219
220
221 def timeIncrement(timePassed):
222     time.sleep(INTERVAL)
223     timePassed = timePassed + INTERVAL
224     return timePassed
225
226 def get_cadi_password():
227     try:
228         with open(Path + '/' + cadi_file , 'r') as file_obj:
229             cadi_pass = file_obj.read().split('=', 1)[1].strip()
230         return cadi_pass
231     except Exception as e:
232         logging.error("Error occurred while fetching password : %s", e)
233         exit()
234
235 def cleanup():
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)
240
241 def extract_content(file, password, count):
242     try:
243         certList = []
244         key = None
245         cert = None
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)
250             os.system(jks_cmd)
251             file = p12_file
252
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)
257
258         result_key = subprocess.check_output(clkey_cmd , shell=True)
259         if result_key:
260             key = result_key.split('-----BEGIN PRIVATE KEY-----', 1)[1].lstrip().split('-----END PRIVATE KEY-----')[0]
261
262         os.system(trustCerts_cmd)
263         if os.path.exists(Path + '/' + trust_file):
264             certList = readTrustedCertificate(Path, trust_file)
265
266         result_crt = subprocess.check_output(clcrt_cmd , shell=True)
267         if result_crt:
268             cert = result_crt.split('-----BEGIN CERTIFICATE-----', 1)[1].lstrip().split('-----END CERTIFICATE-----')[0]
269         """
270         To-do: Posting the key, cert, certList might need modification
271         based on how AAF distributes the files.
272
273         """
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)
277
278 def lookforfiles():
279     count = 0
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)
286                 count += 1
287             else:
288                 logging.error("Cadi password file %s not present under cert directory", cadi_file)
289                 exit()
290     if count > 0:
291         cleanup()
292     else:
293         logging.debug("No jks/p12 files found under cert directory %s", Path)
294
295
296 def readCertProperties():
297     connected = makeHealthcheckCall(headers, timePassed)
298     logging.info('Connected status: %s', connected)
299     if connected:
300         count = 0
301         if os.path.isfile(Path + "/certs.properties"):
302             with open(Path + "/certs.properties", "r") as f:
303                 for line in f:
304                     if not "*****" in line:
305                         zipFileList.append(line)
306                     else:
307                         extractZipFiles(zipFileList, count)
308                         count += 1
309                         del zipFileList[:]
310         else:
311             logging.debug("No zipfiles present under cert directory")
312
313         logging.info("Looking for jks/p12 files under cert directory")
314         lookforfiles()
315
316 readCertProperties()
317 logging.info('Cert installation ending')