42af7d2c5e41b0619238df70b34eec65dfa0647a
[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 http.client
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 newpassword = os.environ.get('ODL_ADMIN_NEWPASSWORD')
49 TIMEOUT=1000
50 INTERVAL=30
51 timePassed=0
52
53 postKeystore= "/rests/operations/netconf-keystore:add-keystore-entry"
54 postPrivateKey= "/rests/operations/netconf-keystore:add-private-key"
55 postTrustedCertificate= "/rests/operations/netconf-keystore:add-trusted-certificate"
56
57 envOdlFeaturesBoot='ODL_FEATURES_BOOT'
58 # Strategy sli-api is default
59 certreadyCmd="POST"
60 certreadyUrl="/rests/operations/SLI-API:healthcheck"
61 odlFeaturesBoot=os.environ.get(envOdlFeaturesBoot)
62
63 if odlFeaturesBoot is not None:
64     odlFeaturesBoot=odlFeaturesBoot.lower()
65     if 'odl-netconf-topology' in odlFeaturesBoot or 'odl-netconf-clustered-topology' in odlFeaturesBoot:
66         certreadyCmd="GET"
67         certreadyUrl="/rests/data/network-topology:network-topology"
68 logging.info('ODL ready strategy with command %s and url %s', certreadyCmd, certreadyUrl)
69
70 cadi_file = '.pass'
71 odl_port = 8181
72 cred_string = username + ":" + password
73 headers = {'Authorization':'Basic %s' %  base64.b64encode(cred_string.encode()).decode(),
74            'X-FromAppId': 'csit-sdnc',
75            'X-TransactionId': 'csit-sdnc',
76            'Accept':"application/json",
77            'Content-type':"application/yang-data+json"}
78
79 def readFile(folder, file):
80     key = open(Path + "/" + folder + "/" + file, "r")
81     fileRead = key.read()
82     key.close()
83     fileRead = "\n".join(fileRead.splitlines()[1:-1])
84     return fileRead
85
86 def readTrustedCertificate(folder, file):
87     listCert = list()
88     caPem = ""
89     startCa = False
90     key = open(folder + "/" + file, "r")
91     lines = key.readlines()
92     for line in lines:
93         if not "BEGIN CERTIFICATE" in line and not "END CERTIFICATE" in line and startCa:
94             caPem += line
95         elif "BEGIN CERTIFICATE" in line:
96             startCa = True
97         elif "END CERTIFICATE" in line:
98             startCa = False
99             listCert.append(caPem)
100             caPem = ""
101     return listCert
102
103 def makeKeystoreKey(clientKey, count):
104     odl_private_key="ODL_private_key_%d" %count
105
106     json_keystore_key='{{\"input\": {{ \"key-credential\": {{\"key-id\": \"{odl_private_key}\", \"private-key\" : ' \
107                       '\"{clientKey}\",\"passphrase\" : \"\"}}}}}}'.format(
108         odl_private_key=odl_private_key,
109         clientKey=clientKey)
110
111     return json_keystore_key
112
113 def makePrivateKey(clientKey, clientCrt, certList, count):
114     caPem = ""
115     if certList:
116         for cert in certList:
117             caPem += '\"%s\",' % cert
118         caPem = caPem.rsplit(',', 1)[0]
119     odl_private_key="ODL_private_key_%d" %count
120
121     json_private_key='{{\"input\": {{ \"private-key\":{{\"name\": \"{odl_private_key}\", \"data\" : ' \
122                      '\"{clientKey}\",\"certificate-chain\":[\"{clientCrt}\",{caPem}]}}}}}}'.format(
123         odl_private_key=odl_private_key,
124         clientKey=clientKey,
125         clientCrt=clientCrt,
126         caPem=caPem)
127
128     return json_private_key
129
130 def makeTrustedCertificate(certList, count):
131     number = 0
132     json_cert_format = ""
133     for cert in certList:
134         cert_name = "xNF_CA_certificate_%d_%d" %(count, number)
135         json_cert_format += '{{\"name\": \"{trusted_name}\",\"certificate\":\"{cert}\"}},\n'.format(
136             trusted_name=cert_name,
137             cert=cert.strip())
138         number += 1
139
140     json_cert_format = json_cert_format.rsplit(',', 1)[0]
141     json_trusted_cert='{{\"input\": {{ \"trusted-certificate\": [{certificates}]}}}}'.format(
142         certificates=json_cert_format)
143     return json_trusted_cert
144
145
146 def makeRestconfPost(conn, json_file, apiCall):
147     req = conn.request("POST", apiCall, json_file, headers=headers)
148     res = conn.getresponse()
149     res.read()
150     if res.status != 200:
151         logging.error("Error here, response back wasnt 200: Response was : %d , %s" % (res.status, res.reason))
152     else:
153         logging.debug("Response :%s Reason :%s ",res.status, res.reason)
154
155 def extractZipFiles(zipFileList, count):
156     for zipFolder in zipFileList:
157         with zipfile.ZipFile(Path + "/" + zipFolder.strip(),"r") as zip_ref:
158             zip_ref.extractall(Path)
159         folder = zipFolder.rsplit(".")[0]
160         processFiles(folder, count)
161
162 def processFiles(folder, count):
163     logging.info('Process folder: %d %s', count, folder)
164     for file in os.listdir(Path + "/" + folder):
165         if os.path.isfile(Path + "/" + folder + "/" + file.strip()):
166             if ".key" in file:
167                 clientKey = readFile(folder, file.strip())
168             elif "trustedCertificate" in file:
169                 certList = readTrustedCertificate(Path + "/" + folder, file.strip())
170             elif ".crt" in file:
171                 clientCrt = readFile(folder, file.strip())
172         else:
173             logging.error("Could not find file %s" % file.strip())
174     shutil.rmtree(Path + "/" + folder)
175     post_content(clientKey, clientCrt, certList, count)
176
177 def post_content(clientKey, clientCrt, certList, count):
178     logging.info('Post content: %d', count)
179     conn = http.client.HTTPConnection("localhost",odl_port)
180     if clientKey:
181         json_keystore_key = makeKeystoreKey(clientKey, count)
182         logging.debug("Posting private key in to ODL keystore")
183         makeRestconfPost(conn, json_keystore_key, postKeystore)
184
185     if certList:
186         json_trusted_cert = makeTrustedCertificate(certList, count)
187         logging.debug("Posting trusted cert list in to ODL")
188         makeRestconfPost(conn, json_trusted_cert, postTrustedCertificate)
189
190     if clientKey and clientCrt and certList:
191         json_private_key = makePrivateKey(clientKey, clientCrt, certList, count)
192         logging.debug("Posting the cert in to ODL")
193         makeRestconfPost(conn, json_private_key, postPrivateKey)
194
195
196 def makeHealthcheckCall(headers, timePassed):
197     connected = False
198     # WAIT 10 minutes maximum and test every 30 seconds if HealthCheck API is returning 200
199     while timePassed < TIMEOUT:
200         try:
201             conn = http.client.HTTPConnection("localhost",odl_port)
202             req = conn.request(certreadyCmd, certreadyUrl,headers=headers)
203             res = conn.getresponse()
204             res.read()
205             httpStatus = res.status
206             if httpStatus == 200:
207                 logging.debug("Healthcheck Passed in %d seconds." %timePassed)
208                 connected = True
209                 break
210             else:
211                 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         except:
213             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))
214         timePassed = timeIncrement(timePassed)
215
216     if timePassed > TIMEOUT:
217         logging.error("TIME OUT: Healthcheck not passed in  %d seconds... Could cause problems for testing activities..." %TIMEOUT)
218
219     return connected
220
221
222 def timeIncrement(timePassed):
223     time.sleep(INTERVAL)
224     timePassed = timePassed + INTERVAL
225     return timePassed
226
227 def get_cadi_password():
228     try:
229         with open(Path + '/' + cadi_file , 'r') as file_obj:
230             cadi_pass = file_obj.read().split('=', 1)[1].strip()
231         return cadi_pass
232     except Exception as e:
233         logging.error("Error occurred while fetching password : %s", e)
234         exit()
235
236 def cleanup():
237     for file in os.listdir(Path):
238         if os.path.isfile(Path + '/' + file):
239             logging.debug("Cleaning up the file %s", Path + '/'+ file)
240             os.remove(Path + '/'+ file)
241
242 def extract_content(file, password, count):
243     try:
244         certList = []
245         key = None
246         cert = None
247         if (file.endswith('.jks')):
248             p12_file = file.replace('.jks', '.p12')
249             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)
250             logging.debug("Converting %s into p12 format", file)
251             os.system(jks_cmd)
252             file = p12_file
253
254         clcrt_cmd = 'openssl pkcs12 -in {src_file} -clcerts -nokeys  -passin pass:{src_pass}'.format(src_file=file, src_pass=password)
255         clkey_cmd = 'openssl pkcs12 -in {src_file}  -nocerts -nodes -passin pass:{src_pass}'.format(src_file=file, src_pass=password)
256         trust_file = file.split('/')[2] + '.trust'
257         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
259         result_key = subprocess.check_output(clkey_cmd , shell=True)
260         if result_key:
261             key = result_key.split('-----BEGIN PRIVATE KEY-----', 1)[1].lstrip().split('-----END PRIVATE KEY-----')[0]
262
263         os.system(trustCerts_cmd)
264         if os.path.exists(Path + '/' + trust_file):
265             certList = readTrustedCertificate(Path, trust_file)
266
267         result_crt = subprocess.check_output(clcrt_cmd , shell=True)
268         if result_crt:
269             cert = result_crt.split('-----BEGIN CERTIFICATE-----', 1)[1].lstrip().split('-----END CERTIFICATE-----')[0]
270         """
271         To-do: Posting the key, cert, certList might need modification
272         based on how AAF distributes the files.
273
274         """
275         post_content(key, cert, certList, count)
276     except Exception as e:
277         logging.error("Error occurred while processing the file %s : %s", file,e)
278
279 def lookforfiles():
280     count = 0
281     for file in os.listdir(Path):
282         if (file.endswith(('.p12', '.jks'))):
283             if os.path.exists(Path + '/' + cadi_file):
284                 cert_password = get_cadi_password()
285                 logging.debug("Extracting contents from the file %s", file)
286                 extract_content(Path + '/' + file, cert_password, count)
287                 count += 1
288             else:
289                 logging.error("Cadi password file %s not present under cert directory", cadi_file)
290                 exit()
291     if count > 0:
292         cleanup()
293     else:
294         logging.debug("No jks/p12 files found under cert directory %s", Path)
295
296 def replaceAdminPassword(username, password, newpassword):
297     if newpassword is None:
298         logging.info('Not to replace password for user %s', username)
299     else:
300         logging.info('Replace password for user %s', username)
301         try:
302             jsondata = '{\"password\": \"{newpassword}\"}'.format(newpassword=newpassword)
303             url = '/auth/v1/users/{username}@sdn'.format(username=username)
304             loggin.info("Url %s data $s", url, jsondata)
305             conn = http.client.HTTPConnection("localhost",odl_port)
306             req = conn.request("PUT", url, jsondata, headers=headers)
307             res = conn.getresponse()
308             res.read()
309             httpStatus = res.status
310             if httpStatus == 200:
311                 logging.debug("New password provided successfully for user %s", username)
312             else:
313                 logging.debug("Password change was not possible. Problem code was: %d", httpStatus)
314         except:
315             logging.error("Cannot execute REST call to set password.")
316
317 def readCertProperties():
318     connected = makeHealthcheckCall(headers, timePassed)
319     logging.info('Connected status: %s', connected)
320     if connected:
321         replaceAdminPassword(username, password, newpassword)
322         count = 0
323         if os.path.isfile(Path + "/certs.properties"):
324             with open(Path + "/certs.properties", "r") as f:
325                 for line in f:
326                     if not "*****" in line:
327                         zipFileList.append(line)
328                     else:
329                         extractZipFiles(zipFileList, count)
330                         count += 1
331                         del zipFileList[:]
332         else:
333             logging.debug("No zipfiles present under cert directory")
334
335         logging.info("Looking for jks/p12 files under cert directory")
336         lookforfiles()
337
338 readCertProperties()
339 logging.info('Cert installation ending')