Wrap the grpc.insecure_channel.
765494
def wrap_insecure_channel(insecure_channel_func, tracer=None):
    """"""
    def call(*args, **kwargs):
        channel = insecure_channel_func(*args, **kwargs)

        try:
            target = kwargs.get('target')
            tracer_interceptor = OpenCensusClientInterceptor(tracer, target)
            intercepted_channel = grpc.intercept_channel(
                channel, tracer_interceptor)
            return intercepted_channel  # pragma: NO COVER
        except Exception:
            log.warning(
                'Failed to wrap insecure channel, '
                'clientlibs grpc calls not traced.')
            return channel
    return call
545837
public void addToChannel(Channel ch) throws IOException {
    ch.pipeline()
      .addFirst(ENCRYPTION_HANDLER_NAME, new EncryptionHandler(this))
      .addFirst(DECRYPTION_HANDLER_NAME, new DecryptionHandler(this));
  }
922677
@Override
  public void makeSecure(HttpServletRequest request, HttpServletResponse response)
    throws IOException
  {
    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.setHeader("Location", secureUrl(request, response));
    response.getOutputStream().flush();
    response.getOutputStream().close();
  }
105060
public byte[] wrap(byte []inBuf, int off, int len, MessageProp prop)
        throws GSSException {

        checkContext();

        logger.debug("enter wrap");

        byte [] token = null;
        boolean doGSIWrap = false;

        if (prop != null) {
            if (prop.getQOP() != 0 && prop.getQOP() != GSSConstants.GSI_BIG) {
                throw new GSSException(GSSException.BAD_QOP);
            }
            doGSIWrap = (!prop.getPrivacy() && prop.getQOP() == GSSConstants.GSI_BIG);
        }

        if (doGSIWrap) {
            throw new GSSException(GSSException.UNAVAILABLE);
/*DEL

            byte [] mic = getMIC(inBuf, off, len, null);

            byte [] wtoken = new byte[5 + len + mic.length];
            wtoken[0] = GSI_WRAP;
            wtoken[1] = 3;
            wtoken[2] = 0;
            wtoken[3] = (byte)(mic.length >>> 8);
            wtoken[4] = (byte)(mic.length >>> 0);
            System.arraycopy(mic, 0, wtoken, 5, mic.length);
            System.arraycopy(inBuf, off, wtoken, 5+mic.length, len);

            token = wtoken;
*/
        } else {
            token = wrap(inBuf, off, len);

            if (prop != null) {
                prop.setPrivacy(this.encryption);
                prop.setQOP(0);
            }
        }

        logger.debug("exit wrap");
        return token;
    }
200711
def security(name, *permissions):
    
    def inner(c):
        c.security = Security(name, *permissions)
        return c
    return inner
79742
private static void checkAccess(Channel c) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(
                new RuntimePermission("inheritedChannel")
            );
        }
    }
1270834
def recv(self, size):
        """"""
        return self._safe_call(
            True,
            super(SSLFileobjectMixin, self).recv,
            size,
        )
821180
public SSLEngineResult wrap(ByteBuffer [] appData,
            int offset, int length, ByteBuffer netData) throws SSLException {

        EngineArgs ea = new EngineArgs(appData, offset, length, netData);

        /*
         * We can be smarter about using smaller buffer sizes later.
         * For now, force it to be large enough to handle any
         * valid SSL/TLS record.
         */
        if (netData.remaining() < outputRecord.maxRecordSize) {
            return new SSLEngineResult(
                Status.BUFFER_OVERFLOW, getHSStatus(null), 0, 0);
        }

        try {
            synchronized (wrapLock) {
                return writeAppRecord(ea);
            }
        } catch (Exception e) {
            ea.resetPos();

            fatal(Alerts.alert_internal_error,
                "problem wrapping app data", e);
            return null;  // make compiler happy
        } finally {
            /*
             * Just in case something didn't reset limits properly.
             */
            ea.resetLim();
        }
    }
119626
def fake_wrap_socket(orig_wrap_socket_fn, *args, **kw):
    
    server_hostname = kw.get('server_hostname')
    if server_hostname is not None:
        matcher = httpretty.match_https_hostname(server_hostname)
        if matcher is None:
                return orig_wrap_socket_fn(*args, **kw)
    if 'sock' in kw:
        return kw['sock']
    else:
        return args[0]
1338795
public void unwrap(InputStream inStream, OutputStream outStream,
                       MessageProp msgProp)
        throws GSSException {
        throw new GSSException(GSSException.UNAVAILABLE);
    }
236530
def _apply_secure(self, func, permission=None):
        ''''''
        self._handle_api_doc(func, {'security': 'apikey'})

        @wraps(func)
        def wrapper(*args, **kwargs):
            if not current_user.is_authenticated:
                self.abort(401)

            if permission is not None:
                with permission.require():
                    return func(*args, **kwargs)
            else:
                return func(*args, **kwargs)

        return wrapper
