ipa

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: BSD-3-Clause Imports: 28 Imported by: 1

README

goipa

Go client library for the FreeIPA / Red Hat IdM JSON-RPC API.

CI Go Reference Release Go version License

goipa talks to a FreeIPA server over HTTPS using its JSON-RPC API. It logs in with a password, a keytab, a Kerberos credential cache or an existing session, and gives you typed Go calls for users, passwords, SSH keys and OTP tokens.

Note: This is the maintained continuation of ubccr/goipa by Andrew E. Bruno, which has had no release since 2024. It is a drop-in replacement for ubccr/goipa v0.0.7; see Migrating from ubccr/goipa. It is developed alongside mokey, a FreeIPA self-service portal.

Features

  • Login: password (Login, RemoteLogin), keytab (LoginWithKeytab), Kerberos credential cache (LoginFromCCache), or a saved session ID (NewDefaultClientWithSession)
  • Reads the host, realm and CA from /etc/ipa/default.conf and /etc/ipa/ca.crt on enrolled machines, or takes them explicitly (NewClient, NewClientCustomHttp)
  • Users: show, find, add (with random or given password), modify, enable, disable, delete
  • Passwords: set, change (with OTP), reset; typed errors for policy, invalid and expired passwords
  • SSH public keys and user authentication types (password, OTP, ...)
  • OTP tokens: add, list, enable, disable, remove

Groups, stage users, HBAC/sudo, sub-IDs, passkeys, password policy and a generic RPC call are planned; see the roadmap.

Install

go get github.com/neverlless/goipa

Requires Go 1.26 or newer. The package name is ipa.

Usage

On a host enrolled in FreeIPA (with /etc/ipa/default.conf), log in with a keytab and show a user:

package main

import (
	"fmt"
	"log"

	ipa "github.com/neverlless/goipa"
)

func main() {
	client := ipa.NewDefaultClient()

	if err := client.LoginWithKeytab("/etc/myapp/myapp.keytab", "myapp"); err != nil {
		log.Fatal(err)
	}

	user, err := client.UserShow("jdoe")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s <%s> uid=%s groups=%v\n", user.DisplayName, user.Email, user.Uid, user.Groups)
}

Elsewhere, name the server and realm and log in with a password:

client := ipa.NewClient("ipa.example.com", "EXAMPLE.COM")
if err := client.RemoteLogin("jdoe", password); err != nil {
	switch {
	case errors.Is(err, ipa.ErrExpiredPassword):
		// ask for a new password, then client.SetPassword(...)
	case errors.Is(err, ipa.ErrInvalidPassword):
		// wrong password
	}
}
// Keep client.SessionID() and reuse it later with NewDefaultClientWithSession.

Full API reference: pkg.go.dev/github.com/neverlless/goipa.

Migrating from ubccr/goipa

The API is the same as ubccr/goipa v0.0.7. Change the import path:

grep -rl ubccr/goipa --include='*.go' . | xargs sed -i 's#ubccr/goipa#neverlless/goipa#'
go mod tidy

On macOS use sed -i ''. What changed since v0.0.7 is listed in the ChangeLog.

Differences from upstream

  • Security updates: golang.org/x/crypto and friends are current, and Dependabot and govulncheck keep them that way
  • Bug fixes: ErrUserExists no longer has the same message as ErrUnauthorized; Kerberos and request-building errors are returned instead of being ignored
  • go test ./... runs without a FreeIPA server; tests that need one are behind the integration build tag
  • CI with race detector, staticcheck, gosec and govulncheck

Development

go test -race ./...

Integration tests run against a real FreeIPA in a container. The scripts in container/ were adapted from webauthinfra by Jan Pazdziora (Apache 2.0) and are for development only, never production.

cp .env.sample .env      # set passwords and your SSH key
docker compose build
docker compose up -d
ssh -p 9022 localhost
kinit admin
cd /app
go test -tags integration ./...
go test -tags integration -v -run UserShow   # one test

See CONTRIBUTING.md before sending a pull request.

Security

Report vulnerabilities privately; see SECURITY.md.

License

goipa is released under a BSD-style license. See LICENSE and NOTICE. Copyright 2015 Andrew E. Bruno and the goipa authors (AUTHORS.rst).

