keysigner

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package keysigner 实现 XOps v2 基于 golang.org/x/crypto/ssh 的私钥解析、指纹核验与签名器适配器 (ports.KeySignerPort,ADR-011 / INV-F1)。

本包隶属 core/internal/sshnet/dial 明文消费白名单层(LayerCoreSSHNetDial),严格维持以下安全不变量:

  • 所有私钥原始字节均经 OperatorReadFS 有界读取后立即装入 secret.WithBytes 同步闭包零化消费, 仅保留不透明 ssh.Signer 与公钥指纹,绝不将原始私钥材料持久化或暴露至日志/错误;
  • 口令保护私钥经 SecretVault.WithSecret + 嵌套 keyBox.Use -> passBox.Use 解密并强制校验 INV-F1 指纹绑定;
  • 全包零行内 nolint 豁免、0 裸 go 语句与 0 全局状态。

Index

Constants

View Source
const (
	// MaxPrivateKeyFileBytes 限制单个本地私钥文件的读取字节上限(1 MiB)。
	MaxPrivateKeyFileBytes int64 = 1 << 20
	// MaxCertFileBytes 限制单个本地用户证书文件的读取字节上限(1 MiB)。
	MaxCertFileBytes int64 = 1 << 20
)
View Source
const DefaultLazyPassphraseRetries = 3

DefaultLazyPassphraseRetries 定义交互式加密私钥口令提示的最大重试次数(ADR-019 B2)。

Variables

This section is empty.

Functions

func AttachMatchingCert

func AttachMatchingCert(signer ssh.Signer, certs []*ssh.Certificate) ssh.Signer

AttachMatchingCert 若 certs 中存在公钥指纹与 signer 匹配的 SSH 证书,则返回证书签名包装器,否则原样返回。

func FilterPublicKeyInfosByFingerprints added in v1.3.0

func FilterPublicKeyInfosByFingerprints(keys []ports.PublicKeyInfo, allowed []inventory.KeyFingerprint) ([]ports.PublicKeyInfo, error)

FilterPublicKeyInfosByFingerprints 按允许指纹列表过滤 ports.PublicKeyInfo(同时支持证书指纹与底层 cert.Key 指纹)。

func FingerprintOfSSHKey

func FingerprintOfSSHKey(key ssh.PublicKey) inventory.KeyFingerprint

FingerprintOfSSHKey 计算 ssh.PublicKey 的 SHA-256 规范指纹;nil 公钥返回无效零值。

func LoadCertificates

func LoadCertificates(
	ctx context.Context,
	readFS ports.OperatorReadFS,
	env ports.EnvPort,
	tokenCtx option.TokenContext,
	certPaths []inventory.CertPathSpec,
) ([]*ssh.Certificate, error)

LoadCertificates 按路径清单读取并解析本地 OpenSSH 用户证书(缺失的证书文件按 OpenSSH 惯例静默跳过)。

func LoadPrivateKeyFile

LoadPrivateKeyFile 通过 OperatorReadFS 读取有界私钥文件并在同步 SecretBox 闭包内解密为不透明 ssh.Signer。 强制执行 INV-F1:当绑定口令凭据时,解密后公钥指纹必须与 KeyPassphraseBinding.KeyFingerprint 一致。

func ParsePrivateKeyBytes

func ParsePrivateKeyBytes(
	ctx context.Context,
	vault ports.SecretVault,
	keyBytes []byte,
	passOpt algebraic.Option[inventory.KeyPassphraseBinding],
) (ssh.Signer, error)

ParsePrivateKeyBytes 在同步明文作用域内解析未加密或口令保护私钥,并强制校验 INV-F1 口令指纹绑定。

func PublicKeyInfoFromSSH

func PublicKeyInfoFromSSH(key ssh.PublicKey) (ports.PublicKeyInfo, error)

PublicKeyInfoFromSSH 将 golang.org/x/crypto/ssh.PublicKey 转换为协议库无关的不可变 ports.PublicKeyInfo。

func ReadBoundedFile

func ReadBoundedFile(ctx context.Context, readFS ports.OperatorReadFS, path pathalg.LocalSourcePath, maxBytes int64) ([]byte, error)

ReadBoundedFile 经 OperatorReadFS 在 maxBytes 上限内安全读取单个文件字节(失败或超限时立即 clear 局部缓冲)。

func ResolveLocalFilePath

func ResolveLocalFilePath(env ports.EnvPort, tokenCtx option.TokenContext, raw string) (pathalg.LocalSourcePath, error)

