SDNC script changes to support jks, p12 cert formats from AAF
[sdnc/oam.git] / installation / sdnc / src / main / scripts / installCerts.py
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
7 #
8 #      http://www.apache.org/licenses/LICENSE-2.0
9 #
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.
15 #
16 # SPDX-License-Identifier: Apache-2.0
17 # ============LICENSE_END=========================================================
18 #
19
20
21 # coding=utf-8
22 import os
23 import httplib
24 import base64
25 import time
26 import zipfile
27 import shutil
28 import subprocess
29 import logging
30
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)
34
35 Path = os.environ['ODL_CERT_DIR']
36
37 zipFileList = []
38
39 username = os.environ['ODL_ADMIN_USERNAME']
40 password = os.environ['ODL_ADMIN_PASSWORD']
41 TIMEOUT=1000
42 INTERVAL=30
43 timePassed=0
44
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"
48
49 cadi_file = '.pass'
50 odl_port = 8181
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"}
56
57 def readFile(folder, file):
58     key = open(Path + "/" + folder + "/" + file, "r")
59     fileRead = key.read()
60     key.close()
61     fileRead = "\n".join(fileRead.splitlines()[1:-1])
62     return fileRead
63
64 def readTrustedCertificate(folder, file):
65     listCert = list()
66     caPem = ""
67     startCa = False
68     key = open(folder + "/" + file, "r")
69     lines = key.readlines()
70     for line in lines:
71         if not "BEGIN CERTIFICATE" in line and not "END CERTIFICATE" in line and startCa:
72             caPem += line
73         elif "BEGIN CERTIFICATE" in line:
74             startCa = True
75         elif "END CERTIFICATE" in line:
76             startCa = False
77             listCert.append(caPem)
78             caPem = ""
79     return listCert
80
81 def makeKeystoreKey(clientKey, count):
82     odl_private_key="ODL_private_key_%d" %count
83
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,
87         clientKey=clientKey)
88
89     return json_keystore_key
90
91
92
93 def makePrivateKey(clientKey, clientCrt, certList, count):
94     caPem = ""
95     if certList:
96         for cert in certList:
97             caPem += '\"%s\",' % cert
98         caPem = caPem.rsplit(',', 1)[0]
99     odl_private_key="ODL_private_key_%d" %count
100
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,
104         clientKey=clientKey,
105         clientCrt=clientCrt,
106         caPem=caPem)
107
108     return json_private_key
109
110 def makeTrustedCertificate(certList, count):
111     number = 0
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,
117             cert=cert.strip())
118         number += 1
119
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
124
125
126 def makeRestconfPost(conn, json_file, apiCall):
127     req = conn.request("POST", apiCall, json_file, headers=headers)
128     res = conn.getresponse()
129     res.read()
130     if res.status != 200:
131         logging.error("Error here, response back wasnt 200: Response was : %d , %s" % (res.status, res.reason))
132     else:
133         logging.debug("Response :%s Reason :%s ",res.status, res.reason)
134
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)
141
142 def processFiles(folder, count):
143     for file in os.listdir(Path + "/" + folder):
144         if os.path.isfile(Path + "/" + folder + "/" + file.strip()):
145             if ".key" in file:
146                 clientKey = readFile(folder, file.strip())
147             elif "trustedCertificate" in file:
148                 certList = readTrustedCertificate(Path + "/" + folder, file.strip())
149             elif ".crt" in file:
150                 clientCrt = readFile(folder, file.strip())
151         else:
152             logging.error("Could not find file %s" % file.strip())
153     shutil.rmtree(Path + "/" + folder)
154     post_content(clientKey, clientCrt, certList, count)
155
156 def post_content(clientKey, clientCrt, certList, count):
157     conn = httplib.HTTPConnection("localhost",odl_port)
158     if clientKey:
159         json_keystore_key = makeKeystoreKey(clientKey, count)
160         logging.debug("Posting private key in to ODL keystore")
161         makeRestconfPost(conn, json_keystore_key, postKeystore)
162
163     if certList:
164         json_trusted_cert = makeTrustedCertificate(certList, count)
165         logging.debug("Posting trusted cert list in to ODL")
166         makeRestconfPost(conn, json_trusted_cert, postTrustedCertificate)
167
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)
172
173
174 def makeHealthcheckCall(headers, timePassed):
175     connected = False
176     # WAIT 10 minutes maximum and test every 30 seconds if HealthCheck API is returning 200
177     while timePassed < TIMEOUT:
178         try:
179             conn = httplib.HTTPConnection("localhost",odl_port)
180             req = conn.request("POST", "/restconf/operations/SLI-API:healthcheck",headers=headers)
181             res = conn.getresponse()
182             res.read()
183             if res.status == 200:
184                 logging.debug("Healthcheck Passed in %d seconds." %timePassed)
185                 connected = True
186                 break
187             else:
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))
189         except:
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)
192
193     if timePassed > TIMEOUT:
194         logging.error("TIME OUT: Healthcheck not passed in  %d seconds... Could cause problems for testing activities..." %TIMEOUT)
195     return connected
196
197
198 def timeIncrement(timePassed):
199     time.sleep(INTERVAL)
200     timePassed = timePassed + INTERVAL
201     return timePassed
202
203 def get_cadi_password():
204     try:
205         with open(Path + '/' + cadi_file , 'r') as file_obj:
206             cadi_pass = file_obj.read().split('=', 1)[1].strip()
207         return cadi_pass
208     except Exception as e:
209         logging.error("Error occurred while fetching password : %s", e)
210         exit()
211
212 def cleanup():
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)
217
218 def extract_content(file, password, count):
219     try:
220         certList = []
221         key = None
222         cert = None
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)
227             os.system(jks_cmd)
228             file = p12_file
229
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)
234
235         result_key = subprocess.check_output(clkey_cmd , shell=True)
236         if result_key:
237             key = result_key.split('-----BEGIN PRIVATE KEY-----', 1)[1].lstrip().split('-----END PRIVATE KEY-----')[0]
238
239         os.system(trustCerts_cmd)
240         if os.path.exists(Path + '/' + trust_file):
241             certList = readTrustedCertificate(Path, trust_file)
242
243         result_crt = subprocess.check_output(clcrt_cmd , shell=True)
244         if result_crt:
245             cert = result_crt.split('-----BEGIN CERTIFICATE-----', 1)[1].lstrip().split('-----END CERTIFICATE-----')[0]
246         """
247         To-do: Posting the key, cert, certList might need modification
248         based on how AAF distributes the files.
249
250         """
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)
254
255 def lookforfiles():
256     count = 0
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)
263                 count += 1
264             else:
265                 logging.error("Cadi password file %s not present under cert directory", cadi_file)
266                 exit()
267     if count > 0:
268         cleanup()
269     else:
270         logging.debug("No jks/p12 files found under cert directory %s", Path)
271
272
273 def readCertProperties():
274     connected = makeHealthcheckCall(headers, timePassed)
275
276     if connected:
277         count = 0
278         if os.path.isfile(Path + "/certs.properties"):
279             with open(Path + "/certs.properties", "r") as f:
280                 for line in f:
281                     if not "*****" in line:
282                         zipFileList.append(line)
283                     else:
284                         extractZipFiles(zipFileList, count)
285                         count += 1
286                         del zipFileList[:]
287         else:
288             logging.debug("No zipfiles present under cert directory")
289
290         logging.info("Looking for jks/p12 files under cert directory")
291         lookforfiles()
292
293 readCertProperties()