commands

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2026 License: Apache-2.0 Imports: 39 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IdentityString

func IdentityString(pkt pktoken.PKToken) (string, error)

IdentityString returns a string representation of the identity from the PK Token. e.g "Email, sub, issuer, audience"

func PrettyIdToken added in v0.5.0

func PrettyIdToken(pkt pktoken.PKToken) (string, error)

PrettyIdToken returns a pretty-printed JSON representation of the ID Token claims.

func ReadHome

func ReadHome(username string) ([]byte, error)

ReadHome is used to read the home policy file for the user with the specified username. This is used when opkssh is called by AuthorizedKeysCommand as the opksshuser and needs to use sudoer access to read the home policy file (`/home/<username>/opk/auth_id`). This function is only available on Linux and Darwin because it relies on syscall.Stat_t to determine the owner of the file.

Types

type AddCmd

type AddCmd struct {
	HomePolicyLoader   *policy.HomePolicyLoader
	SystemPolicyLoader *policy.SystemPolicyLoader

	// Username is the username to lookup when the system policy file cannot be
	// read and we fallback to the user's policy file.
	//
	// See AddCmd.LoadPolicy for more details.
	Username string
}

AddCmd provides functionality to read and update the opkssh policy file

func (*AddCmd) GetPolicyPath

func (a *AddCmd) GetPolicyPath(principal string, userEmail string, issuer string) (string, bool, error)

GetPolicyPath returns the path to the policy file that the current command will write to and a boolean to flag the path is for home policy. True means home policy, false means system policy.

func (*AddCmd) LoadPolicy

func (a *AddCmd) LoadPolicy() (*policy.Policy, string, error)

LoadPolicy reads the opkssh policy at the policy.SystemDefaultPolicyPath. If there is a permission error when reading this file, then the user's local policy file (defined as ~/.opk/auth_id where ~ maps to AddCmd.Username's home directory) is read instead.

If successful, returns the parsed policy and filepath used to read the policy. Otherwise, a non-nil error is returned.

func (*AddCmd) Run added in v0.4.0

func (a *AddCmd) Run(principal string, userEmail string, issuer string) (string, error)

Run adds a new allowed principal to the user whose email is equal to userEmail. The policy file is read and modified.

If successful, returns the policy filepath updated. Otherwise, returns a non-nil error

type AuditCmd added in v0.12.0

type AuditCmd struct {
	Fs     afero.Fs
	Out    io.Writer
	ErrOut io.Writer

	ProviderLoader  policy.ProviderLoader
	CurrentUsername string

	// Args
	ProviderPath   string // Custom provider file path
	PolicyPath     string // Custom policy file path
	JsonOutput     bool   // Output results in JSON format
	SkipUserPolicy bool   // Skip auditing user policy file
	// contains filtered or unexported fields
}

AuditCmd provides functionality to audit policy files against provider definitions

func NewAuditCmd added in v0.12.0

func NewAuditCmd(out io.Writer, errOut io.Writer) *AuditCmd

NewAuditCmd creates a new AuditCmd with default settings

func (*AuditCmd) Audit added in v0.12.0

func (a *AuditCmd) Audit(opksshVersion string) (*TotalResults, error)

func (*AuditCmd) Run added in v0.12.0

func (a *AuditCmd) Run(opksshVersion string) error

Run executes the audit command returns an error if it can't perform the audit or if the audit finds errors or warnings in system configuration. The opksshVersion parameter is the current opkssh version string.

type InspectCmd added in v0.11.0

type InspectCmd struct {
	// KeyOrCert is the SSH key or certificate to be inspected.
	KeyOrCert string
	// Output is where output should be written to.
	Output io.Writer
}

func NewInspectCmd added in v0.11.0

func NewInspectCmd(keyOrCert string, output io.Writer) *InspectCmd

NewInspectCmd creates a new InspectCmd instance with the provided arguments.

func (*InspectCmd) Run added in v0.11.0

func (i *InspectCmd) Run() error

type KeyType added in v0.9.0

type KeyType enumflag.Flag

KeyType is the algorithm to use for the user's key pair. This is used both by OpenPubkey as algorithm for upk (user public key) and by SSH for public key in the SSH certificate generated by opkssh.

const (
	ECDSA KeyType = iota
	ED25519
)

