| 1 |
# Copyright (c) Siemens AG, 2022 |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
import logging |
| 16 |
import socket |
| 17 |
import sys |
| 18 |
import threading |
| 19 |
|
| 20 |
from io import BytesIO as StringIO |
| 21 |
from socket import AF_INET, SOCK_STREAM |
| 22 |
from ssl import CERT_REQUIRED, SSLContext, SSLError |
| 23 |
|
| 24 |
from ncclient.capabilities import Capabilities |
| 25 |
from ncclient.logging_ import SessionLoggerAdapter |
| 26 |
from ncclient.transport.errors import TLSError |
| 27 |
from ncclient.transport.session import Session |
| 28 |
from ncclient.transport.parser import DefaultXMLParser |
| 29 |
|
| 30 |
logger = logging.getLogger("ncclient.transport.tls") |
| 31 |
|
| 32 |
DEFAULT_TLS_NETCONF_PORT = 6513 |
| 33 |
DEFAULT_TLS_TIMEOUT = 120 |
| 34 |
|
| 35 |
BUF_SIZE = 4096 |
| 36 |
|
| 37 |
|
| 38 |
class TLSSession(Session): |
| 39 |
|
| 40 |
def __init__(self, device_handler): |
| 41 |
capabilities = Capabilities(device_handler.get_capabilities()) |
| 42 |
Session.__init__(self, capabilities) |
| 43 |
self._host = None |
| 44 |
self._connected = False |
| 45 |
self._socket = None |
| 46 |
self._buffer = StringIO() |
| 47 |
self._device_handler = device_handler |
| 48 |
self._message_list = [] |
| 49 |
self._closing = threading.Event() |
| 50 |
self.parser = DefaultXMLParser(self) |
| 51 |
self.logger = SessionLoggerAdapter(logger, {'session': self}) |
| 52 |
|
| 53 |
def _dispatch_message(self, raw): |
| 54 |
self.logger.info("Received message from host") |
| 55 |
self.logger.debug("Received:\n%s", raw) |
| 56 |
return super(TLSSession, self)._dispatch_message(raw) |
| 57 |
|
| 58 |
def close(self): |
| 59 |
self._closing.set() |
| 60 |
self._socket.close() |
| 61 |
self._connected = False |
| 62 |
|
| 63 |
def connect(self, host=None, port=DEFAULT_TLS_NETCONF_PORT, |
| 64 |
keyfile=None, certfile=None, ca_certs=None, |
| 65 |
protocol=None, check_hostname=True, server_hostname=None, |
| 66 |
timeout=DEFAULT_TLS_TIMEOUT): |
| 67 |
"""Establish NETCONF session via TLS. |
| 68 |
|
| 69 |
:param host: Hostname or IP address to connect to. |
| 70 |
:param port: Port number which would be used for connection, the |
| 71 |
default value is 6513 (`DEFAULT_TLS_NETCONF_PORT`). |
| 72 |
:param certfile: Points to file in PEM format with client's certificate |
| 73 |
and optionally with client's private key. |
| 74 |
:param keyfile: Points to file with client's private key in PEM format, |
| 75 |
if the latter is not in certfile. |
| 76 |
:param ca_certs: Points to file containing a list of certificates, |
| 77 |
which should be used to verify server certificate. |
| 78 |
:param protocol: Protocol version to use. Should be either |
| 79 |
ssl.PROTOCOL_TLS_CLIENT for Python 3.6+, or ssl.PROTOCOL_TLS |
| 80 |
for older versions. |
| 81 |
:param check_hostname: If set to True, perform verification of the |
| 82 |
hostname during the handshake. |
| 83 |
:param server_hostname: If set, is used upon hostname checking instead |
| 84 |
of the `host` parameter. |
| 85 |
:param timeout: Specifies the connection timeout, defaults to |
| 86 |
120 seconds (`DEFAULT_TLS_TIMEOUT`). |
| 87 |
|
| 88 |
:raise TLSError if the connection can not be established. |
| 89 |
""" |
| 90 |
if host is None: |
| 91 |
raise TLSError('Missing host') |
| 92 |
if certfile is None: |
| 93 |
raise TLSError('Missing client certificate file') |
| 94 |
if protocol is None: |
| 95 |
raise TLSError('Missing TLS protocol') |
| 96 |
|
| 97 |
ssl_context = SSLContext(protocol) |
| 98 |
ssl_context.verify_mode = CERT_REQUIRED |
| 99 |
ssl_context.check_hostname = check_hostname |
| 100 |
try: |
| 101 |
ssl_context.load_cert_chain(certfile=certfile, keyfile=keyfile) |
| 102 |
except SSLError: |
| 103 |
raise TLSError('Bad client private key / certificate pair') |
| 104 |
except IOError: |
| 105 |
raise TLSError('Private key / certificate pair not found') |
| 106 |
|
| 107 |
if ca_certs: |
| 108 |
try: |
| 109 |
ssl_context.load_verify_locations(cafile=ca_certs) |
| 110 |
except SSLError: |
| 111 |
raise TLSError('Bad Certification Authority file') |
| 112 |
except IOError: |
| 113 |
raise TLSError('CA certificate file not found') |
| 114 |
|
| 115 |
sock = socket.socket(AF_INET, SOCK_STREAM) |
| 116 |
ssl_sock = ssl_context.wrap_socket( |
| 117 |
sock, do_handshake_on_connect=False, |
| 118 |
server_hostname=server_hostname or host) |
| 119 |
ssl_sock.settimeout(timeout) |
| 120 |
|
| 121 |
try: |
| 122 |
ssl_sock.connect((host, port)) |
| 123 |
except Exception: |
| 124 |
raise TLSError("Could not connect to %s:%s" % (host, port)) |
| 125 |
|
| 126 |
try: |
| 127 |
ssl_sock.do_handshake() |
| 128 |
except Exception: |
| 129 |
raise TLSError("Unsuccessful TLS handshake with %s:%s" % (host, port)) |
| 130 |
|
| 131 |
self._host = host |
| 132 |
self._socket = ssl_sock |
| 133 |
self._connected = True |
| 134 |
self._post_connect() |
| 135 |
|
| 136 |
def _transport_read(self): |
| 137 |
return self._socket.recv(BUF_SIZE) |
| 138 |
|
| 139 |
def _transport_write(self, data): |
| 140 |
return self._socket.send(data) |
| 141 |
|
| 142 |
def _transport_register(self, selector, event): |
| 143 |
selector.register(self._socket, event) |
| 144 |
|
| 145 |
def _send_ready(self): |
| 146 |
# In contrast to Paramiko's `Channel`, pure python sockets do not |
| 147 |
# expose `send_ready()` function. |
| 148 |
return True |
| 149 |
|
| 150 |
@property |
| 151 |
def host(self): |
| 152 |
"""Host this session is connected to, or None if not connected.""" |
| 153 |
if hasattr(self, '_host'): |
| 154 |
return self._host |
| 155 |
return None |