ssh_config

package module
v0.0.0-...-b38c9e3 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2026 License: MIT Imports: 16 Imported by: 0

README

ssh_config

This is a Go parser for ssh_config files. Importantly, this parser attempts to preserve comments in a given file, so you can manipulate a ssh_config file from a program, if your heart desires.

Fork Notice

This repository is a personal long-term public fork of the original ssh_config project, maintained under its own roadmap.

It's designed to be used with the excellent x/crypto/ssh package, which handles SSH negotiation but isn't very easy to configure.

Use the Resolve API for OpenSSH-accurate evaluation, including Match blocks and spec defaults.

Resolver API (OpenSSH-accurate)

ctx := ssh_config.Context{HostArg: "myhost"}
res, err := ssh_config.DefaultUserSettings.Resolve(ctx, ssh_config.Strict())
if err != nil {
    log.Fatal(err)
}
port := res.Get("Port")
files := res.GetAll("IdentityFile")

You can also load a config file and resolve values from it.

var config = `
Host *.test
  Compression yes
`

cfg, err := ssh_config.Decode(strings.NewReader(config))
if err != nil {
    log.Fatal(err)
}

ctx := ssh_config.Context{HostArg: "example.test"}
res, err := cfg.Resolve(ctx, ssh_config.Strict())
if err != nil {
    log.Fatal(err)
}
port := res.Get("Port")
files := res.GetAll("IdentityFile")

Strict mode validates directives and values against the vendored OpenSSH client spec. Unknown directives are rejected unless IgnoreUnknown matches them; deprecated directives are only accepted when they alias a supported directive. Defaults from the OpenSSH 10.2 spec are applied in Resolve.

Resolve also supports multi-pass evaluation via FinalPass() and optional canonicalization via Canonicalize(...). Match exec and Match localnetwork require callbacks on Context (Exec and LocalNetwork) when strict.

Manipulating SSH config files

Here's how you can manipulate an SSH config file, and then write it back to disk.

f, _ := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "config"))
cfg, _ := ssh_config.Decode(f)
for _, host := range cfg.Hosts {
    fmt.Println("patterns:", host.Patterns)
    for _, node := range host.Nodes {
        // Manipulate the nodes as you see fit, or use a type switch to
        // distinguish between Empty, KV, and Include nodes.
        fmt.Println(node.String())
    }
}

// Print the config to stdout:
fmt.Println(cfg.String())

For parsed configs (Decode/DecodeBytes), mutate cfg.Blocks if you want changes reflected by both Resolve and String. cfg.Hosts remains useful for legacy traversal, but Hosts-only mutations are not authoritative when cfg.Blocks is populated.

Spec compliance

Wherever possible we try to implement the specification as documented in the ssh_config manpage. Unimplemented features should be present in the issues list.

Match is supported in the Resolve API.

OpenSSH client spec

The OpenSSH client option spec is generated from a local OpenSSH source checkout in openssh-portable/ and stored in testdata/openssh_client_spec.json. The generator extracts keywords, defaults, aliases, types, and token/env expansion metadata from readconf.c, myproposal.h, and ssh_config.5. If openssh-portable/ is missing, the generator will clone the upstream OpenSSH portable repository into that git-ignored directory on demand.

To update the spec after bumping OpenSSH:

  1. Update the openssh-portable/ tree.
  2. Run go run ./cmd/openssh-specgen.
  3. Run go test ./....

Attribution

Huge thanks to Kevin Burke and all prior contributors for the original ssh_config project and the foundation this fork builds on.

Contributor credits are listed in AUTHORS.txt.

License

This fork is released under the MIT License. See LICENSE for details, including attribution and third-party license notices.

Documentation

Overview

Package ssh_config provides tools for parsing and resolving SSH config files.

Importantly, this parser attempts to preserve comments in a given file, so you can manipulate a `ssh_config` file from a program, if your heart desires.

For OpenSSH-accurate evaluation (including Match), use Resolve.

cfg, _ := ssh_config.Decode(strings.NewReader(config))
res, _ := cfg.Resolve(ssh_config.Context{HostArg: "example.com"})
port := res.Get("Port")

You can also manipulate an SSH config file and then print it or write it back to disk.

f, _ := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "config"))
cfg, _ := ssh_config.Decode(f)
for _, host := range cfg.Hosts {
	fmt.Println("patterns:", host.Patterns)
	for _, node := range host.Nodes {
		fmt.Println(node.String())
	}
}

// Write the cfg back to disk:
fmt.Println(cfg.String())

NOTE: Match directives are supported via Resolve.

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultUserSettings = &UserSettings{
	IgnoreErrors:       false,
	systemConfigFinder: systemConfigFinder,
	userConfigFinder:   userConfigFinder,
}