Documentation

Overview

Package ipa is a Go client for the FreeIPA JSON-RPC API. It is a maintained continuation of github.com/ubccr/goipa.

A Client logs in with a password (Login for Kerberos, RemoteLogin for the web API), a keytab (LoginWithKeytab), a credentials cache (LoginFromCCache), or an existing session (NewDefaultClientWithSession, SetSessionID). A *Client is safe for concurrent use.

A FreeIPA error is returned as a bare *IpaError: match it with errors.Is against ErrNotFound and the other sentinels, or with a type assertion.

Every method that talks to the server has a ...Context twin that bounds the request with a context, except Login, LoginWithKeytab and LoginFromCCache (gokrb5 is not cancellable). RPC calls any command goipa does not wrap.

Index

Constants

View Source
const (
	CodeVersion              = 901
	CodeCommand              = 905
	CodeReferer              = 911
	CodeACI                  = 2100
	CodeRequirement          = 3007
	CodeValidation           = 3009
	CodeNotFound             = 4001
	CodeDuplicateEntry       = 4002
	CodeAlreadyActive        = 4009
	CodeAlreadyInactive      = 4010
	CodeNotGroupMember       = 4012
	CodeAlreadyGroupMember   = 4014
	CodeAttrValueNotFound    = 4026
	CodeAlreadyContainsValue = 4038
	CodeEmptyModlist         = 4202
	CodeDatabase             = 4203
)

FreeIPA error codes (ipalib.errors).

View Source
const (
	DefaultKerbConf   = "/etc/krb5.conf"
	IpaClientVersion  = "2.237"
	IpaDatetimeFormat = "20060102150405Z"
)
View Source
const (
	AlgorithmSHA1   = "sha1"
	AlgorithmSHA256 = "sha256"
	AlgorithmSHA384 = "sha384"
	AlgorithmSHA512 = "sha512"
)

OTP Token hash Algorithms supported by FreeIPA

View Source
const (
	TokenTypeTOTP = "totp"
	TokenTypeHOTP = "hotp"
)

OTP Token types supported by FreeIPA

Variables

View Source
var (
	ErrNotFound       = &IpaError{Code: CodeNotFound, Name: "NotFound", Message: "not found"}
	ErrDuplicateEntry = &IpaError{Code: CodeDuplicateEntry, Name: "DuplicateEntry", Message: "entry already exists"}
	ErrACI            = &IpaError{Code: CodeACI, Name: "ACIError", Message: "insufficient access"}
	ErrEmptyModlist   = &IpaError{Code: CodeEmptyModlist, Name: "EmptyModlist", Message: "no modifications to be performed"}
)

Sentinels for common FreeIPA errors. They are matched with errors.Is by code only; any other code is available through errors.As and IpaError.Code.

View Source
var (
	// ErrPasswordPolicy is returned when a password does not conform to the password policy
	ErrPasswordPolicy = errors.New("password does not conform to policy")

	// ErrInvalidPassword is returned when a password is invalid
	ErrInvalidPassword = errors.New("invalid current password")

	// ErrExpiredPassword is returned when a password is expired
	ErrExpiredPassword = errors.New("password expired")

	// ErrUnauthorized is returned when user is not authorized
	ErrUnauthorized = errors.New("unauthorized")

	// ErrUserExists is returned when user account already exists. UserAdd
	// returns it for FreeIPA's DuplicateEntry (4002).
	ErrUserExists = errors.New("user exists")
)

Functions

func ParseDateTime

func ParseDateTime(str string) time.Time

Parse a FreeIPA datetime. Datetimes in FreeIPA are returned using a class-hint system. Values are stored as an array with a single element indicating the type and value, for example, '[{"__datetime__": "YYYY-MM-DDTHH:MM:SSZ"]}'

Types

type Client

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

FreeIPA Client

Methods with a Context suffix bound the HTTP request with the given context. Kerberos login and SPNEGO header generation are not cancellable (gokrb5 has no context support), so Login, LoginWithKeytab and LoginFromCCache have no Context twins.

func NewClient

func NewClient(host, realm string) *Client

New IPA Client with host and realm

func NewClientCustomHttp

func NewClientCustomHttp(host, realm string, httpClient *http.Client) *Client

