Skip to content

Commit

Permalink
Merge pull request #14 from slieberth/improve_override_mechanism_by_r…
Browse files Browse the repository at this point in the history
…etrieving_cert_from_server

Retrieve cert from server/router
  • Loading branch information
akarneliuk authored May 7, 2021
2 parents 86752ad + 828419e commit d51ff1a
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions pygnmi/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@
import time
import kthread

# Those three modules are required to retrieve cert from the router and extract cn name
import ssl
from cryptography import x509
from cryptography.hazmat.backends import default_backend

# Own modules
from pygnmi.path_generator import gnmi_path_generator

Expand Down Expand Up @@ -64,6 +69,20 @@ def __enter__(self):
except:
logging.error('The SSL certificate cannot be opened.')
raise Exception('The SSL certificate cannot be opened.')

else:
try:
ssl_cert = ssl.get_server_certificate((self.__target[0], self.__target[1])).encode("utf-8")
ssl_cert_deserialized = x509.load_pem_x509_certificate(ssl_cert, default_backend())
ssl_cert_common_names = ssl_cert_deserialized.subject.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)
ssl_target_name_override = ssl_cert_common_names[0].value
self.__options = [("grpc.ssl_target_name_override", ssl_target_name_override)]
logging.warning('ssl_target_name_override is applied, should be used for testing only!')
cert = grpc.ssl_channel_credentials(ssl_cert)

except:
logging.error(f'The SSL certificate cannot be retrieved from {self.__target}')
raise Exception(f'The SSL certificate cannot be retrieved from {self.__target}')

self.__channel = grpc.secure_channel(f'{self.__target[0]}:{self.__target[1]}',
credentials=cert, options=self.__options)
Expand Down

0 comments on commit d51ff1a

Please sign in to comment.