DefaultUserSettings is the default UserSettings used for resolving configs. It checks both $HOME/.ssh/config and /etc/ssh/ssh_config for keys, and it returns parse errors (if any) instead of swallowing them.

View Source
var ErrDepthExceeded = errors.New("ssh_config: max recurse depth exceeded")

ErrDepthExceeded is returned if too many Include directives are parsed. Usually this indicates a recursive loop (an Include directive pointing to the file it contains).

Functions

func Default

func Default(keyword string) string

Default returns the default value for a supported directive from the embedded OpenSSH client spec. Keyword matching is case-insensitive.

Example
package main

import (
	"fmt"

	"github.com/ncode/ssh_config"
)

func main() {
	fmt.Println(ssh_config.Default("Port"))
	fmt.Println(ssh_config.Default("UnknownVar"))
}
Output:

22

func SupportsMultiple

func SupportsMultiple(key string) bool

SupportsMultiple reports whether a supported directive accepts multiple values, based on the embedded OpenSSH client spec.

Types

type Block

type Block interface {
	Pos() Position
	String() string
	// contains filtered or unexported methods
}

Block represents a top-level block in a Config.

type Config

type Config struct {
	// A list of hosts to match against. The file begins with an implicit
	// "Host *" declaration matching all hosts.
	Hosts  []*Host
	Blocks []Block
	// contains filtered or unexported fields
}

Config represents an SSH config file.

func Decode

func Decode(r io.Reader) (*Config, error)

Decode reads r into a Config, or returns an error if r could not be parsed as an SSH config file.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/ncode/ssh_config"
)

func main() {
	var config = `
Host *.example.com
  Compression yes
`

	cfg, _ := ssh_config.Decode(strings.NewReader(config))
	res, _ := cfg.Resolve(ssh_config.Context{HostArg: "test.example.com"})
	fmt.Println(res.Get("Compression"))
}
Output:

yes

func DecodeBytes

func DecodeBytes(b []byte) (*Config, error)

DecodeBytes reads b into a Config, or returns an error if r could not be parsed as an SSH config file.

func (Config) MarshalText

func (c Config) MarshalText() ([]byte, error)

func (*Config) Resolve

func (c *Config) Resolve(ctx Context, opts ...ResolveOption) (*Result, error)

Resolve evaluates the Config with OpenSSH-like semantics.

func (Config) String

func (c Config) String() string

String returns a string representation of the Config file.

type Context

type Context struct {
	HostArg      string
	OriginalHost string
	LocalUser    string
	Version      string
	SessionType  string
	Command      string
	Exec         func(cmd string) (bool, error)
	LocalNetwork func(cidr string) (bool, error)
}

Context supplies data for Resolve, including Match evaluation.

type Empty

type Empty struct {
	Comment string
	// contains filtered or unexported fields
}

Empty is a line in the config file that contains only whitespace or comments.

func (*Empty) Pos

func (e *Empty) Pos() Position

Pos returns e's Position.

func (*Empty) String

func (e *Empty) String() string

String prints e as it was parsed in the config file.

type Host

type Host struct {
	// A list of host patterns that should match this host.
	Patterns []*Pattern
	// A Node is either a key/value pair or a comment line.
	Nodes []Node
	// EOLComment is the comment (if any) terminating the Host line.
	EOLComment string
	// contains filtered or unexported fields
}

Host describes a Host directive and the keywords that follow it.

func (*Host) Matches

func (h *Host) Matches(alias string) bool

Matches returns true if the Host matches for the given alias. For a description of the rules that provide a match, see the manpage for ssh_config.

Example
package main

import (
	"fmt"

	"github.com/ncode/ssh_config"
)

func main() {
	pat, _ := ssh_config.NewPattern("test.*.example.com")
	host := &ssh_config.Host{Patterns: []*ssh_config.Pattern{pat}}
	fmt.Println(host.Matches("test.stage.example.com"))
	fmt.Println(host.Matches("othersubdomain.example.com"))
}
Output:

true
false

func (*Host) Pos

func (h *Host) Pos() Position

Pos returns h's Position.

func (*Host) String

func (h *Host) String() string

String prints h as it would appear in a config file. Minor tweaks may be present in the whitespace in the printed file.

type Include

type Include struct {
	// Comment is the contents of any comment at the end of the Include
	// statement.
	Comment string
	// contains filtered or unexported fields
}

Include holds the result of an Include directive, including the config files that have been parsed as part of that directive. At most 5 levels of Include statements will be parsed.

func NewInclude

func NewInclude(directives []string, hasEquals bool, pos Position, comment string, system bool, depth uint8) (*Include, error)

NewInclude creates a new Include with a list of file globs to include. Configuration files are parsed greedily (e.g. as soon as this function runs). Any error encountered while parsing nested configuration files will be returned.

func (*Include) Pos

func (i *Include) Pos() Position

Pos returns the position of the Include directive in the larger file.