New IPA Client with host, realm and custom http client

func NewDefaultClient

func NewDefaultClient() *Client

New default IPA Client using host and realm from /etc/ipa/default.conf

func NewDefaultClientWithSession

func NewDefaultClientWithSession(sessionID string) *Client

New default IPA Client with existing sessionID using host and realm from /etc/ipa/default.conf

func (*Client) AddOTPToken

func (c *Client) AddOTPToken(token *OTPToken) (*OTPToken, error)

Add OTP token. Returns new OTPToken

func (*Client) AddOTPTokenContext added in v0.2.0

func (c *Client) AddOTPTokenContext(ctx context.Context, token *OTPToken) (*OTPToken, error)

AddOTPTokenContext is like AddOTPToken but bounds the request with ctx.

func (*Client) ChangePassword

func (c *Client) ChangePassword(username, oldPasswd, newPasswd, otpcode string) error

Change user password. This will run the passwd ipa command. Optionally provide an OTP if required

func (*Client) ChangePasswordContext added in v0.2.0

func (c *Client) ChangePasswordContext(ctx context.Context, username, oldPasswd, newPasswd, otpcode string) error

ChangePasswordContext is like ChangePassword but bounds the request with ctx.

func (*Client) ClearSession

func (c *Client) ClearSession()

Clears out FreeIPA session id

func (*Client) DisableOTPToken

func (c *Client) DisableOTPToken(tokenUUID string) error

Disable OTP token.

func (*Client) DisableOTPTokenContext added in v0.2.0

func (c *Client) DisableOTPTokenContext(ctx context.Context, tokenUUID string) error

DisableOTPTokenContext is like DisableOTPToken but bounds the request with ctx.

func (*Client) EnableOTPToken

func (c *Client) EnableOTPToken(tokenUUID string) error

Enable OTP token.

func (*Client) EnableOTPTokenContext added in v0.2.0

func (c *Client) EnableOTPTokenContext(ctx context.Context, tokenUUID string) error

EnableOTPTokenContext is like EnableOTPToken but bounds the request with ctx.

func (*Client) FetchOTPTokens

func (c *Client) FetchOTPTokens(owner string) ([]*OTPToken, error)

Fetch OTP tokens by owner.

func (*Client) FetchOTPTokensContext added in v0.2.0

func (c *Client) FetchOTPTokensContext(ctx context.Context, owner string) ([]*OTPToken, error)

FetchOTPTokensContext is like FetchOTPTokens but bounds the request with ctx.

func (*Client) Host

func (c *Client) Host() string

Returns FreeIPA server hostname

func (*Client) Login

func (c *Client) Login(username, password string) error

Login to FreeIPA using local kerberos login username and password

func (*Client) LoginFromCCache

func (c *Client) LoginFromCCache(cpath string) error

Login to FreeIPA using credentials cache

func (*Client) LoginWithKeytab

func (c *Client) LoginWithKeytab(ktab, username string) error

Login to FreeIPA using local kerberos login with keytab and username

func (*Client) Ping

func (c *Client) Ping() (*Response, error)

Ping FreeIPA server to check connection

func (*Client) PingContext added in v0.2.0

func (c *Client) PingContext(ctx context.Context) (*Response, error)

PingContext is like Ping but bounds the request with ctx.

func (*Client) RPC added in v0.2.0

func (c *Client) RPC(method string, args []string, options Options) (*Response, error)

RPC calls any FreeIPA command, an escape hatch for commands goipa does not wrap. It uses the client's HTTP client, session or Kerberos credentials and API version. A FreeIPA failure is returned as a bare *IpaError. options is not modified; a "version" in options wins over IpaClientVersion.

func (*Client) RPCContext added in v0.2.0

func (c *Client) RPCContext(ctx context.Context, method string, args []string, options Options) (*Response, error)

RPCContext is like RPC but ends the request when ctx is done.

func (*Client) Realm

func (c *Client) Realm() string

Returns FreeIPA realm

func (*Client) RemoteLogin

func (c *Client) RemoteLogin(uid, passwd string) error

Login to FreeIPA using web API with uid/passwd and set the FreeIPA session id on the client for subsequent requests.

func (*Client) RemoteLoginContext added in v0.2.0

