CSeq validation should only be done for non proxy applications
334834
public boolean validateCSeq(MobicentsSipServletRequest sipServletRequest) {
		final Request request = (Request) sipServletRequest.getMessage();
		final long localCseq = cseq;
		final long remoteCSeq =  ((CSeqHeader) request.getHeader(CSeqHeader.NAME)).getSeqNumber();
		final String method = request.getMethod();
		final boolean isAck = Request.ACK.equalsIgnoreCase(method);
		final boolean isPrackCancel= Request.PRACK.equalsIgnoreCase(method) || Request.CANCEL.equalsIgnoreCase(method);
		boolean resetLocalCSeq = true;

		if(isAck && isAckReceived(remoteCSeq)) {
			// Filter out ACK retransmissions for JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
			logger.debug("ACK filtered out as a retransmission. This Sip Session already has been ACKed.");
			return false;
		}
		if(isAck) {
			if(logger.isDebugEnabled()) {
				logger.debug("localCSeq : " + localCseq + ", remoteCSeq : " + remoteCSeq);
			}
			setAckReceived(remoteCSeq, true);
		}
		if(localCseq == remoteCSeq && !isAck) {
			logger.debug("dropping retransmission " + request + " since it matches the current sip session cseq " + localCseq);
			return false;
		}
		if(localCseq > remoteCSeq) {
			if(!isAck && !isPrackCancel) {
				logger.error("CSeq out of order for the following request " + sipServletRequest);
				if(Request.INVITE.equalsIgnoreCase(method)) {
					setAckReceived(remoteCSeq, false);
				}
				final SipServletResponse response = sipServletRequest.createResponse(Response.SERVER_INTERNAL_ERROR, "CSeq out of order");
				try {
					response.send();
				} catch (IOException e) {
					logger.error("Can not send error response", e);
				}
				return false;
			} else {
				// Issue 1714 : if the local cseq is greater then the remote one don't reset the local cseq
				resetLocalCSeq= false;
			}
		}
		if(logger.isDebugEnabled()) {
			logger.debug("resetLocalCSeq : " + resetLocalCSeq);
		}
		if(resetLocalCSeq) {
			setCseq(remoteCSeq);
			if(Request.INVITE.equalsIgnoreCase(method)) {
				setAckReceived(remoteCSeq, false);
			}
		}
		return true;
	}
967834
public static void validateScriptsCombination(Set<XmLepResourceSubType> scriptTypes,
                                                  LepMethod lepMethod,
                                                  UrlLepResourceKey compositeResourceKey) {
        byte mask = getCombinationMask(scriptTypes, lepMethod, compositeResourceKey);

        StringBuilder errors = new StringBuilder();
        if (isZero(mask, ZERO_PATTERN_NO_TENANT_AND_DEFAULT_AND_JAVA_CODE)) {
            errors.append(String.format("Has no one script of '%s', '%s' or native (java) implementation.",
                                        XmLepResourceSubType.TENANT, XmLepResourceSubType.DEFAULT));
        }

        if (isSetByPattern(mask, IS_SET_PATTERN_AROUND_AND_BEFORE)) {
            if (errors.length() > 0) {
                errors.append(" ");
            }

            errors.append(String.format("Has '%s' script with '%s'.", XmLepResourceSubType.BEFORE, XmLepResourceSubType.AROUND));
        }

        if (isSetByPattern(mask, IS_SET_PATTERN_AROUND_AND_AFTER)) {
            if (errors.length() > 0) {
                errors.append(" ");
            }

            errors.append(String.format("Has '%s' script with '%s'.", XmLepResourceSubType.AROUND, XmLepResourceSubType.AFTER));
        }

        if (isSetByPattern(mask, IS_SET_PATTERN_AROUND_AND_TENANT)) {
            if (errors.length() > 0) {
                errors.append(" ");
            }

            errors.append(String.format("Unallowed combination '%s' and '%s' scripts.", XmLepResourceSubType.AROUND, XmLepResourceSubType.TENANT));
        }

        if (errors.length() > 0) {
            throw new IllegalArgumentException(String.format("Resource key %s has script combination errors. %s",
                                                             compositeResourceKey,
                                                             errors.toString()));

        }
    }
