Documentation
¶
Overview ¶
Package hashcat provides utilities for interacting with hashcat.
Package hashcat provides utilities for interacting with hashcat.
Package hashcat provides parameter validation and command-line argument generation for hashcat operations. It handles configuration for various attack modes including dictionary, mask, and hybrid attacks, with comprehensive validation and error handling.
Package hashcat provides session management and execution control for hashcat processes. It handles process lifecycle, I/O management, and result collection for hash cracking operations in a distributed agent environment.
Package hashcat provides types and constants for hashcat session management. It defines the data structures used to communicate with hashcat processes and track the status of hash cracking operations.
Index ¶
- Constants
- Variables
- func CleanupOrphanedSessionFiles(binaryPath string)
- func IsExhausted(exitCode int) bool
- func IsNormalCompletion(exitCode int) bool
- func IsSuccess(exitCode int) bool
- type ErrorCategory
- type ErrorInfo
- type ExitCodeInfo
- type Params
- type Result
- type Session
- type Status
- type StatusDevice
Constants ¶
const ( // ExitCodeSuccess indicates at least one hash was cracked. ExitCodeSuccess = 0 // RC_FINAL_OK // ExitCodeExhausted indicates the keyspace was fully exhausted. ExitCodeExhausted = 1 // RC_FINAL_EXHAUSTED // ExitCodeAborted indicates the session was aborted by the user. ExitCodeAborted = 2 // RC_FINAL_ABORT // ExitCodeCheckpoint indicates the session was aborted at a checkpoint. ExitCodeCheckpoint = 3 // RC_FINAL_ABORT_CHECKPOINT // ExitCodeRuntimeLimit indicates the session hit the runtime limit. ExitCodeRuntimeLimit = 4 // RC_FINAL_ABORT_RUNTIME // ExitCodeAbortFinish indicates the session was aborted after the finish flag was set. ExitCodeAbortFinish = 5 // RC_FINAL_ABORT_FINISH // ExitCodeGeneralError indicates a general error (STATUS_ERROR). ExitCodeGeneralError = -1 // shell: 255 // ExitCodeRuntimeSkip indicates all backend devices were skipped at runtime. ExitCodeRuntimeSkip = -3 // shell: 253 // ExitCodeMemoryHit indicates insufficient device memory. ExitCodeMemoryHit = -4 // shell: 252 // ExitCodeKernelBuild indicates kernel compilation failed. ExitCodeKernelBuild = -5 // shell: 251 // ExitCodeKernelCreate indicates kernel creation failed. ExitCodeKernelCreate = -6 // shell: 250 // ExitCodeKernelAccel indicates autotune failed on all devices. ExitCodeKernelAccel = -7 // shell: 249 // ExitCodeExtraSize indicates an extra_size backend issue. ExitCodeExtraSize = -8 // shell: 248 // ExitCodeMixedWarnings indicates multiple backend issues. ExitCodeMixedWarnings = -9 // shell: 247 // ExitCodeSelftestFail indicates the kernel self-test failed. ExitCodeSelftestFail = -11 // shell: 245 )
Hashcat exit codes from types.h (hashcat 7.x). Positive codes are RC_FINAL_* (official), negative codes map to shell values 245-255 via unsigned conversion.
const ( // AttackModeMask is the attack mode for mask attacks. AttackModeMask = 3 // AttackBenchmark is the attack mode for benchmarking. AttackBenchmark = 9 // AttackHashInfo is the attack mode for capability detection via --hash-info --machine-readable. // This value is an internal sentinel used only by the agent's toCmdArgs dispatch. AttackHashInfo = 10 // AttackBenchmarkSingle is the attack mode for benchmarking a single hash type // via --benchmark -m <type>. This is an internal sentinel for background benchmarking. AttackBenchmarkSingle = 11 )
Attack mode constants define the different types of hashcat attacks.
Variables ¶
var ( // ErrUnsupportedAttackMode indicates an invalid or unsupported attack mode was specified. ErrUnsupportedAttackMode = errors.New("unsupported attack mode") // ErrDictionaryAttackWordlist indicates a dictionary attack is missing its required wordlist. ErrDictionaryAttackWordlist = errors.New("expected 1 wordlist for dictionary attack, but none given") // ErrMaskAttackNoMask indicates a mask attack is missing both mask and mask list. ErrMaskAttackNoMask = errors.New("using mask attack, but no mask was given") // ErrMaskAttackBothMaskAndList indicates both mask and mask list were provided (mutually exclusive). ErrMaskAttackBothMaskAndList = errors.New("using mask attack, but both mask and mask list were given") // ErrHybridAttackNoMask indicates a hybrid attack is missing its required mask. ErrHybridAttackNoMask = errors.New("using hybrid attack, but no mask was given") // ErrHybridAttackNoWordlist indicates a hybrid attack is missing its required wordlist. ErrHybridAttackNoWordlist = errors.New("expected 1 wordlist for hybrid attack, but none given") // ErrTooManyCustomCharsets indicates more custom charsets were provided than supported. ErrTooManyCustomCharsets = errors.New("too many custom charsets supplied") // ErrWordlistNotOpened indicates the specified wordlist file cannot be accessed. ErrWordlistNotOpened = errors.New("provided word list couldn't be opened on filesystem") // ErrRuleListNotOpened indicates the specified rule list file cannot be accessed. ErrRuleListNotOpened = errors.New("provided rule list couldn't be opened on filesystem") // ErrMaskListNotOpened indicates the specified mask list file cannot be accessed. ErrMaskListNotOpened = errors.New("provided mask list couldn't be opened on filesystem") // ErrHashFileNotReadable indicates the hash file is missing or inaccessible. ErrHashFileNotReadable = errors.New("hash file couldn't be opened on filesystem") // ErrHashFileEmpty indicates the hash file exists but contains zero bytes. ErrHashFileEmpty = errors.New("hash file is empty") // ErrHashFileWhitespaceOnly indicates the hash file contains only whitespace. ErrHashFileWhitespaceOnly = errors.New("hash file contains only whitespace") )
Functions ¶
func CleanupOrphanedSessionFiles ¶ added in v0.6.2
func CleanupOrphanedSessionFiles(binaryPath string)
CleanupOrphanedSessionFiles removes stale session .log and .pid files from hashcat's session directory. It is safe to call at agent startup — at that point, any leftover attack-* files are orphaned by definition. Errors are logged but never returned; cleanup failure must not prevent agent startup. On Windows, cleanup is skipped because the session directory is the hashcat binary directory, which is too broad for removal.
func IsExhausted ¶ added in v0.6.0
IsExhausted returns true if the exit code indicates hashcat exhausted the keyspace.
func IsNormalCompletion ¶ added in v0.6.0
IsNormalCompletion returns true if the exit code indicates normal completion (either cracked or exhausted).
Types ¶
type ErrorCategory ¶ added in v0.6.0
type ErrorCategory int
ErrorCategory represents the classification of a hashcat error.
const ( // ErrorCategoryUnknown is for unrecognized error patterns. ErrorCategoryUnknown ErrorCategory = iota // ErrorCategorySuccess is for normal completion states (not actual errors). ErrorCategorySuccess // ErrorCategoryInfo is for informational messages (not actual errors). ErrorCategoryInfo // ErrorCategoryWarning is for warnings that don't stop operation. ErrorCategoryWarning // ErrorCategoryRetryable is for transient errors that may succeed on retry. ErrorCategoryRetryable // ErrorCategoryHashFormat is for hash file/format issues (permanent). ErrorCategoryHashFormat // ErrorCategoryFileAccess is for missing/corrupted files (permanent). ErrorCategoryFileAccess // ErrorCategoryDevice is for GPU/hardware errors. ErrorCategoryDevice // ErrorCategoryConfiguration is for invalid parameters. ErrorCategoryConfiguration // ErrorCategoryBackend is for OpenCL/CUDA backend errors. ErrorCategoryBackend )
func (ErrorCategory) String ¶ added in v0.6.0
func (c ErrorCategory) String() string
String returns the string representation of an ErrorCategory.
type ErrorInfo ¶ added in v0.6.0
type ErrorInfo struct {
Category ErrorCategory
Severity api.Severity
Retryable bool
Message string
Context map[string]any
}
ErrorInfo contains information about a classified error line.
func ClassifyStderr ¶ added in v0.6.0
ClassifyStderr classifies a stderr/stdout error line from hashcat and returns error information.
type ExitCodeInfo ¶ added in v0.6.0
type ExitCodeInfo struct {
Category ErrorCategory
Severity api.Severity
Retryable bool
Status string
ExitCode int
Context map[string]any
}
ExitCodeInfo contains information about a hashcat exit code.
func ClassifyExitCode ¶ added in v0.6.0
func ClassifyExitCode(exitCode int) ExitCodeInfo
ClassifyExitCode classifies a hashcat exit code and returns detailed information.
type Params ¶ added in v0.1.2
type Params struct {
AttackMode int64 `json:"attack_mode"` // Attack mode (0=dictionary, 3=mask, 6/7=hybrid, 9=benchmark)
HashType int64 `json:"hash_type"` // Hashcat hash type code
HashFile string `json:"hash_file"` // Path to file containing target hashes
Mask string `json:"mask,omitempty"` // Mask pattern for mask/hybrid attacks
MaskIncrement bool `json:"mask_increment,omitempty"` // Enable mask increment mode
MaskIncrementMin int64 `json:"mask_increment_min"` // Minimum mask length for increment mode
MaskIncrementMax int64 `json:"mask_increment_max"` // Maximum mask length for increment mode
MaskCustomCharsets []string `json:"mask_custom_charsets"` // Custom character sets for mask attacks
WordListFilename string `json:"wordlist_filename"` // Path to wordlist file
RuleListFilename string `json:"rules_filename"` // Path to rules file for dictionary attacks
MaskListFilename string `json:"mask_list_filename"` // Path to mask list file
AdditionalArgs []string `json:"additional_args"` // Extra command-line arguments
OptimizedKernels bool `json:"optimized_kernels"` // Use optimized kernels (-O flag)
SlowCandidates bool `json:"slow_candidates"` // Enable slow candidate generators (-S flag)
Skip int64 `json:"skip,omitempty"` // Skip N candidates from start
Limit int64 `json:"limit,omitempty"` // Stop after processing N candidates
BackendDevices string `json:"backend_devices,omitempty"` // Backend devices to use (pre-resolved by DeviceConfig)
OpenCLDevices string `json:"opencl_devices,omitempty"` // OpenCL device types (pre-resolved by DeviceConfig)
EnableAdditionalHashTypes bool `json:"enable_additional_hash_types"` // Enable all hash types in benchmark mode
RestoreFilePath string `json:"restore_file_path,omitempty"` // Path to restore file for session resumption
// Runtime configuration injected by the agent at session construction. These are
// NOT part of the server API contract (json:"-"); they replace direct agentstate
// reads in lib/hashcat so sessions are constructable and testable in isolation.
OutPath string `json:"-"` // Directory for the output file and charset temp files
ZapsPath string `json:"-"` // Directory for zaps (--outfile-check-dir); also cleaned up
FilePath string `json:"-"` // Base directory for wordlist/rule/mask files
StatusTimer int `json:"-"` // Status/outfile-check timer in seconds
RetainZapsOnCompletion bool `json:"-"` // Whether Cleanup keeps the zaps directory
}
Params represents the configuration parameters for a hashcat hash cracking attack. It contains all settings needed to configure and execute an attack including attack mode, hash type, input files, optimization flags, and device selection.
type Result ¶ added in v0.1.2
type Result struct {
Timestamp time.Time `json:"timestamp"` // When the hash was cracked
Hash string `json:"hash"` // Original hash value
Plaintext string `json:"plaintext"` // Recovered plaintext password
}
Result represents a successfully cracked hash. It contains the timestamp, original hash, and recovered plaintext.
type Session ¶ added in v0.1.2
type Session struct {
CrackedHashes chan Result // Channel for successfully cracked hashes
StatusUpdates chan Status // Channel for periodic status updates
StderrMessages chan ErrorInfo // Channel for classified error messages from hashcat
StdoutLines chan string // StdoutLines receives non-JSON stdout lines. Never closed; consumers must select on ctx.Done().
DoneChan chan error // Channel signaling process completion
SkipStatusUpdates bool // Flag to disable status update parsing
RestoreFilePath string // Path to session restore file
// contains filtered or unexported fields
}
Session represents a hashcat execution session with comprehensive process management. It manages the hashcat process lifecycle, handles I/O streams, and provides channels for real-time communication of results, status updates, and error messages. The session stores a context.CancelFunc to enable graceful shutdown and cancellation of session operations, allowing controlled termination of goroutines and resource cleanup during lifecycle management.
func NewHashcatSession ¶
NewHashcatSession creates and initializes a new hashcat session. It configures the hashcat command with the provided parameters, creates necessary temporary files, and sets up channels for communication. The parent context controls the session's lifecycle — cancelling it will stop the hashcat process. Returns an error if binary lookup, file creation, or argument validation fails.
func NewTestSession ¶ added in v0.6.2
NewTestSession creates a minimal Session for testing without requiring the hashcat binary. It initializes only the channels needed for test communication. No process, files, or context are set up — the session is not startable. It is exported (rather than in a _test.go file) so that lib/testhelpers can call it across package boundaries without circular imports. The skipStatusUpdates parameter controls whether status update parsing is skipped.
func (*Session) Cancel ¶ added in v0.6.0
func (sess *Session) Cancel()
Cancel requests cancellation of the running hashcat process via the session context. This method is thread-safe and may be called concurrently from multiple goroutines.
func (*Session) Cleanup ¶ added in v0.1.2
func (sess *Session) Cleanup()
Cleanup kills the hashcat process, waits for all I/O goroutines to exit, then removes all session-related temporary files: output file, charset files, hash file, restore file, session log/pid files, and optionally the zaps directory. It is idempotent — already-removed files are silently skipped. Errors are logged but don't halt the cleanup.
func (*Session) CmdLine ¶ added in v0.1.2
CmdLine returns the command line string used to start the hashcat process.
type Status ¶ added in v0.1.2
type Status struct {
OriginalLine string `json:"original_line"` // Raw status line from hashcat
Time time.Time `json:"time"` // Timestamp when status was captured
Session string `json:"session"` // Unique session identifier
Guess statusGuess `json:"guess"` // Current guess/wordlist state
Status int64 `json:"status"` // Hashcat status code
Target string `json:"target"` // Target hash or hash list
Progress []int64 `json:"progress"` // Current and total progress values
RestorePoint int64 `json:"restore_point"` // Position for session restoration
RecoveredHashes []int64 `json:"recovered_hashes"` // Count of cracked hashes
RecoveredSalts []int64 `json:"recovered_salts"` // Count of recovered salts
Rejected int64 `json:"rejected"` // Number of rejected candidates
Devices []StatusDevice `json:"devices"` // Active compute devices
TimeStart int64 `json:"time_start"` // Attack start timestamp (Unix)
EstimatedStop int64 `json:"estimated_stop"` // Estimated completion timestamp (Unix)
}
Status represents the current operational status of a hashcat process. It contains comprehensive information about the attack progress, performance, and estimated completion time.
type StatusDevice ¶ added in v0.1.2
type StatusDevice struct {
DeviceID int64 `json:"device_id"` // Unique device identifier
DeviceName string `json:"device_name"` // Human-readable device name
DeviceType string `json:"device_type"` // Device type (e.g., "GPU", "CPU")
Speed int64 `json:"speed"` // Current processing speed (hashes/second)
Util int64 `json:"util"` // Device utilization percentage (0-100)
Temp int64 `json:"temp"` // Device temperature in Celsius
}
StatusDevice represents a computing device (GPU/CPU) involved in a hash cracking operation. It tracks device identification, performance metrics, and operational status.