Install a local SSL certificate
764155
def install_cert(selfsigned):
    """"""

    _check_root()

    if selfsigned:
        log('Generating self signed (insecure) certificate/key '
            'combination')

        try:
            os.mkdir('/etc/ssl/certs/hfos')
        except FileExistsError:
            pass
        except PermissionError:
            log("Need root (e.g. via sudo) to generate ssl certificate")
            sys.exit(1)

        def create_self_signed_cert():
            """Create a simple self signed SSL certificate"""

            # create a key pair
            k = crypto.PKey()
            k.generate_key(crypto.TYPE_RSA, 1024)

            if os.path.exists(cert_file):
                try:
                    certificate = open(cert_file, "rb").read()
                    old_cert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                                       certificate)
                    serial = old_cert.get_serial_number() + 1
                except (crypto.Error, OSError) as e:
                    log('Could not read old certificate to increment '
                        'serial:', type(e), e, exc=True, lvl=warn)
                    serial = 1
            else:
                serial = 1

            # create a self-signed certificate
            certificate = crypto.X509()
            certificate.get_subject().C = "DE"
            certificate.get_subject().ST = "Berlin"
            certificate.get_subject().L = "Berlin"
            # noinspection PyPep8
            certificate.get_subject().O = "Hackerfleet"
            certificate.get_subject().OU = "Hackerfleet"
            certificate.get_subject().CN = gethostname()
            certificate.set_serial_number(serial)
            certificate.gmtime_adj_notBefore(0)
            certificate.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)
            certificate.set_issuer(certificate.get_subject())
            certificate.set_pubkey(k)
            certificate.sign(k, b'sha512')

            open(key_file, "wt").write(str(
                crypto.dump_privatekey(crypto.FILETYPE_PEM, k),
                encoding="ASCII"))

            open(cert_file, "wt").write(str(
                crypto.dump_certificate(crypto.FILETYPE_PEM, certificate),
                encoding="ASCII"))

            open(combined_file, "wt").write(str(
                crypto.dump_certificate(crypto.FILETYPE_PEM, certificate),
                encoding="ASCII") + str(
                crypto.dump_privatekey(crypto.FILETYPE_PEM, k),
                encoding="ASCII"))

        create_self_signed_cert()

        log('Done: Install Cert')
    else:

        # TODO

        log('Not implemented yet. You can build your own certificate and '
            'store it in /etc/ssl/certs/hfos/server-cert.pem - it should '
            'be a certificate with key, as this is used server side and '
            'there is no way to enter a separate key.', lvl=error)
124094
def accept(self):
        """"""
        newsock, addr = socket.accept(self)
        ssl_sock = SSLSocket(newsock._sock,
                             keyfile=self.keyfile,
                             certfile=self.certfile,
                             server_side=True,
                             cert_reqs=self.cert_reqs,
                             ssl_version=self.ssl_version,
                             ca_certs=self.ca_certs,
                             do_handshake_on_connect=self.do_handshake_on_connect,
                             suppress_ragged_eofs=self.suppress_ragged_eofs,
                             ciphers=self.ciphers)
        return ssl_sock, addr
468137
def install_ca_cert(ca_cert, name=None):
    
    if not ca_cert:
        return
    if not isinstance(ca_cert, bytes):
        ca_cert = ca_cert.encode('utf8')
    if not name:
        name = 'juju-{}'.format(charm_name())
    cert_file = '/usr/local/share/ca-certificates/{}.crt'.format(name)
    new_hash = hashlib.md5(ca_cert).hexdigest()
    if file_hash(cert_file) == new_hash:
        return
    log("Installing new CA cert at: {}".format(cert_file), level=INFO)
    write_file(cert_file, ca_cert)
    subprocess.check_call(['update-ca-certificates', '--fresh'])
875577
def _init_ssl(self):
        

        if not have_openssl:
            raise ImportError('SSL sockets have been disabled due to missing requirement: pyopenssl.')

        try:
            ctx = SSL.Context(SSL.TLSv1_METHOD)

            if isinstance(self.ssl_key, crypto.PKey):
                ctx.use_privatekey(self.ssl_key)
            else:
                ctx.use_privatekey_file(self.ssl_key)

            if isinstance(self.ssl_certificate, crypto.X509):
                ctx.use_certificate(self.ssl_certificate)
            else:
                ctx.use_certificate_file(self.ssl_certificate)

            if isinstance(self.ssl_ca, crypto.X509):
                store = ctx.get_cert_store()
                store.add_cert(self.ssl_ca)
            else:
                ctx.load_verify_locations(self.ssl_ca, None)

            verify_method = SSL.VERIFY_PEER
            if (self._ssl_allow_self_signed):
                verify_method = SSL.VERIFY_NONE

            ctx.set_verify(verify_method, self._verify_ssl_callback)

            self._device = SSL.Connection(ctx, self._device)

        except SSL.Error as err:
            raise CommError('Error setting up SSL connection.', err)