ResolveLocalFilePath 依次展开路径模板中的 OpenSSH % 令牌、${ENV} 环境变量与 "~/" 主目录前缀, 并解析为不可变 LocalSourcePath;未设置或畸形 ${ENV} 立即失败关闭,绝不按 CWD 相对路径探测字面量。

func VerifyPassphraseBindingLoaded

func VerifyPassphraseBindingLoaded(rawSigners []ssh.Signer, passOpt algebraic.Option[inventory.KeyPassphraseBinding]) error

VerifyPassphraseBindingLoaded 强制校验 INV-F1 防掉包不变式: 当 AuthPrivateKey 声明了 KeyPassphraseBinding 时,必须在附加证书前确认已加载的原始私钥集合中 至少包含一枚与 binding.KeyFingerprint 一致的私钥,彻底阻断将加密私钥静默替换为未加密伪造私钥的绕过攻击。

func WrapPortSigners

func WrapPortSigners(keys []ports.PublicKeyInfo, signFn PortSignFunc) ([]ssh.Signer, error)

WrapPortSigners 将一组 ports.PublicKeyInfo 包装为可传入 ssh.PublicKeys 的 ssh.Signer 列表。

Types

type AgentKeyEntry added in v1.3.0

type AgentKeyEntry struct {
	Pub    ssh.PublicKey
	FP     inventory.KeyFingerprint
	BaseFP inventory.KeyFingerprint
	IsCert bool
	Signer ssh.Signer
}

AgentKeyEntry 表示已从 SSHAgentPort 列举并包装好的单枚代理签名器及其主/底层指纹元数据。

func BuildAgentEntries added in v1.3.0

func BuildAgentEntries(keys []ports.PublicKeyInfo, signFn PortSignFunc) ([]AgentKeyEntry, error)

BuildAgentEntries 将 SSHAgentPort.ListAgentKeys 返回的公钥元数据包装为含主/底层指纹的 AgentKeyEntry 切片。

func FilterAgentEntries added in v1.3.0

func FilterAgentEntries(entries []AgentKeyEntry, allowed []inventory.KeyFingerprint, identitiesOnly bool) []AgentKeyEntry

FilterAgentEntries 在 IdentitiesOnly 模式下按允许指纹集合筛选代理签名器条目。

type Config

type Config struct {
	// ReadFS 提供操作员本地私钥与证书文件的受控只读能力(经 SymlinkFollowOperatorSource)。
	ReadFS ports.OperatorReadFS
	// Vault 可选注入凭据库,用于读取口令保护私钥绑定的解密口令。
	Vault ports.SecretVault
	// Agent 可选注入本机 SSH Agent 端口,用于 AuthAgent 变体列举与签名回退。
	Agent ports.SSHAgentPort
	// Env 可选注入本机身份信息端口,用于展开私钥/证书路径中的 "~/" 前缀。
	Env ports.EnvPort
	// Entropy 可选注入显式随机字节源供签名算法使用;为空时回退 crypto/rand.Reader。
	Entropy ports.Entropy
}

Config 描述 KeySigner 的显式出站依赖配置(全依赖注入,零全局单例与隐式环境变量)。

type KeySigner

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

KeySigner 实现 ports.KeySignerPort,提供并发安全的私钥加载、证书匹配、签名与指纹核验能力;零值恒失败关闭。

func NewKeySigner

func NewKeySigner(cfg Config) (*KeySigner, error)

NewKeySigner 校验至少注入 ReadFS 或 Agent 端口后构造不可变 KeySigner。

func (*KeySigner) InspectPrivateKeyFingerprint

func (k *KeySigner) InspectPrivateKeyFingerprint(
	ctx context.Context,
	keyPath inventory.KeyPathSpec,
	passphrase algebraic.Option[secret.Ref],
) (inventory.KeyFingerprint, error)

InspectPrivateKeyFingerprint 读取并核验未加密或口令保护私钥文件的 SHA-256 公钥指纹(支撑加密私钥原子登记)。

func (*KeySigner) ListPublicKeys

func (k *KeySigner) ListPublicKeys(ctx context.Context, auth inventory.AuthMethod) ([]ports.PublicKeyInfo, error)

ListPublicKeys 根据认证方式加载并缓存不透明签名器,返回协议库无关的公钥元数据列表。

func (*KeySigner) Sign

func (k *KeySigner) Sign(ctx context.Context, key inventory.KeyFingerprint, algorithm string, data []byte) (ports.Signature, error)

