imap

package
v0.0.182 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package imap implements the IMAP4rev1/IMAP4rev2 wire protocol primitives shared between the enumerate (Mode A — fingerprint) and pentest (Mode B — authenticated actions) tools.

Index

Constants

View Source
const (
	// DefaultImapPort is the IANA-assigned port for plain-text IMAP.
	DefaultImapPort = 143
	// DefaultImapsPort is the IANA-assigned port for IMAP over implicit TLS (RFC 8314).
	DefaultImapsPort = 993
)

Variables

View Source
var ErrImplicitTLSSuspected = fmt.Errorf("no IMAP greeting on plain socket; implicit TLS suspected")

ErrImplicitTLSSuspected signals that a plain TCP dial succeeded but the listener did not send an IMAP greeting within implicitTLSPeekTimeout. The caller should close the connection and retry with implicit TLS.

View Source
var ErrSTARTTLSRejected = fmt.Errorf("STARTTLS rejected by server")

ErrSTARTTLSRejected signals that the server replied tagged NO/BAD to STARTTLS. The underlying plain IMAP connection is still usable — callers may continue cleartext (subject to their own plaintext policy) rather than teardown the session. Distinct from a TLS handshake failure, which leaves the socket mid-negotiation and unrecoverable. Wrap with %w so callers can use errors.Is.

Functions

func DeadlineFromContext

func DeadlineFromContext(ctx context.Context) time.Time

DeadlineFromContext returns the absolute deadline from ctx. If the context has no deadline, it falls back to a 30 second budget from now. Using the absolute deadline (rather than re-computing now+duration on each call) ensures later commands cannot extend past the per-target timeout budget.

func DoSTARTTLS

func DoSTARTTLS(ctx context.Context, conn net.Conn, host string) (*tls.Conn, error)

DoSTARTTLS upgrades a plain connection to TLS via the IMAP STARTTLS command.

Failure semantics: any non-nil error returned indicates the underlying `conn` is in an undefined state (the server may have started its TLS handshake mid-stream). Callers MUST close `conn` themselves on error — continuing to send cleartext IMAP on it will race the server's TLS expectation and corrupt protocol state. The function closes `conn` itself when the handshake started but failed (rejected STARTTLS command leaves the plain connection usable, so we don't close in that case).

func ImapQuoteString

func ImapQuoteString(s string) string

ImapQuoteString wraps s in an IMAP double-quoted string literal per RFC 3501 §4.3. Backslash and double-quote are escaped; CR/LF are stripped.

func ParseCapabilities

func ParseCapabilities(line string) []string

ParseCapabilities extracts capability tokens from a CAPABILITY response. Handles both "* CAPABILITY ..." and "A001 OK [CAPABILITY ...]" formats.

func ParseFolderStatus

func ParseFolderStatus(line string) *imapfern.ImapFolderStatus

ParseFolderStatus parses a single STATUS response line. STATUS response: * STATUS INBOX (MESSAGES 1234 RECENT 0 UNSEEN 42 UIDNEXT 5678 UIDVALIDITY 1234567890)

func ParseFolders

func ParseFolders(lines []string) []*imapfern.ImapFolder

ParseFolders parses LIST response lines into ImapFolder values. LIST response format: * LIST (\HasNoChildren) "/" "INBOX"

func ParseUIDFetchHeaders

func ParseUIDFetchHeaders(folderName string, lines []string, maxMessages int) []*imapfern.ImapMessageHeaders

ParseUIDFetchHeaders parses UID FETCH response lines into ImapMessageHeaders keyed by UID. Each message is delimited by "* N FETCH ( ... UID ... )".

func SendCommand

func SendCommand(ctx context.Context, conn net.Conn, tag, cmd string) ([]string, error)

SendCommand sends a tagged IMAP command and reads response lines until the tagged completion (OK/NO/BAD). Returns all lines including the final tagged line. Tagged NO/BAD is surfaced as an error so partial output is not mistaken for success.

func StripCRLF

func StripCRLF(s string) string

StripCRLF removes carriage-return and line-feed characters to prevent CRLF injection in IMAP command lines sent via textproto.PrintfLine.

func TryTCPConnection

func TryTCPConnection(ctx context.Context, host string, port int) (net.Conn, string, error)

TryTCPConnection connects via plain TCP and peeks for the untagged IMAP greeting. An implicit-TLS listener never sends a plaintext greeting; if the first byte isn't '*', we fall back to TLS.

func TryTLSConnection

func TryTLSConnection(ctx context.Context, host string, port int) (*tls.Conn, string, error)

TryTLSConnection connects directly via TLS (IMAPS) and reads the greeting.

InsecureSkipVerify is intentional: this is a probe-style dial against pentest targets that routinely present self-signed certs, wrong CN / SAN, expired chains, or are intentionally vulnerable. Failing on cert validation would silently drop those targets from scope, which is the opposite of the tool's purpose. Matches the established repo pattern in internal/enumerate/imap/helpers.go, internal/enumerate/pop3/helpers.go, internal/enumerate/smtp/helpers.go, internal/discover/tls.go, etc.

Types

type Session

type Session struct {
	Conn         net.Conn
	Host         string
	TLSActive    bool
	Capabilities []string
	SASLMechs    []sasl.Mechanism
	// contains filtered or unexported fields
}

Session is a connected, capability-detected IMAP control channel that the per-action helpers reuse for AUTH / LIST_FOLDERS / FETCH_HEADERS / SEARCH.

func NewSession

func NewSession(ctx context.Context, target string) (*Session, error)

NewSession dials target, optionally upgrades via STARTTLS, and runs CAPABILITY so the caller can use s.SASLMechs / s.TLSActive to choose an auth mechanism safely.

func (*Session) Authenticate

func (s *Session) Authenticate(ctx context.Context, username, password, mechanismOverride string, allowPlaintext bool) (sasl.Mechanism, error)

Authenticate runs SASL authentication using the session's negotiated mechanisms. It honors mechanismOverride, the plaintext policy, and returns the mechanism actually used so the caller can surface it in AuthResult.

func (*Session) Close

func (s *Session) Close(ctx context.Context)

Close issues IMAP LOGOUT and closes the underlying connection. Safe to call on nil or a session with no connection.

func (*Session) NextTag

func (s *Session) NextTag() string

NextTag returns the next IMAP command tag (A001, A002, ...) and increments the session's internal counter.

Jump to

Keyboard shortcuts

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