sshconfig

package
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2026 License: GPL-3.0 Imports: 9 Imported by: 0

Documentation

Overview

Package sshconfig provides SSH config file parsing and manipulation.

This package reads and writes OpenSSH config files (~/.ssh/config and included files), supporting host lookup, fuzzy matching, and programmatic modification.

Parsing

The Parser reads SSH config files following OpenSSH conventions:

  • Host blocks with pattern matching
  • Include directives with glob expansion
  • Standard directives (HostName, User, Port, IdentityFile, etc.)

Host Lookup

Use Parser.FindHost for exact matches or Parser.MatchHost for fuzzy matching with suggestions:

parser := sshconfig.NewParser()
host, err := parser.FindHost("myserver")
if err != nil {
    // Handle not found or parse error
}

Modification

The package supports adding, updating, and removing host entries:

parser.AddHost(entry, "servers.conf")  // Add to include file
parser.RemoveHost("oldserver")          // Remove by name
parser.WriteFile(config)                // Save changes

Include Files

nssh organizes hosts into include files (e.g., work.conf, home.conf) that map to credential contexts. The parser tracks which file each host comes from via [HostEntry.SourceFile].

Compatibility Fixes

Use ApplyCompatFixes to add legacy algorithm support for older SSH servers. This modifies host entries to include KexAlgorithms, Ciphers, MACs, or HostKeyAlgorithms directives as needed.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyAuthType

func ApplyAuthType(host *HostEntry, authType string) error

ApplyAuthType changes the authentication type of a host entry. authType should be "password", "keyboard-interactive", or "key".

func ApplyCompatFixes

func ApplyCompatFixes(host *HostEntry, compatTypes []compat.CompatType) error

ApplyCompatFixes adds compatibility fix lines to a host entry. It removes any existing conflicting directives and inserts new ones.

func DeriveHostID

func DeriveHostID(input string) string

DeriveHostID generates a short Host identifier from an FQDN. For "server.example.com" returns "server". For names without dots, returns as-is (already a short identifier).

func FindInsertionIndex

func FindInsertionIndex(hosts []*HostEntry, newHost string) int

FindInsertionIndex finds where to insert a host to maintain alphabetical order.

func GetAppliedCompatFixes

func GetAppliedCompatFixes(host *HostEntry) []compat.CompatType

GetAppliedCompatFixes returns which compat fixes are already applied to a host.

func HasCompatFix

func HasCompatFix(host *HostEntry, compatType compat.CompatType) bool

HasCompatFix checks if a host entry already has a specific compatibility fix.

func SortHosts

func SortHosts(hosts []*HostEntry)

SortHosts sorts hosts alphabetically by Host.

Types

type HostEntry

type HostEntry struct {
	// Host is the primary identifier (first pattern from "Host" line)
	Host string

	// HostName is the resolved address SSH connects to (from HostName directive, defaults to Host)
	HostName string

	// Patterns contains all patterns from the Host line
	Patterns []string

	// Lines contains the raw config lines including the Host directive
	Lines []string

	// SourceFile is the path to the file containing this entry
	SourceFile string

	// Properties contains parsed key-value pairs (lowercase keys)
	Properties map[string]string
}

HostEntry represents a parsed SSH Host block.

func CreateHostEntry

func CreateHostEntry(host, hostname, user string, port int, usesPassword bool, sourceFile string) *HostEntry

CreateHostEntry creates a new HostEntry with the given parameters. host is the identifier/alias used in the Host line (what users type to connect). hostname is the resolved address SSH connects to (HostName directive, defaults to host if empty).

func FindHostByPattern

func FindHostByPattern(hosts []*HostEntry, pattern string) *HostEntry

FindHostByPattern searches for a host by pattern in a list.

func RemoveHost

func RemoveHost(hosts []*HostEntry, pattern string) []*HostEntry

RemoveHost removes a host from the list by pattern.

func (*HostEntry) Port

func (h *HostEntry) Port() string

Port returns the Port property or "22".

func (*HostEntry) User

func (h *HostEntry) User() string

User returns the User property or empty string.

func (*HostEntry) UsesPassword

func (h *HostEntry) UsesPassword() bool

UsesPassword returns true if the host uses password authentication.

type MatchResult

type MatchResult struct {
	Host        *HostEntry // Matched host (nil if no match or ambiguous)
	Suggestions []string   // Suggested hostnames if multiple matches
}

MatchResult represents the result of a fuzzy host match.

type ParsedConfig

type ParsedConfig struct {
	// Path to the parsed file
	Path string

	// HeaderLines are lines before the first Host block
	HeaderLines []string

	// Hosts are the parsed host entries
	Hosts []*HostEntry
}

ParsedConfig represents a parsed SSH config file.

type Parser

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

Parser handles SSH config file operations.

func NewParser

func NewParser() *Parser

NewParser creates a parser with default paths.

func NewParserWithPaths

func NewParserWithPaths(configFile, backupDir string, maxBackups int) *Parser

NewParserWithPaths creates a parser with explicit paths.

func (*Parser) ConfigFile

func (p *Parser) ConfigFile() string

ConfigFile returns the main SSH config path.

func (*Parser) FindHost

func (p *Parser) FindHost(pattern string) (*HostEntry, error)

FindHost searches all config files for a host by pattern.

func (*Parser) FindHostWithLocation

func (p *Parser) FindHostWithLocation(pattern string) (*HostEntry, *ParsedConfig, error)

FindHostWithLocation searches for a host and returns which file it's in.

func (*Parser) FindIncludeFiles

func (p *Parser) FindIncludeFiles() ([]string, error)

FindIncludeFiles scans the main SSH config for Include directives and returns the list of resolved file paths that exist, including nested includes.

func (*Parser) GetAllHosts

func (p *Parser) GetAllHosts() ([]*HostEntry, error)

GetAllHosts returns all hosts from all Include files plus the main config.

func (*Parser) GetIncludeFileForContext

func (p *Parser) GetIncludeFileForContext(includeFile string) (string, error)

GetIncludeFileForContext finds the SSH config file associated with a context. Returns the path if found, or suggests a default path.

func (*Parser) MatchHost

func (p *Parser) MatchHost(query string) (*MatchResult, error)

MatchHost finds a host by exact or partial match. Returns a MatchResult with either a single matched host or suggestions.

func (*Parser) ParseFile

func (p *Parser) ParseFile(path string) (*ParsedConfig, error)

ParseFile parses an SSH config file into header and host entries.

func (*Parser) WriteFile

func (p *Parser) WriteFile(cfg *ParsedConfig) error

WriteFile writes a parsed config back to disk atomically.

type TempConfig

type TempConfig struct {
	// Path is the path to the temporary config file.
	Path string

	// Host is the host entry being tested.
	Host *HostEntry
	// contains filtered or unexported fields
}

TempConfig manages a temporary SSH config file for testing. It allows testing SSH connections against a host entry before committing changes to the real SSH config.

func NewTempConfig

func NewTempConfig(host *HostEntry) (*TempConfig, error)

NewTempConfig creates a temporary SSH config file with the given host entry. The returned TempConfig.Path can be used with `ssh -F <path>`. It also includes any Host * settings from the user's SSH config to ensure the test uses the same algorithm restrictions as regular SSH connections. Call Cleanup() when done to remove the temp file.

func (*TempConfig) Cleanup

func (tc *TempConfig) Cleanup()

Cleanup removes the temporary config file. Safe to call multiple times.

func (*TempConfig) Update

func (tc *TempConfig) Update() error

Update writes the current host entry state to the temp file. Use this after modifying the host entry (e.g., applying compat fixes).

Jump to

Keyboard shortcuts

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