524876
def sanitize(self):
        '''
        
        '''
        # Let the parent do its stuff
        super(IPv4Packet, self).sanitize()

        # Check the version
        if self.version != 4:
            raise ValueError("Protocol version must be 4")

        # Treat type-of-service as an 8-bit unsigned integer. Future versions
        # of this code may implement methods to treat it as DSCP+ECN
        if not isinstance(self.tos, numbers.Integral) \
        or self.tos < 0 \
        or self.tos >= 2 ** 8:
            raise ValueError('Invalid type of service')

        # Identification: An identifying value assigned by the sender to aid in
        # assembling the fragments of a datagram.
        if not isinstance(self.identification, numbers.Integral) \
        or self.identification < 0 \
        or self.identification >= 2 ** 16:
            raise ValueError('Invalid fragment identification')

        # An internet datagram can be marked "don't fragment."  Any internet
        # datagram so marked is not to be internet fragmented under any
        # circumstances.  If internet datagram marked don't fragment cannot be
        # delivered to its destination without fragmenting it, it is to be
        # discarded instead.
        if not isinstance(self.dont_fragment, bool):
            raise ValueError("Don't fragment flag must be a boolean")

        # The More Fragments flag bit (MF) is set if the datagram is not the
        # last fragment.  The Fragment Offset field identifies the fragment
        # location, relative to the beginning of the original unfragmented
        # datagram.  Fragments are counted in units of 8 octets.  The
        # fragmentation strategy is designed so than an unfragmented datagram
        # has all zero fragmentation information (MF = 0, fragment offset =
        # 0).  If an internet datagram is fragmented, its data portion must be
        # broken on 8 octet boundaries.
        if not isinstance(self.more_fragments, bool):
            raise ValueError('More fragments flag must be a boolean')

        # Fragment offset: This field indicates where in the datagram this
        # fragment belongs. The fragment offset is measured in units of 8
        # octets (64 bits).  The first fragment has offset zero.
        if not isinstance(self.fragment_offset, numbers.Integral) \
        or self.fragment_offset < 0 \
        or self.fragment_offset >= 2 ** 13:
            raise ValueError('Invalid fragment offset')

        # Check for don't-fragment combined with a fragment offset
        if self.dont_fragment and self.fragment_offset > 0:
            raise ValueError("A packet marked don't fragment can't have "
                             "a fragment-offset")

        # Check that the TTL is correct
        if not isinstance(self.ttl, numbers.Integral) \
        or self.ttl < 0 \
        or self.ttl >= 2 ** 8:
            raise ValueError('Invalid TTL')

        # Check the source and destination addresses
        if not isinstance(self.source, IPv4Address):
            raise ValueError('Source address must be IPv4')

        if not isinstance(self.destination, IPv4Address):
            raise ValueError('Destination address must be IPv4')
1051938
def _wrap(x, serializeFunc, encodeFunc=base64.urlsafe_b64encode, compress=True):
    
    return encodeFunc(serializeFunc(x, compress))
1210353
def safe_wraps(wrapper, *args, **kwargs):
    """"""
    while isinstance(wrapper, functools.partial):
        wrapper = wrapper.func
    return functools.wraps(wrapper, *args, **kwargs)
603751
def wrap(self, sock):
        """"""
        EMPTY_RESULT = None, {}
        try:
            s = self.context.wrap_socket(
                sock, do_handshake_on_connect=True, server_side=True,
            )
        except ssl.SSLError as ex:
            if ex.errno == ssl.SSL_ERROR_EOF:
                # This is almost certainly due to the cherrypy engine
                # 'pinging' the socket to assert it's connectable;
                # the 'ping' isn't SSL.
                return EMPTY_RESULT
            elif ex.errno == ssl.SSL_ERROR_SSL:
                if _assert_ssl_exc_contains(ex, 'http request'):
                    # The client is speaking HTTP to an HTTPS server.
                    raise errors.NoSSLError

                # Check if it's one of the known errors
                # Errors that are caught by PyOpenSSL, but thrown by
                # built-in ssl
                _block_errors = (
                    'unknown protocol', 'unknown ca', 'unknown_ca',
                    'unknown error',
                    'https proxy request', 'inappropriate fallback',
                    'wrong version number',
                    'no shared cipher', 'certificate unknown',
                    'ccs received early',
                    'certificate verify failed',  # client cert w/o trusted CA
                )
                if _assert_ssl_exc_contains(ex, *_block_errors):
                    # Accepted error, let's pass
                    return EMPTY_RESULT
            elif _assert_ssl_exc_contains(ex, 'handshake operation timed out'):
                # This error is thrown by builtin SSL after a timeout
                # when client is speaking HTTP to an HTTPS server.
                # The connection can safely be dropped.
                return EMPTY_RESULT
            raise
        except generic_socket_error as exc:
            """It is unclear why exactly this happens.

            It's reproducible only with openssl>1.0 and stdlib ``ssl`` wrapper.
            In CherryPy it's triggered by Checker plugin, which connects
            to the app listening to the socket port in TLS mode via plain
            HTTP during startup (from the same process).


            Ref: https://github.com/cherrypy/cherrypy/issues/1618
            """
            is_error0 = exc.args == (0, 'Error')

            if is_error0 and IS_ABOVE_OPENSSL10:
                return EMPTY_RESULT
            raise
        return s, self.get_environ(s)
1256158
void toggleSecureServer() {

        if (m_fieldSecureServer.isEmpty()) {
            m_fieldExclusiveURL.setEnabled(false);
            m_fieldExclusiveError.setEnabled(false);
            return;
        }
        m_fieldExclusiveURL.setEnabled(true);
        m_fieldExclusiveError.setEnabled(true);
    }
679074
def wrap(self, sock):
        """"""
        try:
            s = ssl.wrap_socket(sock, do_handshake_on_connect=True,
                    server_side=True, certfile=self.certificate,
                    keyfile=self.private_key, ssl_version=ssl.PROTOCOL_SSLv23)
        except ssl.SSLError, e:
            if e.errno == ssl.SSL_ERROR_EOF:
                # This is almost certainly due to the cherrypy engine
                # 'pinging' the socket to assert it's connectable;
                # the 'ping' isn't SSL.
                return None, {}
            elif e.errno == ssl.SSL_ERROR_SSL:
                if e.args[1].endswith('http request'):
                    # The client is speaking HTTP to an HTTPS server.
                    raise wsgiserver.NoSSLError
            raise
        return s, self.get_environ(s)