// parsePacketToken parses the packet token and populates the right state.
// Returns an error if the token cannot be parsed or the signature fails
766688
func (t *tokenAccessor) ParsePacketToken(auth *connection.AuthInfo, data []byte) (*tokens.ConnectionClaims, error) {

	// Validate the certificate and parse the token
	claims, nonce, cert, err := t.getToken().Decode(false, data, auth.RemotePublicKey)
	if err != nil {
		return nil, err
	}

	// We always a need a valid remote context ID
	if claims.T == nil {
		return nil, errors.New("no claims found")
	}
	remoteContextID, ok := claims.T.Get(enforcerconstants.TransmitterLabel)
	if !ok {
		return nil, errors.New("no transmitter label")
	}

	auth.RemotePublicKey = cert
	auth.RemoteContext = nonce
	auth.RemoteContextID = remoteContextID
	auth.RemoteServiceContext = claims.EK

	return claims, nil
}
1331763
func (m *MockSendAlgorithm) OnPacketAcked(arg0 protocol.PacketNumber, arg1, arg2 protocol.ByteCount, arg3 time.Time) {
	m.ctrl.T.Helper()
	m.ctrl.Call(m, "OnPacketAcked", arg0, arg1, arg2, arg3)
}
141854
func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (rest []byte, err error) {
	// RFC 4880, section 5.2.3.1
	var (
		length     uint32
		packetType signatureSubpacketType
		isCritical bool
	)
	switch {
	case subpacket[0] < 192:
		length = uint32(subpacket[0])
		subpacket = subpacket[1:]
	case subpacket[0] < 255:
		if len(subpacket) < 2 {
			goto Truncated
		}
		length = uint32(subpacket[0]-192)<<8 + uint32(subpacket[1]) + 192
		subpacket = subpacket[2:]
	default:
		if len(subpacket) < 5 {
			goto Truncated
		}
		length = uint32(subpacket[1])<<24 |
			uint32(subpacket[2])<<16 |
			uint32(subpacket[3])<<8 |
			uint32(subpacket[4])
		subpacket = subpacket[5:]
	}
	if length > uint32(len(subpacket)) {
		goto Truncated
	}
	rest = subpacket[length:]
	subpacket = subpacket[:length]
	if len(subpacket) == 0 {
		err = errors.StructuralError("zero length signature subpacket")
		return
	}
	packetType = signatureSubpacketType(subpacket[0] & 0x7f)
	isCritical = subpacket[0]&0x80 == 0x80
	subpacket = subpacket[1:]
	sig.rawSubpackets = append(sig.rawSubpackets, outputSubpacket{isHashed, packetType, isCritical, subpacket})
	switch packetType {
	case creationTimeSubpacket:
		if !isHashed {
			err = errors.StructuralError("signature creation time in non-hashed area")
			return
		}
		if len(subpacket) != 4 {
			err = errors.StructuralError("signature creation time not four bytes")
			return
		}
		t := binary.BigEndian.Uint32(subpacket)
		sig.CreationTime = time.Unix(int64(t), 0)
	case signatureExpirationSubpacket:
		// Signature expiration time, section 5.2.3.10
		if !isHashed {
			return
		}
		if len(subpacket) != 4 {
			err = errors.StructuralError("expiration subpacket with bad length")
			return
		}
		sig.SigLifetimeSecs = new(uint32)
		*sig.SigLifetimeSecs = binary.BigEndian.Uint32(subpacket)
	case keyExpirationSubpacket:
		// Key expiration time, section 5.2.3.6
		if !isHashed {
			return
		}
		if len(subpacket) != 4 {
			err = errors.StructuralError("key expiration subpacket with bad length")
			return
		}
		sig.KeyLifetimeSecs = new(uint32)
		*sig.KeyLifetimeSecs = binary.BigEndian.Uint32(subpacket)
	case prefSymmetricAlgosSubpacket:
		// Preferred symmetric algorithms, section 5.2.3.7
		if !isHashed {
			return
		}
		sig.PreferredSymmetric = make([]byte, len(subpacket))
		copy(sig.PreferredSymmetric, subpacket)
	case issuerSubpacket:
		// Issuer, section 5.2.3.5
		if len(subpacket) != 8 {
			err = errors.StructuralError("issuer subpacket with bad length")
			return
		}
		sig.IssuerKeyId = new(uint64)
		*sig.IssuerKeyId = binary.BigEndian.Uint64(subpacket)
	case prefHashAlgosSubpacket:
		// Preferred hash algorithms, section 5.2.3.8
		if !isHashed {
			return
		}
		sig.PreferredHash = make([]byte, len(subpacket))
		copy(sig.PreferredHash, subpacket)
	case prefCompressionSubpacket:
		// Preferred compression algorithms, section 5.2.3.9
		if !isHashed {
			return
		}
		sig.PreferredCompression = make([]byte, len(subpacket))
		copy(sig.PreferredCompression, subpacket)
	case primaryUserIdSubpacket:
		// Primary User ID, section 5.2.3.19
		if !isHashed {
			return
		}
		if len(subpacket) != 1 {
			err = errors.StructuralError("primary user id subpacket with bad length")
			return
		}
		sig.IsPrimaryId = new(bool)
		if subpacket[0] > 0 {
			*sig.IsPrimaryId = true
		}
	case keyFlagsSubpacket:
		// Key flags, section 5.2.3.21
		if !isHashed {
			return
		}
		if len(subpacket) == 0 {
			err = errors.StructuralError("empty key flags subpacket")
			return
		}
		sig.FlagsValid = true
		if subpacket[0]&KeyFlagCertify != 0 {
			sig.FlagCertify = true
		}
		if subpacket[0]&KeyFlagSign != 0 {
			sig.FlagSign = true
		}
		if subpacket[0]&KeyFlagEncryptCommunications != 0 {
			sig.FlagEncryptCommunications = true
		}
		if subpacket[0]&KeyFlagEncryptStorage != 0 {
			sig.FlagEncryptStorage = true
		}
	case reasonForRevocationSubpacket:
		// Reason For Revocation, section 5.2.3.23
		if !isHashed {
			return
		}
		if len(subpacket) == 0 {
			err = errors.StructuralError("empty revocation reason subpacket")
			return
		}
		sig.RevocationReason = new(uint8)
		*sig.RevocationReason = subpacket[0]
		sig.RevocationReasonText = string(subpacket[1:])
	case featuresSubpacket:
		// Features subpacket, section 5.2.3.24 specifies a very general
		// mechanism for OpenPGP implementations to signal support for new
		// features. In practice, the subpacket is used exclusively to
		// indicate support for MDC-protected encryption.
		sig.MDC = len(subpacket) >= 1 && subpacket[0]&1 == 1
	case embeddedSignatureSubpacket:
		// Only usage is in signatures that cross-certify
		// signing subkeys. section 5.2.3.26 describes the
		// format, with its usage described in section 11.1
		if sig.EmbeddedSignature != nil {
			err = errors.StructuralError("Cannot have multiple embedded signatures")
			return
		}
		sig.EmbeddedSignature = new(Signature)
		// Embedded signatures are required to be v4 signatures see
		// section 12.1. However, we only parse v4 signatures in this
		// file anyway.
		if err := sig.EmbeddedSignature.parse(bytes.NewBuffer(subpacket)); err != nil {
			return nil, err
		}
		if sigType := sig.EmbeddedSignature.SigType; sigType != SigTypePrimaryKeyBinding {
			return nil, errors.StructuralError("cross-signature has unexpected type " + strconv.Itoa(int(sigType)))
		}
	default:
		if isCritical {
			err = errors.UnsupportedError("unknown critical signature subpacket type " + strconv.Itoa(int(packetType)))
			return
		}
	}
	return

Truncated:
	err = errors.StructuralError("signature subpacket truncated")
	return
}
78684
func (c *Client) processPacket(pkt packet.Generic) error {
	// prepare error
	var err error

	// handle individual packets
	switch typedPkt := pkt.(type) {
	case *packet.Subscribe:
		err = c.processSubscribe(typedPkt)
	case *packet.Unsubscribe:
		err = c.processUnsubscribe(typedPkt)
	case *packet.Publish:
		err = c.processPublish(typedPkt)
	case *packet.Puback:
		err = c.processPubackAndPubcomp(typedPkt.ID)
	case *packet.Pubcomp:
		err = c.processPubackAndPubcomp(typedPkt.ID)
	case *packet.Pubrec:
		err = c.processPubrec(typedPkt.ID)
	case *packet.Pubrel:
		err = c.processPubrel(typedPkt.ID)
	case *packet.Pingreq:
		err = c.processPingreq()
	case *packet.Disconnect:
		err = c.processDisconnect()
	default:
		err = c.die(ClientError, ErrUnexpectedPacket)
	}

	// return eventual error
	if err != nil {
		return err // error has already been handled
	}

	return nil
}
1317411
func (mw *GinJWTMiddleware) ParseTokenString(token string) (*jwt.Token, error) {
	return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
		if jwt.GetSigningMethod(mw.SigningAlgorithm) != t.Method {
			return nil, ErrInvalidSigningAlgorithm
		}
		if mw.usingPublicKeyAlgo() {
			return mw.pubKey, nil
		}

		return mw.Key, nil
	})
}
868335
func (d *Datapath) processUDPFinPacket(udpPacket *packet.Packet) (err error) { // nolint

	// add it to the udp fin cache. If we have already received the fin packet
	// for this flow. There is no need to change the connmark label again.
	if d.udpFinPacketTracker.AddOrUpdate(udpPacket.L4ReverseFlowHash(), true) {
		return nil
	}

	// clear cache entries.
	if err := d.udpAppOrigConnectionTracker.Remove(udpPacket.L4ReverseFlowHash()); err != nil {
		zap.L().Debug("Failed to clean cache udpappOrigConnectionTracker", zap.Error(err))
	}

	if err := d.udpSourcePortConnectionCache.Remove(udpPacket.SourcePortHash(packet.PacketTypeNetwork)); err != nil {
		zap.L().Debug("Failed to clean cache udpsourcePortConnectionCache", zap.Error(err))
	}

	zap.L().Debug("Updating the connmark label", zap.String("flow", udpPacket.L4FlowHash()))
	if err = d.conntrack.UpdateNetworkFlowMark(
		udpPacket.SourceAddress(),
		udpPacket.DestinationAddress(),
		udpPacket.IPProto(),
		udpPacket.SourcePort(),
		udpPacket.DestPort(),
		constants.DeleteConnmark,
	); err != nil {
		zap.L().Error("Failed to update conntrack table for flow to terminate connection",
			zap.String("app-conn", udpPacket.L4FlowHash()),
			zap.Error(err),
		)
	}

	return nil
}
1054981
func (v *GenerateServiceRequest) GetPackagePrefix() (o string) {
	if v != nil {
		o = v.PackagePrefix
	}
	return
}
914604
func (p *Packet) UDPTokenAttach(udpdata []byte, udptoken []byte) {

	udpData := []byte{}
	udpData = append(udpData, udpdata...)
	udpData = append(udpData, udptoken...)

	packetLenIncrease := uint16(len(udpdata) + len(udptoken))

	// IP Header Processing
	p.FixupIPHdrOnDataModify(p.ipHdr.ipTotalLength, p.ipHdr.ipTotalLength+packetLenIncrease)

	// Attach Data @ the end of current buffer
	p.ipHdr.Buffer = append(p.ipHdr.Buffer, udpData...)

	p.UpdateUDPChecksum()
}
1272093
func (pwm *Manager) DeleteResetToken(token string) (err error) {
	_, err = pwm.tokencollection.RemoveAll(bson.M{"token": token})
	return
}
799054
func (self *QueueCursor) ReadPacket() (pkt av.Packet, err error) {
	self.que.cond.L.Lock()
	buf := self.que.buf
	if !self.gotpos {
		self.pos = self.init(buf, self.que.videoidx)
		self.gotpos = true
	}
	for {
		if self.pos.LT(buf.Head) {
			self.pos = buf.Head
		} else if self.pos.GT(buf.Tail) {
			self.pos = buf.Tail
		}
		if buf.IsValidPos(self.pos) {
			pkt = buf.Get(self.pos)
			self.pos++
			break
		}
		if self.que.closed {
			err = io.EOF
			break
		}
		self.que.cond.Wait()
	}
	self.que.cond.L.Unlock()
	return
}
263245
func unsealToken(c context.Context, tok *messages.DelegationToken, certsProvider CertificatesProvider) (*messages.Subtoken, error) {
	// Grab the public keys of the service that signed the token, if we trust it.
	signerID, err := identity.MakeIdentity(tok.SignerId)
	if err != nil {
		return nil, fmt.Errorf("bad signer_id %q - %s", tok.SignerId, err)
	}
	certs, err := certsProvider.GetCertificates(c, signerID)
	switch {
	case err != nil:
		return nil, fmt.Errorf("failed to grab certificates of %q - %s", tok.SignerId, err)
	case certs == nil:
		return nil, fmt.Errorf("the signer %q is not trusted", tok.SignerId)
	}

	// Check the signature on the token.
	err = certs.CheckSignature(tok.SigningKeyId, tok.SerializedSubtoken, tok.Pkcs1Sha256Sig)
	if err != nil {
		return nil, err
	}

	// The signature is correct! Deserialize the subtoken.
	msg := &messages.Subtoken{}
	if err = proto.Unmarshal(tok.SerializedSubtoken, msg); err != nil {
		return nil, err
	}

	return msg, nil
}
575472
func (t *Tx) CompletedPacket() (id uint64, ok bool) {
	for {
		b := t.rx.Pull()
		if b == nil {
			return 0, false
		}

		if len(b) != 8 {
			t.rx.Flush()
			log.Printf("Ignoring completed packet: size (%v) is less than expected (%v)", len(b), 8)
			continue
		}

		v := binary.LittleEndian.Uint64(b)

		t.rx.Flush()

		return v, true
	}
}
1356197
func ParseSSF(packet []byte) (*ssf.SSFSpan, error) {
	span := &ssf.SSFSpan{}
	scratchBuff := pbufPool.Get().(*proto.Buffer)
	defer func() {
		scratchBuff.Reset()
		pbufPool.Put(scratchBuff)
	}()
	scratchBuff.SetBuf(packet)
	err := scratchBuff.Unmarshal(span)

	if err != nil {
		return nil, err
	}

	// Normalize the span:
	if span.Tags == nil {
		span.Tags = map[string]string{}
	}
	if span.Name == "" {
		// Even though incoming packets should have Name set,
		// this allows Veneur to be backwards-compatible.
		for k, v := range span.Tags {
			if k == "name" {
				span.Name = v
			}
		}
		delete(span.Tags, "name")
	}

	// Normalize metrics on the span:
	for _, sample := range span.Metrics {
		if sample.SampleRate == 0 {
			sample.SampleRate = 1
		}
	}
	return span, nil
}
1365166
func ParseRawTokenDetails(token string) (jwtToken []string, err error) {
	chunks := strings.Split(token, ".")
	for _, chunk := range chunks {
		jsonString, err := base64.RawURLEncoding.DecodeString(chunk)
		if err == nil {
			jwtToken = append(jwtToken, string(jsonString))
		}
	}

	return jwtToken, err
}
1077666
func parseContToken(token string) (pack int, offset int64, err error) {
	// Special case
	if token == "" {
		pack = 0
		offset = 0
		return
	}
	_, err = fmt.Sscan(token, &pack, &offset)

	return
}
1079371
func (s *LocalStore) SetHTTPChallengeToken(token, domain string, keyAuth []byte) error {
	s.lock.Lock()
	defer s.lock.Unlock()

	if s.storedData.HTTPChallenges == nil {
		s.storedData.HTTPChallenges = map[string]map[string][]byte{}
	}

	if _, ok := s.storedData.HTTPChallenges[token]; !ok {
		s.storedData.HTTPChallenges[token] = map[string][]byte{}
	}

	s.storedData.HTTPChallenges[token][domain] = keyAuth
	return nil
}
830608
func (p *Packet) DecodePacket() PacketManipulator {

	packetData := &Packet{
		ethernetLayer: &layers.Ethernet{},
		ipLayer:       &layers.IPv4{},
		tcpLayer:      &layers.TCP{},
	}

	newEthernetPacket := packetData.GetEthernetPacket()
	newIPPacket := packetData.GetIPPacket()
	newTCPPacket := packetData.GetTCPPacket()

	if ethernetLayer := p.packet.Layer(layers.LayerTypeEthernet); ethernetLayer != nil {
		ethernet, _ := ethernetLayer.(*layers.Ethernet)
		newEthernetPacket.SrcMAC = ethernet.SrcMAC
		newEthernetPacket.DstMAC = ethernet.DstMAC
		newEthernetPacket.EthernetType = ethernet.EthernetType
	}

	if ipLayer := p.packet.Layer(layers.LayerTypeIPv4); ipLayer != nil {
		ip, _ := ipLayer.(*layers.IPv4)

		newIPPacket.SrcIP = ip.SrcIP
		newIPPacket.DstIP = ip.DstIP
		newIPPacket.Version = ip.Version
		newIPPacket.Length = ip.Length
		newIPPacket.Protocol = ip.Protocol
		newIPPacket.TTL = ip.TTL
	}

	if tcpLayer := p.packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
		tcp, _ := tcpLayer.(*layers.TCP)

		newTCPPacket.SrcPort = tcp.SrcPort
		newTCPPacket.DstPort = tcp.DstPort
		newTCPPacket.Seq = tcp.Seq
		newTCPPacket.Ack = tcp.Ack
		newTCPPacket.SYN = tcp.SYN
		newTCPPacket.FIN = tcp.FIN
		newTCPPacket.RST = tcp.RST
		newTCPPacket.PSH = tcp.PSH
		newTCPPacket.ACK = tcp.ACK
		newTCPPacket.URG = tcp.URG
		newTCPPacket.ECE = tcp.ECE
		newTCPPacket.CWR = tcp.CWR
		newTCPPacket.NS = tcp.NS
		newTCPPacket.Checksum = tcp.Checksum
		newTCPPacket.Window = tcp.Window
	}

	packetData = &Packet{
		ethernetLayer: &newEthernetPacket,
		ipLayer:       &newIPPacket,
		tcpLayer:      &newTCPPacket,
	}

	return packetData
}