func (c *Client) RemoteLoginContext(ctx context.Context, uid, passwd string) error

RemoteLoginContext is like RemoteLogin but bounds the request with ctx.

func (*Client) RemoveOTPToken

func (c *Client) RemoveOTPToken(tokenUUID string) error

Remove OTP token

func (*Client) RemoveOTPTokenContext added in v0.2.0

func (c *Client) RemoveOTPTokenContext(ctx context.Context, tokenUUID string) error

RemoveOTPTokenContext is like RemoveOTPToken but bounds the request with ctx.

func (*Client) ResetPassword

func (c *Client) ResetPassword(username string) (string, error)

Reset user password and return new random password

func (*Client) ResetPasswordContext added in v0.2.0

func (c *Client) ResetPasswordContext(ctx context.Context, username string) (string, error)

ResetPasswordContext is like ResetPassword but bounds the request with ctx.

func (*Client) SessionID

func (c *Client) SessionID() string

Return current FreeIPA sessionID

func (*Client) SetAuthTypes

func (c *Client) SetAuthTypes(username string, types []string) error

Update user authentication types.

func (*Client) SetAuthTypesContext added in v0.2.0

func (c *Client) SetAuthTypesContext(ctx context.Context, username string, types []string) error

SetAuthTypesContext is like SetAuthTypes but bounds the request with ctx.

func (*Client) SetPassword

func (c *Client) SetPassword(username, oldPasswd, newPasswd, otpcode string) error

Set user password. In FreeIPA when a password is first set or when a password is later reset it is marked as immediately expired and requires the owner to perform a password change. See here https://www.freeipa.org/page/New_Passwords_Expired for more details. This function exists to circumvent the "new passwords expired" feature of FreeIPA and allow an administrator to set a new password for a user without it being expired. This is acheived, for example, by first calling ResetPassword() then immediately calling this function. *WARNING* See https://www.freeipa.org/page/Self-Service_Password_Reset for security issues and possible weaknesses of this approach.

func (*Client) SetPasswordContext added in v0.2.0

func (c *Client) SetPasswordContext(ctx context.Context, username, oldPasswd, newPasswd, otpcode string) error

SetPasswordContext is like SetPassword but bounds the request with ctx.

func (*Client) SetSessionID added in v0.2.0

func (c *Client) SetSessionID(sessionID string)

SetSessionID restores a session saved from SessionID (for example in a web session store) on any client. An empty string clears it.

func (*Client) StickySession

func (c *Client) StickySession(enable bool)

Set stick sessions.

func (*Client) UserAdd

func (c *Client) UserAdd(user *User, random bool) (*User, error)

Add new user. If random is true a random password will be created for the user. Note this requires "User Administrators" Privilege in FreeIPA.

func (*Client) UserAddContext added in v0.2.0

func (c *Client) UserAddContext(ctx context.Context, user *User, random bool) (*User, error)

UserAddContext is like UserAdd but bounds the request with ctx.

func (*Client) UserAddWithPassword

func (c *Client) UserAddWithPassword(user *User, password string) (*User, error)

Add new user and set password. Note this requires "User Administrators" Privilege in FreeIPA.

func (*Client) UserAddWithPasswordContext added in v0.2.0

func (c *Client) UserAddWithPasswordContext(ctx context.Context, user *User, password string) (*User, error)

UserAddWithPasswordContext is like UserAddWithPassword but bounds the request with ctx.

func (*Client) UserDelete

func (c *Client) UserDelete(preserve, stopOnError bool, usernames ...string) error

Delete user. If preserve is false the user will be permanetly deleted, if true the users is moved to the Delete container. If stopOnError is false the operation will be in continuous mode otherwise it will stop on errors

func (*Client) UserDeleteContext added in v0.2.0

func (c *Client) UserDeleteContext(ctx context.Context, preserve, stopOnError bool, usernames ...string) error

UserDeleteContext is like UserDelete but bounds the request with ctx.

func (*Client) UserDisable

func (c *Client) UserDisable(username string) error

Disable User Account

func (*Client) UserDisableContext added in v0.2.0

func (c *Client) UserDisableContext(ctx context.Context, username string) error

UserDisableContext is like UserDisable but bounds the request with ctx.