2223
def validate_callback(self, service, pgturl, pgtid, pgtiou):
        """"""
        if not proxy_allowed(service):
            raise UnauthorizedServiceProxy("%s is not authorized to use proxy authentication" % service)

        if not is_scheme_https(pgturl):
            raise InvalidProxyCallback("Proxy callback %s is not HTTPS" % pgturl)

        if not proxy_callback_allowed(service, pgturl):
            raise InvalidProxyCallback("%s is not an authorized proxy callback URL" % pgturl)

        # Verify that the SSL certificate is valid
        verify = os.environ.get('REQUESTS_CA_BUNDLE', True)
        try:
            requests.get(pgturl, verify=verify, timeout=5)
        except requests.exceptions.SSLError:
            raise InvalidProxyCallback("SSL certificate validation failed for proxy callback %s" % pgturl)
        except requests.exceptions.RequestException as e:
            raise InvalidProxyCallback(e)

        # Callback certificate appears valid, so send the ticket strings
        pgturl = add_query_params(pgturl, {'pgtId': pgtid, 'pgtIou': pgtiou})
        try:
            response = requests.get(pgturl, verify=verify, timeout=5)
        except requests.exceptions.RequestException as e:
            raise InvalidProxyCallback(e)

        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            raise InvalidProxyCallback("Proxy callback %s returned %s" % (pgturl, e))
912655
def validateProxy(path):
    

    # load the proxy from path
    try:
        proxy = M2Crypto.X509.load_cert(path)
    except Exception, e:
        msg = "Unable to load proxy from path %s : %s" % (path, e)
        print >>sys.stderr, msg
        sys.exit(1)

    # make sure the proxy is RFC 3820 compliant
    # or is an end-entity X.509 certificate
    try:
        proxy.get_ext("proxyCertInfo")
    except LookupError:
        # it is not an RFC 3820 proxy so check
        # if it is an old globus legacy proxy
        subject = proxy.get_subject().as_text()
        if re.search(r'.+CN=proxy$', subject):
            # it is so print warning and exit
            RFCproxyUsage()
            sys.exit(1)

    # attempt to make sure the proxy is still good for more than 15 minutes
    try:
        expireASN1 = proxy.get_not_after().__str__()
        expireGMT  = time.strptime(expireASN1, "%b %d %H:%M:%S %Y %Z")
        expireUTC  = calendar.timegm(expireGMT)
        now = int(time.time())
        secondsLeft = expireUTC - now
    except Exception, e:
        # problem getting or parsing time so just let the client
        # continue and pass the issue along to the server
        secondsLeft = 3600

    if secondsLeft <= 0:
        msg = """\
Your proxy certificate is expired.

Please generate a new proxy certificate and
try again.
"""
        print >>sys.stderr, msg
        sys.exit(1)

    if secondsLeft < (60 * 15):
        msg = """\
Your proxy certificate expires in less than
15 minutes.

Please generate a new proxy certificate and
try again.
"""
        print >>sys.stderr, msg
        sys.exit(1)

    # return True to indicate validated proxy
    return True
978664
private void validateClient(Client client) throws RegistrationException {
        Set<Contract> contracts = client.getContracts();
        if (contracts.isEmpty()) {
            throw new NoContractFoundException(Messages.i18n.format("ESRegistry.NoContracts")); //$NON-NLS-1$
        }
        for (Contract contract : contracts) {
            validateContract(contract);
        }
    }
