netcat

package
v0.15.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 18, 2025 License: BSD-3-Clause Imports: 18 Imported by: 0

Documentation

Overview

Copyright 2024 the u-root Authors. All rights reserved Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

Copyright 2024 the u-root Authors. All rights reserved Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

Index

Constants

View Source
const (
	DEFAULT_PORT            = 31337
	DEFAULT_SOURCE_PORT     = "31337"
	DEFAULT_IP_TYPE         = IP_V4_V6
	DEFAULT_CONNECTION_MODE = CONNECTION_MODE_CONNECT
	DEFAULT_CONNECTION_MAX  = 100
	DEFAULT_SHELL           = "/bin/sh"
	DEFAULT_UNIX_SOCKET     = "/tmp/netcat.sock"
	DEFAULT_IPV4_ADDRESS    = "0.0.0.0"
	DEFAULT_IPV6_ADDRESS    = "::"
	DEFAULT_WAIT            = time.Duration(10) * time.Second
)

Default values for the netcat command. These values were taken from the original netcat project.

Variables

View Source
var (
	DEFAULT_LF            = LINE_FEED_LF
	DEFAULT_SSL_SUITE_STR = []string{"ALL", "!aNULL", "!eNULL", "!LOW", "!EXP", "!RC4", "!MD5", "@STRENGTH"}
	LINE_FEED_LF          = []byte{0xa}        // \n
	LINE_FEED_CRLF        = []byte{0x0d, 0x0a} // \r\n
)

Functions

func CloseWrite

func CloseWrite(writerToClose io.Writer) error

CloseWrite is a convenience wrapper that calls CloseWrite on an io.Writer that is a TLS connection, a TCP connection, or a UNIX domain connection.

func SplitVSockAddr

func SplitVSockAddr(addr string) (uint32, uint32, error)

Types

type AccessControlOptions

type AccessControlOptions struct {
	SetAllowed     bool
	ConnectionList map[string]bool
}

Holds allowed and denied hosts for the connection. The map is a string representation of the host is allowed or denied. The key is the host and the value is true for allowed and false for denied. If the host is not in the map, it is allowed by default. The map is populated by the access cli flags, with access flags taking precedence over deny flags.

func ParseAccessControl

func ParseAccessControl(connectionAllowFile string, connectionAllowList []string, connectionDenyFile string, connectionDenyList []string) (AccessControlOptions, error)

func (*AccessControlOptions) IsAllowed

func (ac *AccessControlOptions) IsAllowed(hostNames []string) bool

Check if the hostName is allowed to connect.

type ConcurrentWriteCloser

type ConcurrentWriteCloser struct {
	ConcurrentWriter
}

func NewConcurrentWriteCloser

func NewConcurrentWriteCloser(wc io.WriteCloser) *ConcurrentWriteCloser

func (*ConcurrentWriteCloser) Close

func (swc *ConcurrentWriteCloser) Close() error

type ConcurrentWriter

type ConcurrentWriter struct {
	// contains filtered or unexported fields
}

ConcurrentWriter wraps an io.Writer with a mutex to ensure safe concurrent writes.

func NewConcurrentWriter

func NewConcurrentWriter(w io.Writer) *ConcurrentWriter

NewConcurrentWriter creates a new ConcurrentWriter.

func (*ConcurrentWriter) Write

func (sw *ConcurrentWriter) Write(p []byte) (n int, err error)

Write writes data to the underlying io.Writer, locking the writer during the operation.

type Config

type Config struct {
	Host                  string
	Port                  uint64
	ConnectionMode        ConnectionMode
	ConnectionModeOptions ConnectModeOptions
	ListenModeOptions     ListenModeOptions
	ProtocolOptions       ProtocolOptions
	SSLConfig             SSLOptions
	ProxyConfig           ProxyOptions
	AccessControl         AccessControlOptions
	CommandExec           Exec
	Output                OutputOptions
	Misc                  MiscOptions
	Timing                TimingOptions
}

Omit version and help here since they are handled by the flag parser

func DefaultConfig

func DefaultConfig() Config

Default values for the netcat command.

func (*Config) Address

func (c *Config) Address() (string, error)

Return a default address for the provided configuration

type ConnectModeOptions

type ConnectModeOptions struct {
	ScanPorts               bool
	CurrentPort             uint64
	EndPort                 uint64
	LooseSourceRouterPoints []string // IPV4_STRICT, Point as IP or Hostname
	LooseSourcePointer      uint     // The argument must be a multiple of 4 and no more than 28
	SourceHost              string   // Address for Ncat to bind to
	SourcePort              string   // Port number for Ncat to bind to
	ZeroIO                  bool     // restrict IO, only report connection
}