func (*Client) UserEnable

func (c *Client) UserEnable(username string) error

Enable User Account

func (*Client) UserEnableContext added in v0.2.0

func (c *Client) UserEnableContext(ctx context.Context, username string) error

UserEnableContext is like UserEnable but bounds the request with ctx.

func (*Client) UserFind

func (c *Client) UserFind(options Options) ([]*User, error)

Find users.

func (*Client) UserFindContext added in v0.2.0

func (c *Client) UserFindContext(ctx context.Context, options Options) ([]*User, error)

UserFindContext is like UserFind but bounds the request with ctx.

func (*Client) UserMod

func (c *Client) UserMod(user *User) (*User, error)

Modify user. Currently only modifies a subset of user attributes: mail, givenname, sn, homedirectory, loginshell, displayname, ipasshpubkey, telephonenumber, and mobile

func (*Client) UserModContext added in v0.2.0

func (c *Client) UserModContext(ctx context.Context, user *User) (*User, error)

UserModContext is like UserMod but bounds the request with ctx.

func (*Client) UserShow

func (c *Client) UserShow(username string) (*User, error)

Fetch user details by call the FreeIPA user-show method

func (*Client) UserShowContext added in v0.2.0

func (c *Client) UserShowContext(ctx context.Context, username string) (*User, error)

UserShowContext is like UserShow but bounds the request with ctx.

type HTTPError added in v0.2.0

type HTTPError struct {
	StatusCode int
	Status     string
}

HTTPError is returned when the server answers a JSON-RPC call with a status other than 200. HTTP 401 (for example an expired session) also matches ErrUnauthorized with errors.Is.

func (*HTTPError) Error added in v0.2.0

func (e *HTTPError) Error() string

Error returns the message used before HTTPError existed.

func (*HTTPError) Is added in v0.2.0

func (e *HTTPError) Is(target error) bool

Is reports whether target is ErrUnauthorized and the status is 401.

type IpaError

type IpaError struct {
	Message string
	Code    int
	Name    string `json:"name"`
	// Data is the raw JSON of the exception's keyword arguments, e.g.
	// {"reason":"..."}. A string so IpaError stays comparable.
	Data string `json:"data"`
}

FreeIPA error

func (*IpaError) Error

func (e *IpaError) Error() string

func (*IpaError) Is added in v0.2.0

func (e *IpaError) Is(target error) bool

Is reports whether target is an *IpaError with the same Code.

func (*IpaError) UnmarshalJSON added in v0.2.0

func (e *IpaError) UnmarshalJSON(b []byte) error

UnmarshalJSON keeps Data as raw JSON text; Message and Code still match the "message" and "code" keys case-insensitively.

type Message added in v0.2.0

type Message struct {
	Type    string          `json:"type"`
	Name    string          `json:"name"`
	Message string          `json:"message"`
	Code    int             `json:"code"`
	Data    json.RawMessage `json:"data"`
}

Message is a server warning attached to a FreeIPA result.

type OTPToken

type OTPToken struct {
	DN          string    `json:"dn"`
	UUID        string    `json:"ipatokenuniqueid"`
	Algorithm   string    `json:"ipatokenotpalgorithm"`
	Digits      int       `json:"ipatokenotpdigits"`
	Owner       string    `json:"ipatokenowner"`
	TimeStep    int       `json:"ipatokentotptimestep"`
	ClockOffest int       `json:"ipatokentotpclockoffset"`
	ManagedBy   string    `json:"managedby_user"`
	Enabled     bool      `json:"-"`
	Type        string    `json:"type"`
	URI         string    `json:"uri"`
	Description string    `json:"description"`
	Vendor      string    `json:"ipatokenvendor"`
	Model       string    `json:"ipatokenmodel"`
	Serial      string    `json:"ipatokenserial"`
	NotBefore   time.Time `json:"ipatokennotbefore"`
	NotAfter    time.Time `json:"ipatokennotafter"`
}

OTPToken encapsulates FreeIPA otptokens

var DefaultTOTPToken *OTPToken = &OTPToken{
	Type:      TokenTypeTOTP,
	Algorithm: AlgorithmSHA1,
	Digits:    6,
	TimeStep:  30,
}

func (*OTPToken) DisplayName