380408
@FFDCIgnore(NoSuchElementException.class)
    private void doInvalidations() {
        final boolean trace = TraceComponent.isAnyTracingEnabled();

        try {
            long now = System.currentTimeMillis();

            // loop through all the candidates eligible for invalidation
            BackedSession pmiStatSession = null; // fake session for pmi stats
            SessionStatistics pmiStats = null;

            if (trace && tc.isDebugEnabled())
                tcInvoke(tcSessionMetaCache, "iterator");

            @SuppressWarnings("rawtypes")
            Iterator<Cache.Entry<String, ArrayList>> it = sessionMetaCache.iterator();

            if (trace && tc.isDebugEnabled())
                tcReturn(tcSessionMetaCache, "iterator", it);

            while (it.hasNext()) {
                if (trace && tc.isDebugEnabled())
                    tcInvoke(tcSessionMetaCache, "_iterator.next");

                @SuppressWarnings("rawtypes")
                Cache.Entry<String, ArrayList> entry;
                try {
                    entry = it.next();
                } catch (NoSuchElementException x) {
                    // ignore - some JCache providers might raise this instead of returning null when modified during iterator
                    entry = null;
                }
                String id = entry == null ? null : entry.getKey();
                ArrayList<?> value = id == null ? null : entry.getValue();

                if (trace && tc.isDebugEnabled())
                    tcReturn(tcSessionMetaCache, "_iterator.next", id, value);

                if (id != null && !INVAL_KEY.equals(id)) {
                    SessionInfo sessionInfo = new SessionInfo(value);
                    long lastAccessTime = sessionInfo.getLastAccess();
                    short listenerTypes = sessionInfo.getListenerTypes();
                    int maxInactiveTime = sessionInfo.getMaxInactiveTime();
                    if ((listenerTypes & BackedSession.HTTP_SESSION_BINDING_LISTENER) == 0 // sessions that do NOT have binding listeners
                                    && maxInactiveTime >= 0
                                    && maxInactiveTime < (now - lastAccessTime) / 1000) {
                        if (now + _smc.getInvalidationCheckInterval() * 1000 <= System.currentTimeMillis()) {
                            // If the scan is taking more than pollInterval, just break and
                            // invalidate the sessions so far determined
                            break;
                        }

                        if (trace && tc.isDebugEnabled())
                            tcInvoke(tcSessionMetaCache, "remove", id, value);

                        boolean removed = sessionMetaCache.remove(id, value);

                        if (trace && tc.isDebugEnabled())
                            tcReturn(tcSessionMetaCache, "remove", removed);

                        if (removed) {
                            //delete sub rows
                            Set<String> propIds = sessionInfo.getSessionPropertyIds();
                            if (propIds != null && !propIds.isEmpty()) {
                                HashSet<String> propKeys = new HashSet<String>();
                                for (String propId : propIds)
                                    propKeys.add(createSessionAttributeKey(id, propId));

                                if (trace && tc.isDebugEnabled())
                                    tcInvoke(tcSessionAttrCache, "removeAll", propKeys);

                                sessionAttributeCache.removeAll(propKeys);

                                if (trace && tc.isDebugEnabled())
                                    tcReturn(tcSessionAttrCache, "removeAll");
                            }
                        }

                        /*
                         * We already did cleanUpCache during the invalidation processing. Therefore, the session is no longer
                         * in our cache, and superRemove should return null. We need to create a temporary Session with an
                         * accurate Id and creationTime to send to the PMI counters.
                         */
                        superRemove(id);
                        long createTime = sessionInfo.getCreationTime();
                        //we don't want to retrieve session, so use a fake one for pmi
                        if (pmiStatSession == null)
                            pmiStatSession = new CacheSession();
                        if (pmiStats == null)
                            pmiStats = _iStore.getSessionStatistics();
                        pmiStatSession.setId(id);
                        pmiStatSession.setCreationTime(createTime);
                        if (pmiStats != null) {
                            pmiStats.sessionDestroyed(pmiStatSession);
                            pmiStats.sessionDestroyedByTimeout(pmiStatSession);
                        }
                    }
                }
            }
        } catch (Exception x) {
            // auto FFDC
            Tr.error(tc, "ERROR_SESSION_INVAL", x);
        }
    }
1120818
def _validate_conn(self, conn):
        
        super(HTTPSConnectionPool, self)._validate_conn(conn)

        # Force connect early to allow us to validate the connection.
        if not getattr(conn, 'sock', None):  # AppEngine might not have  `.sock`
            conn.connect()

        if not conn.is_verified:
            warnings.warn((
                'Unverified HTTPS request is being made. '
                'Adding certificate verification is strongly advised. See: '
                'https://urllib3.readthedocs.org/en/latest/security.html'),
                InsecureRequestWarning)