func (KeyType) String added in v0.9.0

func (k KeyType) String() string

type LoginCmd added in v0.4.0

type LoginCmd struct {
	// Inputs
	Fs                    afero.Fs
	AutoRefreshArg        bool   // Automatically refresh PK token after login
	ConfigPathArg         string // Path to the client config file.
	CreateConfigArg       bool   // Creates a client config file if it does not exist
	ConfigureArg          bool   // Apply changes to ssh config and create ~/.ssh/opkssh directory
	LogDirArg             string // Directory to write output logs
	SendAccessTokenArg    bool   // Send the Access Token as well as the PK Token in the SSH cert. The Access Token is used to call the userinfo endpoint to get claims not included in the ID Token
	DisableBrowserOpenArg bool   // Disable opening the browser. Useful for choosing the browser you want to use
	PrintIdTokenArg       bool   // Print out the contents of the id_token. Useful for inspecting claims and troubleshooting
	KeyPathArg            string // Path where SSH private key is written
	ProviderArg           string // OpenID Provider specification in the format: <issuer>,<client_id> or <issuer>,<client_id>,<client_secret> or <issuer>,<client_id>,<client_secret>,<scopes>
	ProviderAliasArg      string
	KeyTypeArg            KeyType
	PrintKeyArg           bool // Print private key and SSH cert instead of writing them to the filesystem
	SSHConfigured         bool
	Verbosity             int // Default verbosity is 0, 1 is verbose, 2 is debug
	RemoteRedirectURI     string

	// State
	Config *config.ClientConfig

	// For testing
	OutWriter io.Writer // Captures non-logged output that would normally be written to stdout
	// contains filtered or unexported fields
}

LoginCmd represents the login command that performs OIDC authentication and generates SSH certificates.

func NewLogin added in v0.4.0

func NewLogin(autoRefreshArg bool, configPathArg string, createConfigArg bool, configureArg bool, logDirArg string,
	sendAccessTokenArg bool, disableBrowserOpenArg bool, printIdTokenArg bool,
	providerArg string, printKeyArg bool, keyPathArg string, providerAliasArg string, keyTypeArg KeyType,
	remoteRedirectUri string,
) *LoginCmd

NewLogin creates a new LoginCmd instance with the provided arguments.

func (*LoginCmd) Login added in v0.5.0

func (l *LoginCmd) Login(ctx context.Context, provider providers.OpenIdProvider, printIdToken bool, seckeyPath string) error

Login performs the OIDC login procedure and creates the SSH certs/keys in the default SSH key location.

func (*LoginCmd) LoginWithRefresh added in v0.5.0

func (l *LoginCmd) LoginWithRefresh(ctx context.Context, provider providers.RefreshableOpenIdProvider, printIdToken bool, seckeyPath string) error

LoginWithRefresh performs the OIDC login procedure, creates the SSH certs/keys in the default SSH key location, and continues to run and refresh the PKT (and create new SSH certs) indefinitely as its token expires. This function only returns if it encounters an error or if the supplied context is cancelled.

func (*LoginCmd) Run added in v0.4.0

func (l *LoginCmd) Run(ctx context.Context) error

type PolicyEnforcerFunc

type PolicyEnforcerFunc func(username string, pkt *pktoken.PKToken, userInfo string, sshCert string, keyType string, denyList policy.DenyList, extraArgs []string) error

PolicyEnforcerFunc returns nil if the supplied PK token is permitted to login as username. Otherwise, an error is returned indicating the reason for rejection

func OpkPolicyEnforcerFunc

func OpkPolicyEnforcerFunc(username string) PolicyEnforcerFunc

OpkPolicyEnforcerAuthFunc returns an opkssh policy.Enforcer that can be used in the opkssh verify command.

type PolicyFileResult added in v0.12.0

type PolicyFileResult struct {
	FilePath string `json:"file_path"`
	// The validation results for each row in the policy file
	Rows []policy.ValidationRowResult `json:"rows"`
	// Error records any errors found in reading the policy file
	Error string `json:"error"`
	// PermsError records any permission errors found on the policy file
	PermsError string `json:"perms_error"`
}

PolicyFileResult records the results of auditing a policy file, e.g. /etc/opk/auth_id or ~/.opk/auth_id

type ProviderResults added in v0.12.0