890023
def gen_cert_request(filepath, keyfile, config, silent=False):
    
    message = 'generate ssl certificate request'
    cmd = (
        'openssl req -new -key {} -out {} -subj "{}"'
        ' -extensions v3_req -config {}').format(
            keyfile, filepath, SUBJECT, config)
    call_openssl(cmd, message, silent)
1329652
def install(self):  # pragma: no cover
        """"""
        keys = self.get_keys_from_ldap()
        for user, ssh_keys in keys.items():
            user_dir = API.__authorized_keys_path(user)
            if not os.path.isdir(user_dir):
                os.makedirs(user_dir)
            authorized_keys_file = os.path.join(user_dir, 'authorized_keys')
            with open(authorized_keys_file, 'w') as FILE:
                print("\n".join([k.decode() for k in ssh_keys]), file=FILE)
385017
def cert(type, url = ENV['ONEVIEWSDK_URL'])
      case type.downcase
      when 'check'
        fail_nice 'Must specify a url' unless url
        puts "Checking certificate for '#{url}' ..."
        if OneviewSDK::SSLHelper.check_cert(url)
          puts 'Certificate is valid!'
        else
          fail_nice 'Certificate Validation Failed!'
        end
      when 'import'
        fail_nice 'Must specify a url' unless url
        puts "Importing certificate for '#{url}' into '#{OneviewSDK::SSLHelper::CERT_STORE}'..."
        OneviewSDK::SSLHelper.install_cert(url)
      when 'list'
        if File.file?(OneviewSDK::SSLHelper::CERT_STORE)
          puts File.read(OneviewSDK::SSLHelper::CERT_STORE)
        else
          puts 'No certs imported!'
        end
      else fail_nice "Invalid action '#{type}'. Valid actions are [check, import, list]"
      end
    rescue StandardError => e
      fail_nice e.message
    end
1278199
async def connect(self, server_info, proto_code=None, *,
                            use_tor=False, disable_cert_verify=False,
                            proxy=None, short_term=False):
        '''
            
        '''
        self.server_info = server_info
        if not proto_code:
             proto_code,*_ = server_info.protocols
        self.proto_code = proto_code

        logger.debug("Connecting to: %r" % server_info)

        if proto_code == 'g':       # websocket
            # to do this, we'll need a websockets implementation that
            # operates more like a asyncio.Transport
            # maybe: `asyncws` or `aiohttp` 
            raise NotImplementedError('sorry no WebSocket transport yet')

        hostname, port, use_ssl = server_info.get_port(proto_code)

        if use_tor:
            if have_aiosocks:
                # Connect via Tor proxy proxy, assumed to be on localhost:9050
                # unless a tuple is given with another host/port combo.
                try:
                    socks_host, socks_port = use_tor
                except TypeError:
                    socks_host, socks_port = 'localhost', 9050

                # basically no-one has .onion SSL certificates, and
                # pointless anyway.
                disable_cert_verify = True

                assert not proxy, "Sorry not yet supporting proxy->tor->dest"

                logger.debug(" .. using TOR")

                proxy = aiosocks.Socks5Addr(socks_host, int(socks_port))
            else:
                logger.debug("Error: want to use tor, but no aiosocks module.")

        if use_ssl == True and disable_cert_verify:
            # Create a more liberal SSL context that won't
            # object to self-signed certicates. This is 
            # very bad on public Internet, but probably ok
            # over Tor
            use_ssl = ssl.create_default_context()
            use_ssl.check_hostname = False
            use_ssl.verify_mode = ssl.CERT_NONE

            logger.debug(" .. SSL cert check disabled")

        async def _reconnect():
            if self.protocol: return        # race/duplicate work

            if proxy:
                if have_aiosocks:
                    transport, protocol = await aiosocks.create_connection(
                                            StratumProtocol, proxy=proxy,
                                            proxy_auth=None,
                                            remote_resolve=True, ssl=use_ssl,
                                            dst=(hostname, port))
                else:
                    logger.debug("Error: want to use proxy, but no aiosocks module.")
            else:
                transport, protocol = await self.loop.create_connection(
                                                        StratumProtocol, host=hostname,
                                                        port=port, ssl=use_ssl)

            self.protocol = protocol
            protocol.client = self

            # capture actual values used
            self.actual_connection = dict(hostname=hostname, port=int(port),
                                            ssl=bool(use_ssl), tor=bool(proxy))
            self.actual_connection['ip_addr'] = transport.get_extra_info('peername',
                                                        default=['unknown'])[0]

            if not short_term:
                self.ka_task = self.loop.create_task(self._keepalive())

            logger.debug("Connected to: %r" % server_info)

        # close whatever we had
        if self.protocol:
            self.protocol.close()
            self.protocol = None

        self.reconnect = _reconnect
        await self.reconnect()