1370806
def validate(cert, ca_name, crl_file):
    '''
    
    '''
    store = OpenSSL.crypto.X509Store()
    cert_obj = _read_cert(cert)
    if cert_obj is None:
        raise CommandExecutionError(
            'Failed to read cert from {0}, see log for details'.format(cert)
        )
    ca_dir = '{0}/{1}'.format(cert_base_path(), ca_name)
    ca_cert = _read_cert('{0}/{1}_ca_cert.crt'.format(ca_dir, ca_name))
    store.add_cert(ca_cert)
    # These flags tell OpenSSL to check the leaf as well as the
    # entire cert chain.
    X509StoreFlags = OpenSSL.crypto.X509StoreFlags
    store.set_flags(X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
    if crl_file is None:
        crl = OpenSSL.crypto.CRL()
    else:
        with salt.utils.files.fopen(crl_file) as fhr:
            crl = OpenSSL.crypto.load_crl(OpenSSL.crypto.FILETYPE_PEM, fhr.read())
    store.add_crl(crl)
    context = OpenSSL.crypto.X509StoreContext(store, cert_obj)
    ret = {}
    try:
        context.verify_certificate()
        ret['valid'] = True
    except OpenSSL.crypto.X509StoreContextError as e:
        ret['error'] = str(e)
        ret['error_cert'] = e.certificate
        ret['valid'] = False
    return ret
1118536
function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) {
  ensureSafeMemberName(key0, fullExp);
  ensureSafeMemberName(key1, fullExp);
  ensureSafeMemberName(key2, fullExp);
  ensureSafeMemberName(key3, fullExp);
  ensureSafeMemberName(key4, fullExp);

  return !options.unwrapPromises
      ? function cspSafeGetter(scope, locals) {
          var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;

          if (pathVal === null || pathVal === undefined) return pathVal;
          pathVal = pathVal[key0];

          if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
          pathVal = pathVal[key1];

          if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
          pathVal = pathVal[key2];

          if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
          pathVal = pathVal[key3];

          if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
          pathVal = pathVal[key4];

          return pathVal;
        }
      : function cspSafePromiseEnabledGetter(scope, locals) {
          var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
              promise;

          if (pathVal === null || pathVal === undefined) return pathVal;

          pathVal = pathVal[key0];
          if (pathVal && pathVal.then) {
            promiseWarning(fullExp);
            if (!("$$v" in pathVal)) {
              promise = pathVal;
              promise.$$v = undefined;
              promise.then(function(val) { promise.$$v = val; });
            }
            pathVal = pathVal.$$v;
          }
          if (!key1 || pathVal === null || pathVal === undefined) return pathVal;

          pathVal = pathVal[key1];
          if (pathVal && pathVal.then) {
            promiseWarning(fullExp);
            if (!("$$v" in pathVal)) {
              promise = pathVal;
              promise.$$v = undefined;
              promise.then(function(val) { promise.$$v = val; });
            }
            pathVal = pathVal.$$v;
          }
          if (!key2 || pathVal === null || pathVal === undefined) return pathVal;

          pathVal = pathVal[key2];
          if (pathVal && pathVal.then) {
            promiseWarning(fullExp);
            if (!("$$v" in pathVal)) {
              promise = pathVal;
              promise.$$v = undefined;
              promise.then(function(val) { promise.$$v = val; });
            }
            pathVal = pathVal.$$v;
          }
          if (!key3 || pathVal === null || pathVal === undefined) return pathVal;

          pathVal = pathVal[key3];
          if (pathVal && pathVal.then) {
            promiseWarning(fullExp);
            if (!("$$v" in pathVal)) {
              promise = pathVal;
              promise.$$v = undefined;
              promise.then(function(val) { promise.$$v = val; });
            }
            pathVal = pathVal.$$v;
          }
          if (!key4 || pathVal === null || pathVal === undefined) return pathVal;

          pathVal = pathVal[key4];
          if (pathVal && pathVal.then) {
            promiseWarning(fullExp);
            if (!("$$v" in pathVal)) {
              promise = pathVal;
              promise.$$v = undefined;
              promise.then(function(val) { promise.$$v = val; });
            }
            pathVal = pathVal.$$v;
          }
          return pathVal;
        };
}
694496
private void validateProcessReference(List<String> mqProcessList,
            Map<String, String> connectionProcessMap) throws RabbitmqCommunicateException
    {
        //RabbitMQプロセス一覧が未設定の場合、例外を出力する。
        if (mqProcessList == null || mqProcessList.size() == 0)
        {
            String message = "ProcessList is not defined.";
            throw new RabbitmqCommunicateException(message);
        }

        // 呼出元別、接続先RabbitMQプロセスの定義マップが未設定の場合、確認を行わない。
        if (connectionProcessMap == null || connectionProcessMap.size() == 0)
        {
            return;
        }

        Set<String> processSet = new HashSet<String>(mqProcessList);
        Set<String> connectionProcessSet = new HashSet<String>(connectionProcessMap.values());

        if (processSet.containsAll(connectionProcessSet) == false)
        {
            @SuppressWarnings("unchecked")
            Set<String> nonContainedProcessSet = new HashSet<String>(CollectionUtils.subtract(
                    connectionProcessSet, processSet));
            String messageFmt = "Connection process is illegal. NonContainedProcessSet={0}";
            String message = MessageFormat.format(messageFmt, nonContainedProcessSet.toString());
            throw new RabbitmqCommunicateException(message);
        }
    }
993712
public void validate(KeyStore keyStore, Certificate cert) throws CertificateException {
        Certificate[] certChain = null;
	if (cert != null && cert instanceof X509Certificate) {
            ((X509Certificate)cert).checkValidity();
            
            String certAlias = null;
            try {
                if (keyStore == null) {
                    throw new InvalidParameterException("Keystore cannot be null");
                }

                certAlias = keyStore.getCertificateAlias((X509Certificate)cert);
                if (certAlias == null) {
                    certAlias = "CHSMPP" + String.format("%016X", aliasCount.incrementAndGet());
                    keyStore.setCertificateEntry(certAlias, cert);
                }
                
                certChain = keyStore.getCertificateChain(certAlias);
                if (certChain == null || certChain.length == 0) {
                    throw new IllegalStateException("Unable to retrieve certificate chain");
                }
            }
            catch (KeyStoreException kse) {
                logger.debug("", kse);
                throw new CertificateException("Unable to validate certificate" +
					       (certAlias == null ? "":" for alias [" +certAlias + "]") + ": " + kse.getMessage(), kse);
            }
            validate(certChain);
        } 
    }