Sign 使用已加载的本地不透明 ssh.Signer 或已登记的 Agent 公钥对 data 执行指定算法签名。

type LazyPassphraseConfig added in v1.3.0

type LazyPassphraseConfig struct {
	Ctx             context.Context
	PubKey          ssh.PublicKey
	AdvertisedPubFP inventory.KeyFingerprint
	KeyPath         pathalg.LocalSourcePath
	DisplayPath     string
	Subject         string
	ReadFS          ports.OperatorReadFS
	Interaction     ports.InteractionPort
	PauseDeadline   func() func()
	MaxAttempts     int
	OnDiag          func(level uint8, msg string)
}

LazyPassphraseConfig 描述惰性加密私钥签名器的显式构造入参(构造期零私钥字节、零口令常驻)。

type LazyPassphraseSigner added in v1.3.0

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

LazyPassphraseSigner 实现 ssh.AlgorithmSigner 与 ssh.MultiAlgorithmSigner, 仅在远端返回 SSH_MSG_USERAUTH_PK_OK 后按需经 OperatorReadFS + PromptSecret(AllowAskpass=true) 在同步闭包内临时解密、核验 TOCTOU 公钥指纹并立即签名,退出即清零全部明文缓冲(ADR-019 B2)。

func NewLazyPassphraseSigner added in v1.3.0

func NewLazyPassphraseSigner(cfg LazyPassphraseConfig) (*LazyPassphraseSigner, error)

NewLazyPassphraseSigner 校验入参并构造不持有私钥明文与口令的惰性签名器。

func (*LazyPassphraseSigner) Algorithms added in v1.3.0

func (s *LazyPassphraseSigner) Algorithms() []string

Algorithms 返回本签名器底层支持的签名算法偏好顺序(使 RSA 密钥优先协商 rsa-sha2-256 / rsa-sha2-512)。

func (*LazyPassphraseSigner) HardErr added in v1.3.0

func (s *LazyPassphraseSigner) HardErr() error

HardErr 返回签名过程中触发的硬安全错误(如 TOCTOU 公钥指纹变更、符号链接拒绝或上下文取消), 供上层 AuthCallback 区分「硬中止」与「3 次口令失败/用户取消后平滑回退」。

func (*LazyPassphraseSigner) PublicKey added in v1.3.0

func (s *LazyPassphraseSigner) PublicKey() ssh.PublicKey

PublicKey 返回探测阶段呈递给服务端的公钥(不触碰私钥密文与交互提示)。

func (*LazyPassphraseSigner) Sign added in v1.3.0

func (s *LazyPassphraseSigner) Sign(rand io.Reader, data []byte) (*ssh.Signature, error)

Sign 以默认算法签名,委托至 SignWithAlgorithm 执行惰性解密与 TOCTOU 核验。

func (*LazyPassphraseSigner) SignWithAlgorithm added in v1.3.0

func (s *LazyPassphraseSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*ssh.Signature, error)

SignWithAlgorithm 在暂停握手截止时间窗口内读取私钥、最多重试 maxAttempts 次提示口令、 核验解密后公钥指纹一致性防 TOCTOU 并完成单次签名,随后退出闭包清零全部明文。

type LegacyPEMConfig added in v1.3.0

type LegacyPEMConfig struct {
	Ctx           context.Context
	KeyPath       pathalg.LocalSourcePath
	DisplayPath   string
	Subject       string
	Certs         []*ssh.Certificate
	ReadFS        ports.OperatorReadFS
	Interaction   ports.InteractionPort
	PauseDeadline func() func()
	MaxAttempts   int
	OnDiag        func(level uint8, msg string)
}

LegacyPEMConfig 描述缺 .pub 的老式加密 PEM 延迟认证加载器配置(仅在主机密钥校验通过后触发)。

type LegacyPEMLoader added in v1.3.0

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

LegacyPEMLoader 封装缺 .pub 的老式加密 PEM 延迟解密回调(用于 ssh.PublicKeysCallback,绝不在主机密钥校验前弹窗)。

func NewLegacyPEMLoader added in v1.3.0

func NewLegacyPEMLoader(cfg LegacyPEMConfig) (*LegacyPEMLoader, error)

NewLegacyPEMLoader 构造缺 .pub 老式加密 PEM 延迟加载器(构造期零私钥字节与口令常驻)。

func (*LegacyPEMLoader) HardErr added in v1.3.0