func (t *OTPToken) DisplayName() string

type Options

type Options map[string]interface{}

FreeIPA api options map

type Response

type Response struct {
	Error     *IpaError `json:"error"`
	ID        int       `json:"id"`
	Principal string    `json:"principal"`
	Version   string    `json:"version"`
	Result    *Result   `json:"result"`
}

Response returned from a FreeIPA JSON rpc call

type Result

type Result struct {
	Summary   string          `json:"summary"`
	Value     interface{}     `json:"value"`
	Data      json.RawMessage `json:"result"`
	Count     int             `json:"count"`
	Truncated bool            `json:"truncated"`
	Messages  []Message       `json:"messages"`
	Completed int             `json:"completed"`
	Failed    json.RawMessage `json:"failed"`
	// Raw is the whole FreeIPA result object, for shapes without a "result"
	// key such as hbactest.
	Raw json.RawMessage `json:"-"`
}

Result returned from a FreeIPA JSON rpc call

func (*Result) UnmarshalJSON added in v0.2.0

func (r *Result) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the result and keeps a copy of the raw object in Raw.

type SSHAuthorizedKey

type SSHAuthorizedKey struct {
	Comment     string
	Options     []string
	PublicKey   ssh.PublicKey
	Fingerprint string
}

SSH Public Key

func NewSSHAuthorizedKey

func NewSSHAuthorizedKey(in string) (*SSHAuthorizedKey, error)

func (*SSHAuthorizedKey) MarshalJSON

func (k *SSHAuthorizedKey) MarshalJSON() ([]byte, error)

func (*SSHAuthorizedKey) String

func (k *SSHAuthorizedKey) String() string

type User

type User struct {
	UUID             string              `json:"ipauniqueid"`
	DN               string              `json:"dn"`
	First            string              `json:"givenname"`
	Last             string              `json:"sn"`
	DisplayName      string              `json:"displayname"`
	Principal        string              `json:"krbprincipalname"`
	Username         string              `json:"uid"`
	Uid              string              `json:"uidnumber"`
	Gid              string              `json:"gidnumber"`
	Groups           []string            `json:"memberof_group"`
	SSHAuthKeys      []*SSHAuthorizedKey `json:"ipasshpubkey"`
	AuthTypes        []string            `json:"ipauserauthtype"`
	HasKeytab        bool                `json:"has_keytab"`
	HasPassword      bool                `json:"has_password"`
	Locked           bool                `json:"nsaccountlock"`
	Preserved        bool                `json:"preserved"`
	HomeDir          string              `json:"homedirectory"`
	Email            string              `json:"mail"`
	TelephoneNumber  string              `json:"telephonenumber"`
	Mobile           string              `json:"mobile"`
	Shell            string              `json:"loginshell"`
	Category         string              `json:"userclass"`
	SudoRules        []string            `json:"memberofindirect_sudorule"`
	HbacRules        []string            `json:"memberofindirect_hbacrule"`
	LastPasswdChange time.Time           `json:"krblastpwdchange"`
	PasswdExpire     time.Time           `json:"krbpasswordexpiration"`
	PrincipalExpire  time.Time           `json:"krbprincipalexpiration"`
	LastLoginSuccess time.Time           `json:"krblastsuccessfulauth"`
	LastLoginFail    time.Time           `json:"krblastfailedauth"`
	RandomPassword   string              `json:"randompassword"`
}

User encapsulates user data returned from ipa user commands

func (*User) AddSSHAuthorizedKey

func (u *User) AddSSHAuthorizedKey(key *SSHAuthorizedKey)

Add ssh authorized key

func (*User) FormatSSHAuthorizedKeys

func (u *User) FormatSSHAuthorizedKeys() []string

Format ssh authorized keys

func (*User) HasGroup

func (u *User) HasGroup(group string) bool

Returns true if the User is in group

func (*User) OTPOnly

func (u *User) OTPOnly() bool

Returns true if OTP is the only authentication type enabled

func (*User) RemoveSSHAuthorizedKey

func (u *User) RemoveSSHAuthorizedKey(fingerprint string)

Removes ssh authorized key

func (*User) ToOptions

func (u *User) ToOptions() Options

Jump to

Keyboard shortcuts

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