//GenerateTCPFlow returns an array of PacketFlowManipulator interface
346071
func (p *PacketFlow) GenerateTCPFlow(pt PacketFlowType) (PacketFlowManipulator, error) {

	if pt == 0 {
		//Create a SYN packet to initialize the flow
		firstPacket := NewPacket()
		if err := firstPacket.AddEthernetLayer(p.sMAC, p.dMAC); err != nil {
			return nil, fmt.Errorf("unable tp add ethernet layer: %s", err)
		}
		if err := firstPacket.AddIPLayer(p.sIP, p.dIP); err != nil {
			return nil, fmt.Errorf("unable to add ip layer: %s", err)
		}
		if err := firstPacket.AddTCPLayer(p.sPort, p.dPort); err != nil {
			return nil, fmt.Errorf("unable to add tcp layer: %s", err)
		}
		firstPacket.SetTCPSyn()
		firstPacket.SetTCPSequenceNumber(firstPacket.GetTCPSequenceNumber())
		firstPacket.SetTCPAcknowledgementNumber(firstPacket.GetTCPAcknowledgementNumber())
		synPacket, _ := firstPacket.(*Packet)

		p.flow = append(p.flow, synPacket)

		//Create a SynAck packet
		secondPacket := NewPacket()
		if err := secondPacket.AddEthernetLayer(p.sMAC, p.dMAC); err != nil {
			return nil, fmt.Errorf("unable to add ethernet layer: %s", err)
		}
		if err := secondPacket.AddIPLayer(p.dIP, p.sIP); err != nil {
			return nil, fmt.Errorf("unable to add ip layer: %s", err)
		}
		if err := secondPacket.AddTCPLayer(p.dPort, p.sPort); err != nil {
			return nil, fmt.Errorf("unable to add tcp layer: %s", err)
		}
		secondPacket.SetTCPSynAck()
		secondPacket.SetTCPSequenceNumber(0)
		secondPacket.SetTCPAcknowledgementNumber(firstPacket.GetTCPSequenceNumber() + 1)
		synackPacket, _ := secondPacket.(*Packet)

		p.flow = append(p.flow, synackPacket)

		//Create an Ack Packet
		thirdPacket := NewPacket()
		if err := thirdPacket.AddEthernetLayer(p.sMAC, p.dMAC); err != nil {
			return nil, fmt.Errorf("unable tp add ethernet layer: %s", err)
		}
		if err := thirdPacket.AddIPLayer(p.sIP, p.dIP); err != nil {
			return nil, fmt.Errorf("unable to add ip layer: %s", err)
		}
		if err := thirdPacket.AddTCPLayer(p.sPort, p.dPort); err != nil {
			return nil, fmt.Errorf("unable to add tcp layer: %s", err)
		}
		thirdPacket.SetTCPAck()
		thirdPacket.SetTCPSequenceNumber(secondPacket.GetTCPAcknowledgementNumber())
		thirdPacket.SetTCPAcknowledgementNumber(secondPacket.GetTCPSequenceNumber() + 1)
		ackPacket, _ := thirdPacket.(*Packet)

		p.flow = append(p.flow, ackPacket)

		return p, nil

	} else if pt == 1 {

		for i := 0; i < len(PacketFlowTemplate1); i++ {
			//Create a Packet type variable to store decoded packet
			newPacket := NewPacket()
			packet := gopacket.NewPacket(PacketFlowTemplate1[i], layers.LayerTypeEthernet, gopacket.Default)
			newPacket.AddPacket(packet)

			p.flow = append(p.flow, newPacket.DecodePacket())

		}

		return p, nil
	} else if pt == 2 {

		for i := 0; i < len(PacketFlowTemplate2); i++ {

			//Create a Packet type variable to store decoded packet
			newPacket := NewPacket()
			packet := gopacket.NewPacket(PacketFlowTemplate2[i], layers.LayerTypeEthernet, gopacket.Default)
			newPacket.AddPacket(packet)

			p.flow = append(p.flow, newPacket.DecodePacket())

		}

		return p, nil
	} else if pt == 3 {

		for i := 0; i < len(PacketFlowTemplate3); i++ {

			//Create a Packet type variable to store decoded packet
			newPacket := NewPacket()
			packet := gopacket.NewPacket(PacketFlowTemplate3[i], layers.LayerTypeEthernet, gopacket.Default)
			newPacket.AddPacket(packet)

			p.flow = append(p.flow, newPacket.DecodePacket())

		}

		return p, nil
	}

	return nil, nil
}
267747
func (p *Packet) FixuptcpHdrOnTCPDataDetach(dataLength uint16, optionLength uint16) {

	// Update DataOffset
	buffer := p.ipHdr.Buffer[p.ipHdr.ipHeaderLen:]
	p.tcpHdr.tcpDataOffset = p.tcpHdr.tcpDataOffset - uint8(optionLength/4)
	buffer[tcpDataOffsetPos] = p.tcpHdr.tcpDataOffset << 4
}
578691
func (b *BigIP) CreateTcpProfile(name string, parent string) error {
	config := &TcpProfile{
		Name:         name,
		DefaultsFrom: parent,
	}

	return b.post(config, uriLtm, uriProfile, uriTcp)
}
992357
func tmpl(tmpl templateIface) Option {
	return optionFunc(func(opts *options) {
		opts.tmpl = tmpl
	})
}
495812
func (m *Manager) BuildTCP(rootCtx context.Context, serviceName string) (tcp.Handler, error) {
	ctx := log.With(rootCtx, log.Str(log.ServiceName, serviceName))

	serviceName = internal.GetQualifiedName(ctx, serviceName)
	ctx = internal.AddProviderInContext(ctx, serviceName)

	if conf, ok := m.configs[serviceName]; ok {
		// FIXME Check if the service is declared multiple times with different types
		if conf.LoadBalancer != nil {
			loadBalancer := tcp.NewRRLoadBalancer()

			var handler tcp.Handler
			for _, server := range conf.LoadBalancer.Servers {
				_, err := parseIP(server.Address)
				if err == nil {
					handler, _ = tcp.NewProxy(server.Address)
					loadBalancer.AddServer(handler)
				} else {
					log.FromContext(ctx).Errorf("Invalid IP address for a %s server %s: %v", serviceName, server.Address, err)
				}
			}
			return loadBalancer, nil
		}
		return nil, fmt.Errorf("the service %q doesn't have any TCP load balancer", serviceName)
	}
	return nil, fmt.Errorf("the service %q does not exits", serviceName)
}
47785
func NewTCPProxy(frontendAddr, backendAddr *net.TCPAddr) (*TCPProxy, error) {
	listener, err := net.ListenTCP("tcp", frontendAddr)
	if err != nil {
		return nil, err
	}
	// If the port in frontendAddr was 0 then ListenTCP will have a picked
	// a port to listen on, hence the call to Addr to get that actual port:
	return &TCPProxy{
		listener:     listener,
		frontendAddr: listener.Addr().(*net.TCPAddr),
		backendAddr:  backendAddr,
	}, nil
}
318724
func (d *Datapath) processNetworkTCPPacket(tcpPacket *packet.Packet, context *pucontext.PUContext, conn *connection.TCPConnection) (action interface{}, claims *tokens.ConnectionClaims, err error) {

	if conn == nil {
		return nil, nil, nil
	}

	// Update connection state in the internal state machine tracker
	switch tcpPacket.GetTCPFlags() & packet.TCPSynAckMask {

	case packet.TCPSynMask:
		return d.processNetworkSynPacket(context, conn, tcpPacket)

	case packet.TCPAckMask:
		return d.processNetworkAckPacket(context, conn, tcpPacket)

	case packet.TCPSynAckMask:
		return d.processNetworkSynAckPacket(context, conn, tcpPacket)

	default: // Ignore any other packet
		return nil, nil, nil
	}
}
1232959
func (c *Config) InitHTTPClient() {
	var emptySettings HTTPClientSettings

	if c.HTTPSettings == emptySettings { // User forgot to initialize the settings
		c.HTTPSettings = DefaultHTTPClientSettings
	} else {
		if c.HTTPSettings.ConnectTimeout == 0 {
			c.HTTPSettings.ConnectTimeout = DefaultHTTPClientSettings.ConnectTimeout
		}
		// If ReadTimeout and WriteTimeout is zero, means no read/write timeout
		if c.HTTPSettings.TLSHandshakeTimeout == 0 {
			c.HTTPSettings.TLSHandshakeTimeout = DefaultHTTPClientSettings.TLSHandshakeTimeout
		}
		if c.HTTPSettings.ExpectContinueTimeout == 0 {
			c.HTTPSettings.ExpectContinueTimeout = DefaultHTTPClientSettings.ExpectContinueTimeout
		}
	}
	dialer := utils.NewDialer(
		c.HTTPSettings.ConnectTimeout,
		c.HTTPSettings.ReadTimeout,
		c.HTTPSettings.WriteTimeout,
	)
	dialer.KeepAlive = c.HTTPSettings.TCPKeepAlive
	// XXX: DualStack enables RFC 6555-compliant "Happy Eyeballs" dialing
	// when the network is "tcp" and the destination is a host name
	// with both IPv4 and IPv6 addresses. This allows a client to
	// tolerate networks where one address family is silently broken
	dialer.DualStack = c.HTTPSettings.DualStack
	c.Connection = &http.Client{
		// We do not use the timeout in http client,
		// because this timeout is for the whole http body read/write,
		// it's unsuitable for various length of files and network condition.
		// We provide a wraper in utils/conn.go of net.Dialer to make io timeout to the http connection
		// for individual buffer I/O operation,
		Timeout: 0,
		Transport: &http.Transport{
			DialContext:           dialer.DialContext,
			MaxIdleConns:          c.HTTPSettings.MaxIdleConns,
			MaxIdleConnsPerHost:   c.HTTPSettings.MaxIdleConnsPerHost,
			IdleConnTimeout:       c.HTTPSettings.IdleConnTimeout,
			TLSHandshakeTimeout:   c.HTTPSettings.TLSHandshakeTimeout,
			ExpectContinueTimeout: c.HTTPSettings.ExpectContinueTimeout,
		},
	}
}
306521
func PackTCPAddress(ip string, port uint16) ([]byte, error) {
	var result bytes.Buffer

	// Pack the port to 2 bytes
	portBuf := make([]byte, 2)
	endian.PutUint16(portBuf, port)
	result.Write(portBuf)

	// Pack the ip address to 4 bytes
	ipaddr := net.ParseIP(ip)
	if ipaddr == nil {
		return nil, ErrInvalidTCPAddress
	}
	ipbytes := ipaddr.To4()
	result.Write(ipbytes)

	return result.Bytes(), nil
}
170531
func (d *Datapath) processApplicationAckPacket(tcpPacket *packet.Packet, context *pucontext.PUContext, conn *connection.TCPConnection) error {

	// Only process the first Ack of a connection. This means that we have received
	// as SynAck packet and we can now process the ACK.
	if conn.GetState() == connection.TCPSynAckReceived && tcpPacket.IsEmptyTCPPayload() {
		// Create a new token that includes the source and destinatio nonse
		// These are both challenges signed by the secret key and random for every
		// connection minimizing the chances of a replay attack
		token, err := d.tokenAccessor.CreateAckPacketToken(context, &conn.Auth)
		if err != nil {
			return err
		}

		tcpOptions := d.createTCPAuthenticationOption([]byte{})

		// Attach the tags to the packet
		if err := tcpPacket.TCPDataAttach(tcpOptions, token); err != nil {
			return err
		}

		conn.SetState(connection.TCPAckSend)

		// If its not a service connection, we release it to the kernel. Subsequent
		// packets after the first data packet, that might be already in the queue
		// will be transmitted through the kernel directly. Service connections are
		// delegated to the service module
		if !conn.ServiceConnection && tcpPacket.SourceAddress().String() != tcpPacket.DestinationAddress().String() &&
			!(tcpPacket.SourceAddress().IsLoopback() && tcpPacket.DestinationAddress().IsLoopback()) {
			if err := d.conntrack.UpdateApplicationFlowMark(
				tcpPacket.SourceAddress(),
				tcpPacket.DestinationAddress(),
				tcpPacket.IPProto(),
				tcpPacket.SourcePort(),
				tcpPacket.DestPort(),
				constants.DefaultConnMark,
			); err != nil {
				zap.L().Error("Failed to update conntrack table for flow after ack packet",
					zap.String("context", string(conn.Auth.LocalContext)),
					zap.String("app-conn", tcpPacket.L4ReverseFlowHash()),
					zap.String("state", fmt.Sprintf("%d", conn.GetState())),
					zap.Error(err),
				)
			}
		}

		return nil
	}

	// If we are already in the connection.TCPData connection just forward the packet
	if conn.GetState() == connection.TCPData {
		return nil
	}

	if conn.GetState() == connection.UnknownState {
		// Check if the destination is in the external services approved cache
		// and if yes, allow the packet to go and release the flow.
		_, policy, perr := context.ApplicationACLPolicyFromAddr(tcpPacket.DestinationAddress(), tcpPacket.DestPort())

		if perr != nil {
			// If it is an SSH PU, we let the connection go through
			// It means it is a new SSH Session connection, we mark
			// the packet and let it go through.
			if context.Type() == common.SSHSessionPU {
				if err := d.conntrack.UpdateApplicationFlowMark(
					tcpPacket.SourceAddress(),
					tcpPacket.DestinationAddress(),
					tcpPacket.IPProto(),
					tcpPacket.SourcePort(),
					tcpPacket.DestPort(),
					constants.DefaultConnMark,
				); err != nil {
					zap.L().Error("Failed to update conntrack entry for flow at Ack packet",
						zap.String("context", string(conn.Auth.LocalContext)),
						zap.String("app-conn", tcpPacket.L4ReverseFlowHash()),
						zap.String("state", fmt.Sprintf("%d", conn.GetState())),
						zap.Error(err),
					)
				}
				return nil
			}
			// Convert Ack to FinAck for all other pus
			return tcpPacket.ConvertAcktoFinAck()
		}

		if policy.Action.Rejected() {
			return errors.New("Reject the packet")
		}

		if err := d.conntrack.UpdateApplicationFlowMark(
			tcpPacket.SourceAddress(),
			tcpPacket.DestinationAddress(),
			tcpPacket.IPProto(),
			tcpPacket.SourcePort(),
			tcpPacket.DestPort(),
			constants.DefaultConnMark,
		); err != nil {
			zap.L().Error("Failed to update conntrack entry for flow at Ack packet",
				zap.String("context", string(conn.Auth.LocalContext)),
				zap.String("app-conn", tcpPacket.L4ReverseFlowHash()),
				zap.String("state", fmt.Sprintf("%d", conn.GetState())),
				zap.Error(err),
			)
		}
		return nil
	}

	// Here we capture the first data packet after an ACK packet by modyfing the
	// state. We will not release the caches though to deal with re-transmissions.
	// We will let the caches expire.
	if conn.GetState() == connection.TCPAckSend {
		conn.SetState(connection.TCPData)
		return nil
	}

	return fmt.Errorf("received application ack packet in the wrong state: %d", conn.GetState())
}
928415
func (p *PacketFlow) GetNthPacket(index int) PacketManipulator {

	for i := 0; i < len(p.flow); i++ {
		if index == i {
			return p.flow[i]
		}
	}

	panic("Index out of range")
}
33161
func (d *Datapath) processApplicationSynAckPacket(tcpPacket *packet.Packet, context *pucontext.PUContext, conn *connection.TCPConnection) error {

	// if the traffic belongs to the same pu, let it go
	if conn.GetState() == connection.TCPData && conn.IsLoopbackConnection() {
		return nil
	}

	// If we are already in the connection.TCPData, it means that this is an external flow
	// At this point we can release the flow to the kernel by updating conntrack
	// We can also clean up the state since we are not going to see any more
	// packets from this connection.
	if conn.GetState() == connection.TCPData && !conn.ServiceConnection {
		if err := d.conntrack.UpdateApplicationFlowMark(
			tcpPacket.SourceAddress(),
			tcpPacket.DestinationAddress(),
			tcpPacket.IPProto(),
			tcpPacket.SourcePort(),
			tcpPacket.DestPort(),
			constants.DefaultConnMark,
		); err != nil {
			zap.L().Error("Failed to update conntrack entry for flow at SynAck packet",
				zap.String("context", string(conn.Auth.LocalContext)),
				zap.String("app-conn", tcpPacket.L4ReverseFlowHash()),
				zap.String("state", fmt.Sprintf("%d", conn.GetState())),
				zap.Error(err),
			)
		}

		err1 := d.netOrigConnectionTracker.Remove(tcpPacket.L4ReverseFlowHash())
		err2 := d.appReplyConnectionTracker.Remove(tcpPacket.L4FlowHash())

		if err1 != nil || err2 != nil {
			zap.L().Debug("Failed to remove cache entries")
		}

		return nil
	}

	// We now process packets that need authorization options

	// Create TCP Option
	tcpOptions := d.createTCPAuthenticationOption([]byte{})

	claimsHeader := claimsheader.NewClaimsHeader(
		claimsheader.OptionEncrypt(conn.PacketFlowPolicy.Action.Encrypted()),
	)

	tcpData, err := d.tokenAccessor.CreateSynAckPacketToken(context, &conn.Auth, claimsHeader)

	if err != nil {
		return err
	}

	// Set the state for future reference
	conn.SetState(connection.TCPSynAckSend)

	// Attach the tags to the packet
	return tcpPacket.TCPDataAttach(tcpOptions, tcpData)
}
914877
func generateRPCKeyPair(writeKey bool) (tls.Certificate, error) {
	log.Infof("Generating TLS certificates...")

	// Create directories for cert and key files if they do not yet exist.
	certDir, _ := filepath.Split(cfg.RPCCert.Value)
	keyDir, _ := filepath.Split(cfg.RPCKey.Value)
	err := os.MkdirAll(certDir, 0700)
	if err != nil {
		return tls.Certificate{}, err
	}
	err = os.MkdirAll(keyDir, 0700)
	if err != nil {
		return tls.Certificate{}, err
	}

	// Generate cert pair.
	org := "btcwallet autogenerated cert"
	validUntil := time.Now().Add(time.Hour * 24 * 365 * 10)
	cert, key, err := btcutil.NewTLSCertPair(org, validUntil, nil)
	if err != nil {
		return tls.Certificate{}, err
	}
	keyPair, err := tls.X509KeyPair(cert, key)
	if err != nil {
		return tls.Certificate{}, err
	}

	// Write cert and (potentially) the key files.
	err = ioutil.WriteFile(cfg.RPCCert.Value, cert, 0600)
	if err != nil {
		return tls.Certificate{}, err
	}
	if writeKey {
		err = ioutil.WriteFile(cfg.RPCKey.Value, key, 0600)
		if err != nil {
			rmErr := os.Remove(cfg.RPCCert.Value)
			if rmErr != nil {
				log.Warnf("Cannot remove written certificates: %v",
					rmErr)
			}
			return tls.Certificate{}, err
		}
	}

	log.Info("Done generating TLS certificates")
	return keyPair, nil
}
562817
func NewTcpTransport(conn net.Conn) *TcpTransport {
	t := &TcpTransport{
		conn:         conn,
		requestQueue: make(chan request),
	}
	go t.runRequestQueue()
	return t
}
216909
func (d *Datapath) processApplicationPacketsFromNFQ(p *nfqueue.NFPacket) {

	// Being liberal on what we transmit - malformed TCP packets are let go
	// We are strict on what we accept on the other side, but we don't block
	// lots of things at the ingress to the network
	appPacket, err := packet.New(packet.PacketTypeApplication, p.Buffer, strconv.Itoa(p.Mark), true)

	var processError error
	var tcpConn *connection.TCPConnection
	var udpConn *connection.UDPConnection
	if err != nil {
		appPacket.Print(packet.PacketFailureCreate)
	} else if appPacket.IPProto() == packet.IPProtocolTCP {
		tcpConn, processError = d.processApplicationTCPPackets(appPacket)
	} else if appPacket.IPProto() == packet.IPProtocolUDP {
		udpConn, processError = d.ProcessApplicationUDPPacket(appPacket)
	} else {
		processError = fmt.Errorf("invalid ip protocol: %d", appPacket.IPProto())
	}
	if processError != nil {
		length := uint32(len(p.Buffer))
		buffer := p.Buffer
		p.QueueHandle.SetVerdict2(uint32(p.QueueHandle.QueueNum), 0, uint32(p.Mark), length, uint32(p.ID), buffer)
		if appPacket.IPProto() == packet.IPProtocolTCP {

			d.collectTCPPacket(&debugpacketmessage{
				Mark:    p.Mark,
				p:       appPacket,
				tcpConn: tcpConn,
				udpConn: nil,
				err:     processError,
				network: false,
			})
		} else if appPacket.IPProto() == packet.IPProtocolUDP {
			d.collectUDPPacket(&debugpacketmessage{
				Mark:    p.Mark,
				p:       appPacket,
				tcpConn: nil,
				udpConn: udpConn,
				err:     processError,
				network: false,
			})
		}
		return
	}

	if appPacket.IPProto() == packet.IPProtocolTCP {
		// Accept the packet
		buffer := make([]byte, appPacket.IPTotalLen())
		copyIndex := copy(buffer, appPacket.GetBuffer(0))
		copyIndex += copy(buffer[copyIndex:], appPacket.GetTCPOptions())
		copyIndex += copy(buffer[copyIndex:], appPacket.GetTCPData())

		p.QueueHandle.SetVerdict2(uint32(p.QueueHandle.QueueNum), 1, uint32(p.Mark), uint32(copyIndex), uint32(p.ID), buffer)

	} else {
		p.QueueHandle.SetVerdict2(uint32(p.QueueHandle.QueueNum), 1, uint32(p.Mark), uint32(len(appPacket.GetBuffer(0))), uint32(p.ID), appPacket.GetBuffer(0))
	}
	if appPacket.IPProto() == packet.IPProtocolTCP {
		d.collectTCPPacket(&debugpacketmessage{
			Mark:    p.Mark,
			p:       appPacket,
			tcpConn: tcpConn,
			udpConn: nil,
			err:     nil,
			network: false,
		})
	} else if appPacket.IPProto() == packet.IPProtocolUDP {
		d.collectUDPPacket(&debugpacketmessage{
			Mark:    p.Mark,
			p:       appPacket,
			tcpConn: nil,
			udpConn: udpConn,
			err:     nil,
			network: false,
		})
	}

}
529940
func (client *Client) CreateLoadBalancerTCPListener(args *CreateLoadBalancerTCPListenerArgs) (err error) {
	response := &CommonLoadBalancerListenerResponse{}
	err = client.Invoke("CreateLoadBalancerTCPListener", args, response)
	return err
}
965256
func generateCPU(p domainParams) *CPU {
	if p.Arch() == arch.ARM64 {
		return &CPU{
			Mode:  "custom",
			Match: "exact",
			Model: Model{
				Fallback: "allow",
				Text:     "cortex-a53"},
		}
	}
	return nil
}