1103213
def generate
      cert = OpenSSL::X509::Certificate.new
      configure(cert)
      add_extensions(cert)
      cert.sign(key, OpenSSL::Digest::SHA256.new)
    end
1053745
def _local_install(self, args, pkg_name=None):
        '''
        
        '''
        if len(args) < 2:
            raise SPMInvocationError('A package file must be specified')

        self._install(args)
910383
def installSite(self, siteStore, domain, publicURL, generateCert=True):
        
        certPath = siteStore.filesdir.child("server.pem")
        if generateCert and not certPath.exists():
            certPath.setContent(self._createCert(domain, genSerial()))

        # Install the base Mantissa offering.
        IOfferingTechnician(siteStore).installOffering(baseOffering)

        # Make the HTTP server baseOffering includes listen somewhere.
        site = siteStore.findUnique(SiteConfiguration)
        site.hostname = domain
        installOn(
            TCPPort(store=siteStore, factory=site, portNumber=8080),
            siteStore)
        installOn(
            SSLPort(store=siteStore, factory=site, portNumber=8443,
                    certificatePath=certPath),
            siteStore)

        # Make the SSH server baseOffering includes listen somewhere.
        shell = siteStore.findUnique(SecureShellConfiguration)
        installOn(
            TCPPort(store=siteStore, factory=shell, portNumber=8022),
            siteStore)

        # Install a front page on the top level store so that the
        # developer will have something to look at when they start up
        # the server.
        fp = siteStore.findOrCreate(publicweb.FrontPage, prefixURL=u'')
        installOn(fp, siteStore)
1326318
def _init_server_authentication(self, ssl_verify: OpenSslVerifyEnum, ssl_verify_locations: Optional[str]) -> None:
        
        self._ssl_ctx.set_verify(ssl_verify.value)
        if ssl_verify_locations:
            # Ensure the file exists
            with open(ssl_verify_locations):
                pass
            self._ssl_ctx.load_verify_locations(ssl_verify_locations)
481231
def importExistingServerCertificate(self, alias, certPassword, certFile):
        """"""
        url = self._url + "/sslcertificates/importExistingServerCertificate"
        files = {}
        files['certFile'] = certFile
        params = {
            "f" : "json",
            "alias" : alias,
            "certPassword" : certPassword
        }
        return self._post(url=url,
                            param_dict=params,
                            securityHandler=self._securityHandler,
                            files=files,
                            proxy_url=self._proxy_url,
                            proxy_port=self._proxy_port)
905508
def get_ssl(database):
    

    # Set available keys per engine
    if database['engine'] == 'postgresql':
        keys = ['sslmode', 'sslcert', 'sslkey',
                'sslrootcert', 'sslcrl', 'sslcompression']
    else:
        keys = ['ssl_ca', 'ssl_capath', 'ssl_cert', 'ssl_key',
                'ssl_cipher', 'ssl_check_hostname']

    # Loop thru keys
    ssl = {}
    for key in keys:
        value = database.get(key, None)
        if value is not None:
            ssl[key] = value

    return ssl
1269131
function newClientStub() {
    // First create the appropriate TLS certs with dgraph cert:
    //     $ dgraph cert
    //     $ dgraph cert -n localhost
    //     $ dgraph cert -c user
    const rootCaCert = fs.readFileSync(path.join(__dirname, 'tls', 'ca.crt'));
    const clientCertKey = fs.readFileSync(path.join(__dirname, 'tls', 'client.user.key'));
    const clientCert = fs.readFileSync(path.join(__dirname, 'tls', 'client.user.crt'));
    return new dgraph.DgraphClientStub(
        "localhost:9080",
        grpc.credentials.createSsl(rootCaCert, clientCertKey, clientCert));
}
309594
def run_local(client):
  """"""
  webbrowser.open(client.get_auth_uri())
  code = wait_for_redirect()
  return client.get_token(code)
1073564
def common_config_nginx_ssl(self):
        
        if prompt(red(' * Change url from http to https (y/n)?'), default='n') == 'y':
            if not exists(self.nginx_ssl_dir):
                sudo('mkdir -p {0}'.format(self.nginx_ssl_dir))

            # generate ssh key
            sudo('openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout {0}/cert.key -out {0}/cert.pem'.format(self.nginx_ssl_dir))

            # do nginx config config
            put(StringIO(self.nginx_web_ssl_config), '/etc/nginx/sites-available/default', use_sudo=True)

            sudo('service nginx restart')

            print(green(' * Make Nginx from http to https.'))
            print(green(' * Done'))
            print()