func (l *LegacyPEMLoader) HardErr() error

HardErr 返回延迟加载老式加密 PEM 期间遇到的硬安全错误(如符号链接拒绝或上下文取消)。

func (*LegacyPEMLoader) LoadSigners added in v1.3.0

func (l *LegacyPEMLoader) LoadSigners() ([]ssh.Signer, error)

LoadSigners 供 ssh.PublicKeysCallback 在主机密钥校验通过后按需调用: 暂停握手截止时间、读取私钥并最多重试 3 次交互解密、配对匹配证书后返回单次签名器列表。

type NoReadFSPubkeyInput added in v1.3.0

type NoReadFSPubkeyInput struct {
	Ctx            context.Context
	KeySigner      ports.KeySignerPort
	PrivKeys       []*inventory.AuthPrivateKey
	HasAgents      bool
	IdentitiesOnly bool
	AgentFirst     bool
	AllowedFPs     []inventory.KeyFingerprint
	FetchAgent     func() ([]AgentKeyEntry, error)
	OnDiag         func(level uint8, msg string)
}

NoReadFSPubkeyInput 聚合无本地 OperatorReadFS 路径(MCP 或仅注入 KeySignerPort/Agent)的公钥编排参数。

type PortSignFunc

type PortSignFunc func(fp inventory.KeyFingerprint, algorithm string, data []byte) (ports.Signature, error)

PortSignFunc 是适配外部 KeySignerPort / SSHAgentPort 签名回调的函数类型。

type PubkeyStep added in v1.3.0

type PubkeyStep struct {
	Method  ssh.AuthMethod
	HardErr func() error
}

PubkeyStep 表示统一公钥管线产出的单个认证步骤(合并后的即时签名批次、单个惰性口令签名器或延迟老式 PEM 回调)。

func BuildNoReadFSPubkeySteps added in v1.3.0

func BuildNoReadFSPubkeySteps(in NoReadFSPubkeyInput) ([]PubkeyStep, error)

BuildNoReadFSPubkeySteps 处理无本地读权限路径(如 MCP 或仅注入 KeySignerPort/Agent 的测试桩): 当 IdentitiesOnly=true 且无允许指纹时严格返回 0 枚 Agent 密钥(MCP 隔离铁律),并保持 AgentFirst 优先级顺序。

func BuildUnifiedPubkeySteps added in v1.3.0

func BuildUnifiedPubkeySteps(in UnifiedPubkeyInput) ([]PubkeyStep, error)

BuildUnifiedPubkeySteps 在 ReadFS 可用时按 OpenSSH 顺序统一编排 AuthPrivateKey 与 AuthAgent:

  1. 加载显式 CertificateFile 并自动只读探测各 IdentityFile 同目录 <key>-cert.pub(缺失静默跳过,损坏失败关闭);
  2. 若默认未显式指定 IdentityFile(AgentFirst==true),先呈递 SSH Agent 密钥再尝试默认本地私钥(避免先弹默认加密私钥口令);
  3. 按显式 IdentityFile 顺序优先匹配 Agent 普通签名器配对新证,未覆盖时加载本地私钥/惰性口令签名器/延迟老式 PEM 回调;
  4. 仅 .pub 硬件密钥匹配 Agent 时缺失本地私钥不报错;BatchMode 下未绑定加密私钥以 ErrSignerUnavailable 跳过;
  5. 合并剩余 Agent 密钥(IdentitiesOnly=true 时按 allowedFPs 过滤)并按最终公钥/证书指纹全局去重。

type UnifiedPubkeyInput added in v1.3.0

type UnifiedPubkeyInput struct {
	Ctx                    context.Context
	ReadFS                 ports.OperatorReadFS
	Vault                  ports.SecretVault
	Env                    ports.EnvPort
	Interaction            ports.InteractionPort
	TokenCtx               option.TokenContext
	Subject                string
	BatchMode              bool
	IdentitiesOnly         bool
	AgentFirst             bool
	PrivKeys               []*inventory.AuthPrivateKey
	TransportIdentityFiles option.PathList
	TransportCertFiles     option.PathList
	AgentEntries           []AgentKeyEntry
	AgentAllowedFPs        []inventory.KeyFingerprint
	PauseDeadline          func() func()
	OnDiag                 func(level uint8, msg string)
}

UnifiedPubkeyInput 聚合单跳统一公钥编排管线(ADR-019 B1/B2)所需的全部显式依赖与策略参数。

Jump to

Keyboard shortcuts

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