Coverage for /root/GitHubProjects/impacket/impacket/examples/ntlmrelayx/utils/ssl.py : 17%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Impacket - Collection of Python classes for working with network protocols.
2#
3# SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved.
4#
5# This software is provided under a slightly modified version
6# of the Apache Software License. See the accompanying LICENSE file
7# for more information.
8#
9# Description:
10# SSL utilities
11#
12# Various functions and classes for SSL support:
13# - generating certificates
14# - creating SSL capable SOCKS protocols
15#
16# Most of the SSL generation example code comes from the pyopenssl examples
17# https://github.com/pyca/pyopenssl/blob/master/examples/certgen.py
18#
19# Made available under the Apache license by the pyopenssl team
20# See https://github.com/pyca/pyopenssl/blob/master/LICENSE
21#
22# Author:
23# Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)
24#
25from OpenSSL import crypto, SSL
26from impacket import LOG
28# This certificate is not supposed to be exposed on the network
29# but only used for the local SOCKS plugins
30# therefore, for now we don't bother with a CA and with hosts/hostnames matching
31def generateImpacketCert(certname='/tmp/impacket.crt'):
32 # Create a private key
33 pkey = crypto.PKey()
34 pkey.generate_key(crypto.TYPE_RSA, 2048)
36 # Create the certificate
37 cert = crypto.X509()
38 cert.gmtime_adj_notBefore(0)
39 # Valid for 5 years
40 cert.gmtime_adj_notAfter(60*60*24*365*5)
41 subj = cert.get_subject()
42 subj.CN = 'impacket'
43 cert.set_pubkey(pkey)
44 cert.sign(pkey, "sha256")
45 # We write both from the same file
46 with open(certname, 'w') as certfile:
47 certfile.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey).decode('utf-8'))
48 certfile.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode('utf-8'))
49 LOG.debug('Wrote certificate to %s' % certname)
51# Class to wrap the client socket in SSL when serving as a SOCKS server
52class SSLServerMixin(object):
53 # This function will wrap the socksSocket in an SSL layer
54 def wrapClientConnection(self, cert='/tmp/impacket.crt'):
55 # Create a context, we don't really care about the SSL/TLS
56 # versions used since it is only intended for local use and thus
57 # doesn't have to be super-secure
58 ctx = SSL.Context(SSL.SSLv23_METHOD)
59 try:
60 ctx.use_privatekey_file(cert)
61 ctx.use_certificate_file(cert)
62 except SSL.Error:
63 LOG.info('SSL requested - generating self-signed certificate in /tmp/impacket.crt')
64 generateImpacketCert(cert)
65 ctx.use_privatekey_file(cert)
66 ctx.use_certificate_file(cert)
68 sslSocket = SSL.Connection(ctx, self.socksSocket)
69 sslSocket.set_accept_state()
71 # Now set this property back to the SSL socket instead of the regular one
72 self.socksSocket = sslSocket