func (*Include) String

func (inc *Include) String() string

String prints out a string representation of this Include directive. Note included Config files are not printed as part of this representation.

type KV

type KV struct {
	Key   string
	Value string

	Comment string
	// contains filtered or unexported fields
}

KV is a line in the config file that contains a key, a value, and possibly a comment.

func (*KV) Pos

func (k *KV) Pos() Position

Pos returns k's Position.

func (*KV) String

func (k *KV) String() string

String prints k as it was parsed in the config file.

type Match

type Match struct {
	// Criteria is the raw criteria string after the Match directive.
	Criteria string
	// A Node is either a key/value pair or a comment line.
	Nodes []Node
	// EOLComment is the comment (if any) terminating the Match line.
	EOLComment string
	// contains filtered or unexported fields
}

Match describes a Match directive and the keywords that follow it.

func (*Match) Pos

func (m *Match) Pos() Position

Pos returns m's Position.

func (*Match) String

func (m *Match) String() string

String prints m as it would appear in a config file.

type Node

type Node interface {
	Pos() Position
	String() string
}

Node represents a line in a Config.

type Pattern

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

Pattern is a pattern in a Host declaration. Patterns are read-only values; create a new one with NewPattern().

Example
package main

import (
	"fmt"

	"github.com/ncode/ssh_config"
)

func main() {
	pat, _ := ssh_config.NewPattern("*")
	host := &ssh_config.Host{Patterns: []*ssh_config.Pattern{pat}}
	fmt.Println(host.Matches("test.stage.example.com"))
	fmt.Println(host.Matches("othersubdomain.any.any"))
}
Output:

true
true

func NewPattern

func NewPattern(s string) (*Pattern, error)

NewPattern creates a new Pattern for matching hosts. NewPattern("*") creates a Pattern that matches all hosts.

From the manpage, a pattern consists of zero or more non-whitespace characters, `*' (a wildcard that matches zero or more characters), or `?' (a wildcard that matches exactly one character). For example, to specify a set of declarations for any host in the ".co.uk" set of domains, the following pattern could be used:

Host *.co.uk

The following pattern would match any host in the 192.168.0.[0-9] network range:

Host 192.168.0.?

func (Pattern) String

func (p Pattern) String() string

String prints the string representation of the pattern.

type Position

type Position struct {
	Line int // line within the document
	Col  int // column within the line
}

Position of a document element within a SSH document.

Line and Col are both 1-indexed positions for the element's line number and column number, respectively. Values of zero or less will cause Invalid(), to return true.

func (Position) Invalid

func (p Position) Invalid() bool

Invalid returns whether or not the position is valid (i.e. with negative or null values)

func (Position) String

func (p Position) String() string

String representation of the position. Displays 1-indexed line and column numbers.

type ResolveOption

type ResolveOption func(*resolveOptions)

ResolveOption configures Resolve behavior.

func Canonicalize

func Canonicalize(fn func(host string) (canonical string, changed bool, err error)) ResolveOption

Canonicalize provides a callback to perform host canonicalization.

func FinalPass

func FinalPass() ResolveOption

FinalPass enables a final pass where Match final evaluates true.

func Strict

func Strict() ResolveOption

Strict enables strict validation using the OpenSSH client spec.

type Result

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

Result holds resolved configuration values.

func (*Result) Get

func (r *Result) Get(key string) string

Get returns the effective value for key, or empty string if none.

func (*Result) GetAll

func (r *Result) GetAll(key string) []string

GetAll returns all effective values for key.

type UserSettings

type UserSettings struct {
	IgnoreErrors bool
	// contains filtered or unexported fields
}

UserSettings checks ~/.ssh and /etc/ssh for configuration files. The config files are parsed and cached the first time Resolve is called.

func (*UserSettings) ConfigFinder

func (u *UserSettings) ConfigFinder(f func() string)

ConfigFinder will invoke f to try to find a ssh config file in a custom location on disk, instead of in /etc/ssh or $HOME/.ssh. f should return the name of a file containing SSH configuration.

ConfigFinder must be invoked before any calls to Resolve and panics if f is nil. Most users should not need to use this function.

Example
package main

import (
	"path/filepath"

	"github.com/ncode/ssh_config"
)

func main() {
	// This can be used to test SSH config parsing.
	u := ssh_config.UserSettings{}
	u.ConfigFinder(func() string {
		return filepath.Join("testdata", "test_config")
	})
	u.Resolve(ssh_config.Context{HostArg: "example.com"})
}

func (*UserSettings) Resolve

func (u *UserSettings) Resolve(ctx Context, opts ...ResolveOption) (*Result, error)

Resolve evaluates user/system config files with OpenSSH-like semantics.

Directories

Path Synopsis
cmd
openssh-specgen command
internal

Jump to

Keyboard shortcuts

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