25339
def validate_nonce(nonce, secret):
    '''
    
    '''
    nonce_components = nonce.split(':', 2)
    if not len(nonce_components) == 3:
        return False
    timestamp = nonce_components[0]
    salt = nonce_components[1]
    nonce_signature = nonce_components[2]

    calculated_nonce = calculate_nonce(timestamp, secret, salt)

    if not nonce == calculated_nonce:
        return False

    return True
782258
function validateNewCredentialProperties (credentialConfig, credentialDetail) {
  // Tmp — horrible hack to remove.
  const credentialDetails = JSON.parse(JSON.stringify(credentialDetail));
  delete credentialDetails.scopes;

  const validationResult = validate(credentialConfig, credentialDetails);
  if (!validationResult.isValid) {
    return Promise.reject(new Error(validationResult.error));
  };

  return Promise.resolve(credentialDetails);
}
1228593
def _validate_request(endpoint, file_type='json', data=None, params=None):
        
        if not isinstance(endpoint, string_types) or endpoint.strip() == '':
            raise ClientException("Must submit `endpoint` for DHIS2 API")
        if not isinstance(file_type, string_types) or file_type.lower() not in ('json', 'csv', 'xml', 'pdf', 'xlsx'):
            raise ClientException("Invalid file_type: {}".format(file_type))
        if params:
            if not isinstance(params, (dict, list)):
                raise ClientException("`params` must be a dict or list of tuples, not {}".format(params.__class__.__name__))
            if isinstance(params, list) and not all([isinstance(elem, tuple) for elem in params]):
                raise ClientException("`params` list must all be tuples")
        if data and not isinstance(data, dict):
            raise ClientException("`data` must be a dict, not {}".format(data.__class__.__name__))
830875
function validateCurlyBeforeKeyword(curlyToken) {
         const keywordToken = sourceCode.getTokenAfter(curlyToken);

         if (style === '1tbs' && !astUtils.isTokenOnSameLine(curlyToken, keywordToken)) {
            context.report({
               node: curlyToken,
               messageId: 'nextLineClose',
               fix: removeNewlineBetween(curlyToken, keywordToken),
            });
         }

         if (style !== '1tbs' && astUtils.isTokenOnSameLine(curlyToken, keywordToken)) {
            context.report({
               node: curlyToken,
               messageId: 'sameLineClose',
               fix: (fixer) => fixer.insertTextAfter(curlyToken, '\n'),
            });
         }
      }
654218
public void validateWhitelisted(Props props) {
    String id = null;
    if (props.containsKey(PROXY_USER_KEY)) {
      id = props.get(PROXY_USER_KEY);
      Preconditions.checkArgument(
          !StringUtils.isEmpty(id), PROXY_USER_KEY + " is required.");
    } else if (props.containsKey(CommonJobProperties.SUBMIT_USER)) {
      id = props.get(CommonJobProperties.SUBMIT_USER);
      Preconditions.checkArgument(!StringUtils.isEmpty(id),
          CommonJobProperties.SUBMIT_USER + " is required.");
    } else {
      throw new IllegalArgumentException(
          "Property neither has " + PROXY_USER_KEY + " nor " + CommonJobProperties.SUBMIT_USER);
    }
    validateWhitelisted(id);
  }
370202
function validateWire () {
      if (wire.requests.length) return

      let i = self._selections.length
      while (i--) {
        const next = self._selections[i]
        let piece
        if (self.strategy === 'rarest') {
          const start = next.from + next.offset
          const end = next.to
          const len = end - start + 1
          const tried = {}
          let tries = 0
          const filter = genPieceFilterFunc(start, end, tried)

          while (tries < len) {
            piece = self._rarityMap.getRarestPiece(filter)
            if (piece < 0) break
            if (self._request(wire, piece, false)) return
            tried[piece] = true
            tries += 1
          }
        } else {
          for (piece = next.to; piece >= next.from + next.offset; --piece) {
            if (!wire.peerPieces.get(piece)) continue
            if (self._request(wire, piece, false)) return
          }
        }
      }

      // TODO: wire failed to validate as useful; should we close it?
      // probably not, since 'have' and 'bitfield' messages might be coming
    }