Since Ncat can be either in connect mode or in listen mode, only one of these options structs should be filled at a time. TODO: Make this a generic ConnectionModeOptions struct that may have different fields

type ConnectionMode

type ConnectionMode int
const (
	CONNECTION_MODE_CONNECT ConnectionMode = iota
	CONNECTION_MODE_LISTEN
)

Ncat operates in one of two primary modes: connect mode and listen mode.

func (ConnectionMode) String

func (c ConnectionMode) String() string

type EOLReader

type EOLReader struct {
	// contains filtered or unexported fields
}

EOLReader is a reader that reads until the end of line and appends the EOL sequence.

func NewEOLReader

func NewEOLReader(reader io.Reader, eol []byte) *EOLReader

func (*EOLReader) Read

func (cr *EOLReader) Read(p []byte) (n int, err error)

type Exec

type Exec struct {
	Type    ExecType
	Command string
}

func ParseCommands

func ParseCommands(execs ...Exec) (Exec, error)

func (*Exec) Execute

func (n *Exec) Execute(stdout io.Writer, stderr io.Writer, eol []byte) error

Execute a given command on the host system stdout of the command is send to to the connection stderr of the command is displayed on stdout of the host The host process exits with the exit code of the command unless --keep-open is specified

type ExecType

type ExecType int
const (
	EXEC_TYPE_NATIVE ExecType = iota
	EXEC_TYPE_SHELL
	EXEC_TYPE_LUA
	EXEC_TYPE_NONE // For faster case switching this is appended at the end
)

type IPType

type IPType int
const (
	IP_NONE IPType = iota
	IP_V4
	IP_V6
	IP_V4_V6
	IP_V4_STRICT
	IP_V6_STRICT
)

type ListenModeOptions

type ListenModeOptions struct {
	MaxConnections uint32 // Maximum number of simultaneous connections accepted by an Ncat instance
	KeepOpen       bool   // Accept multiple connections. In this mode there is no way for Ncat to know when its network input is finished, so it will keep running until interrupted
	BrokerMode     bool   // Don't echo messages but redirect them to all others. Compatible with other modes
	ChatMode       bool   // Enables chat mode, intended for the exchange of text between several users
}

All the modes can be combined with each other, no need to check for mutual exclusivity

type MiscOptions

type MiscOptions struct {
	EOL         []byte // This can either be a single byte or a sequence of bytes
	ReceiveOnly bool   // Only receive data and will not try to send anything.
	SendOnly    bool   // Ncat will only send data and will ignore anything received
	NoShutdown  bool   // Req: half-duplex mode, Ncat will not invoke shutdown on a socket after seeing EOF on stdin
	NoDNS       bool   // Completely disable hostname resolution across all Ncat options (destination, source address, source routing hops, proxy)
	Telnet      bool   // Handle DO/DONT WILL/WONT Telnet negotiations.
}

type OutputOptions

type OutputOptions struct {
	OutFilePath     string      // Dump session data to a file
	OutFileMutex    sync.Mutex  // Mutex for the file
	OutFileHexPath  string      // Dump session data in hex to a file
	OutFileHexMutex sync.Mutex  // Mutex for the hex file
	AppendOutput    bool        // Append the resulted output rather than truncating
	Logger          ulog.Logger // Verbose output
}

func (*OutputOptions) Close

func (n *OutputOptions) Close() error

Close does nothing: Write already closes any underlying files. Close exists only to implement the io.WriteCloser interface with OutputOptions.

func (*OutputOptions) Write

func (n *OutputOptions) Write(data []byte) (int, error)

Write writes the data to the file specified in the options If Netcat is not configured to write to a file, it will return 0, nil https://go.dev/src/io/io.go

type ProtocolOptions

type ProtocolOptions struct {
	IPType     IPType
	SocketType SocketType
}

func (*ProtocolOptions) Network

func (p *ProtocolOptions) Network() (string, error)

type ProxyDNSType

type ProxyDNSType int
const (
	PROXY_DNS_NONE ProxyDNSType = iota
	PROXY_DNS_LOCAL
	PROXY_DNS_REMOTE
	PROXY_DNS_BOTH
)

func ProxyDNSTypeFromString

func ProxyDNSTypeFromString(s string) ProxyDNSType

type ProxyOptions

type ProxyOptions struct {
	Enabled bool
	Type    ProxyType
	Address string // if address is empty, discard the entire proxy handling
	Auth    string
	DNSType ProxyDNSType
}

type ProxyType

type ProxyType int
const (
	PROXY_TYPE_NONE ProxyType = iota
	PROXY_TYPE_HTTP
	PROXY_TYPE_SOCKS4
	PROXY_TYPE_SOCKS5
	DEFAULT_PROXY_TYPE = PROXY_TYPE_NONE
)

func ProxyTypeFromString

func ProxyTypeFromString(s string) ProxyType