type ProviderResults struct {
	FilePath string `json:"file_path"`
	// Error records any permission errors found on the provider file
	Error string `json:"error"`
}

ProviderResults records the results of auditing a provider file, e.g. /etc/opk/providers

type TotalResults added in v0.12.0

type TotalResults struct {
	// Overall status of the audit, true if the audit did not find any problems
	Ok bool `json:"ok"`
	// Username of the process that ran the audit
	Username         string             `json:"username"`
	ProviderFile     ProviderResults    `json:"providers_file"`
	SystemPolicyFile PolicyFileResult   `json:"system_policy"`
	HomePolicyFiles  []PolicyFileResult `json:"home_policy"`
	OpkVersion       string             `json:"opk_version"`
	OpenSSHVersion   string             `json:"openssh_version"`
	OsInfo           string             `json:"os_info"`
}

TotalResults aggregates all results of the audit

func (*TotalResults) EvaluateOk added in v0.12.0

func (t *TotalResults) EvaluateOk() bool

func (*TotalResults) SetOk added in v0.12.0

func (t *TotalResults) SetOk()

func (*TotalResults) SetOpenSSHVersion added in v0.12.0

func (t *TotalResults) SetOpenSSHVersion()

func (*TotalResults) SetOsInfo added in v0.12.0

func (t *TotalResults) SetOsInfo()

type VerifyCmd

type VerifyCmd struct {
	Fs afero.Fs
	// PktVerifier is responsible for verifying the PK token
	// contained in the SSH certificate
	PktVerifier verifier.Verifier
	// CheckPolicy determines whether the verified PK token is permitted to SSH as a
	// specific user
	CheckPolicy PolicyEnforcerFunc
	// ConfigPathArg is the path to the server config file
	ConfigPathArg string

	// HTTPClient can be mocked using a roundtripper in tests
	HttpClient *http.Client
	// contains filtered or unexported fields
}

VerifyCmd provides functionality to verify OPK tokens contained in SSH certificates and authorize requests to SSH as a specific username using a configurable authorization system. It is designed to be used in conjunction with sshd's AuthorizedKeysCommand feature.

func NewVerifyCmd added in v0.7.0

func NewVerifyCmd(pktVerifier verifier.Verifier, checkPolicy PolicyEnforcerFunc, configPathArg string) *VerifyCmd

NewVerifyCmd creates a new VerifyCmd instance with the provided arguments.

func (*VerifyCmd) AuthorizedKeysCommand

func (v *VerifyCmd) AuthorizedKeysCommand(ctx context.Context, userArg string, typArg string, certB64Arg string, extraArgs []string) (string, error)

This function is called by the SSH server as the AuthorizedKeysCommand:

By default, the following lines are added to the sshd_config at /etc/ssh/sshd_config.d/60-opk-ssh.conf:

AuthorizedKeysCommand /usr/local/bin/opkssh verify %u %k %t
AuthorizedKeysCommandUser opksshuser

The parameters specified in the config map the parameters sent to the function below. We prepend "Arg" to specify which ones are arguments sent by sshd. They are:

%u The username (requested principal) - userArg
%k The base64-encoded public key for authentication - certB64Arg - the public key is also a certificate
%t The public key type - typArg - in this case a certificate being used as a public key

AuthorizedKeysCommand verifies the OPK PK token contained in the base64-encoded SSH pubkey; the pubkey is expected to be an SSH certificate. pubkeyType is used to determine how to parse the pubkey as one of the SSH certificate types.

This function: 1. Verifying the PK token with the OP (OpenID Provider) 2. Enforcing policy by checking if the identity is allowed to assume the username (principal) requested.

If all steps of verification succeed, then the expected authorized_keys file format string is returned (i.e. the expected line to produce on standard output when using sshd's AuthorizedKeysCommand feature). Otherwise, a non-nil error is returned.

func (*VerifyCmd) ReadFromServerConfig added in v0.9.0

func (v *VerifyCmd) ReadFromServerConfig() error

ReadFromServerConfig sets the environment variables specified in the server config file and assigns configured deny lists to VerifyCmd's denyList

func (*VerifyCmd) UserInfoLookup added in v0.7.0

func (v *VerifyCmd) UserInfoLookup(ctx context.Context, pkt *pktoken.PKToken, accessToken string) (string, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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