func (ProxyType) DefaultPort

func (p ProxyType) DefaultPort() (uint, error)

func (ProxyType) String

func (p ProxyType) String() string

type SSLOptions

type SSLOptions struct {
	// In connect mode, this option transparently negotiates an SSL session
	// In server mode, this option listens for incoming SSL connections
	// Depending on the Protocol Type, either TLS (TCP) od DTLS (UDP) will be used
	Enabled bool

	CertFilePath  string // Path to the certificate file in PEM format
	KeyFilePath   string // Path to the private key file in PEM format
	VerifyTrust   bool   // In client mode is like --ssl except that it also requires verification of the server certificate. No effect in server mode.
	TrustFilePath string // Verify trust and domain name of certificates

	// List of ciphersuites that Ncat will use when connecting to servers or when accepting SSL connections from clients
	// Syntax is described in the OpenSSL ciphers(1) man page
	Ciphers []string
	SNI     string   // (Server Name Indication) Tell the server the name of the logical server Ncat is contacting
	ALPN    []string // List of protocols to send via the Application-Layer Protocol Negotiation
}

func (*SSLOptions) GenerateTLSConfiguration

func (s *SSLOptions) GenerateTLSConfiguration(listen bool) (*tls.Config, error)

type SocketType

type SocketType int
const (
	SOCKET_TYPE_TCP SocketType = iota
	SOCKET_TYPE_UDP
	SOCKET_TYPE_UNIX
	SOCKET_TYPE_VSOCK
	SOCKET_TYPE_SCTP
	SOCKET_TYPE_UDP_VSOCK
	SOCKET_TYPE_UDP_UNIX
	SOCKET_TYPE_NONE
)

UDP can be combined with one of {UNIX, VSOCK} or stand alone

func ParseSocketType

func ParseSocketType(udp, unix, vsock, sctp bool) (SocketType, error)

func (SocketType) String

func (s SocketType) String() string

type StdoutWriteCloser

type StdoutWriteCloser struct{}

StdoutWriteCloser wraps os.Stdout such that it satisfy the io.WriteCloser interface, *but* with a special Close. Per POSIX, fd#1 should always remain open:

https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#tag_19_09_01_05 https://pubs.opengroup.org/onlinepubs/9799919799/functions/exec.html#tag_17_129_03 https://pubs.opengroup.org/onlinepubs/9799919799/functions/close.html#tag_17_81_07

Thus, we can't close os.Stdout, even temporarily.

What we actually need to do is decrement the reference count on the file description that underlies file descriptor #1, without closing file descriptor #1. That's only doable with dup2(). Therefore, duplicate "/dev/null" over fd#1.

On any GOOS that does not conform to POSIX (by certificate or by intent), StdoutWriteCloser.Close() is a no-op, as the well-known file handles shouldn't be closed in any case. (See e.g. <https://pkg.go.dev/os#Stderr>.)

func (*StdoutWriteCloser) Close

func (swc *StdoutWriteCloser) Close() error

Close implements io.WriteCloser.Close.

func (*StdoutWriteCloser) Write

func (swc *StdoutWriteCloser) Write(b []byte) (n int, err error)

Write implements io.WriteCloser.Write.

type TeeWriteCloser

type TeeWriteCloser struct {
	// contains filtered or unexported fields
}

TeeWriteCloser is a simplistic crossing between io.MultiWriter and io.WriteCloser.

func NewTeeWriteCloser

func NewTeeWriteCloser(wc1 io.WriteCloser, wc2 io.WriteCloser) *TeeWriteCloser

func (*TeeWriteCloser) Close

func (twc *TeeWriteCloser) Close() error

Close closes both io.WriteCloser objects in all cases, and returns the first error (if any).

func (*TeeWriteCloser) Write

func (twc *TeeWriteCloser) Write(b []byte) (n int, err error)

Write doesn't continue past the first write error, similarly to io.MultiWriter's Write.

type TimingOptions

type TimingOptions struct {
	Delay   time.Duration // Delay interval for lines sent
	Timeout time.Duration // If the idle timeout is reached, the connection is terminated.
	Wait    time.Duration // Fixed timeout for connection attempts.
}

type UDPListener

type UDPListener struct {
	// contains filtered or unexported fields
}

UDPListener implements net.UDPListener for UDP

func NewUDPListener

func NewUDPListener(network, addr string, _ ulog.Logger) (*UDPListener, error)

NewUDPListener creates a new UDPListener

func (*UDPListener) Accept

func (l *UDPListener) Accept() (net.Conn, error)

Accept waits for and returns the next connection to the listener.

func (*UDPListener) Addr

func (l *UDPListener) Addr() net.Addr

func (*UDPListener) Close

func (l *UDPListener) Close() error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL