ec2macosinit

package
v0.0.0-...-e45a68f Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2023 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ConfigurationManagementWarning is a header warning for sshd_config
	ConfigurationManagementWarning = "" /* 169-byte string literal not displayed */
	// InlineWarning is a warning line for each entry to help encourage users to avoid doing the risky configuration change
	InlineWarning = "" /* 164-byte string literal not displayed */
	// DefaultsCmd is the path to the script edit macOS defaults
	DefaultsCmd = "/usr/bin/defaults"
	// DefaultsRead is the command to read from a plist
	DefaultsRead = "read"
	// DefaultsReadType is the command to read the type of a parameter from a plist
	DefaultsReadType = "read-type"
	// DefaultsWrite is the command to write a value of a parameter to a plist
	DefaultsWrite = "write"
)
View Source
const (
	// PasswordLength is the default number of characters that the auto-generated password should be
	PasswordLength = 25
	// DsclPath is the default path for the dscl utility needed for the functions in this file
	DsclPath = "/usr/bin/dscl"
)
View Source
const PerBootFatalLimit = 100

Number of runs resulting in fatal exits in a single boot before giving up

Variables

This section is empty.

Functions

This section is empty.

Types

type CommandModule

type CommandModule struct {
	Cmd             []string `toml:"Cmd"`
	RunAsUser       string   `toml:"RunAsUser"`
	EnvironmentVars []string `toml:"EnvironmentVars"`
}

CommandModule contains contains all necessary configuration fields for running a Command module.

func (*CommandModule) Do

func (c *CommandModule) Do(ctx *ModuleContext) (message string, err error)

Do for CommandModule runs a command with the values set in the config file.

type FatalCount

type FatalCount struct {
	Count int `json:"count"`
}

FatalCount contains a Count for tracking the number of Fatal exits for this boot

func (*FatalCount) IncrementFatalCount

func (r *FatalCount) IncrementFatalCount() (err error)

IncrementFatalCount takes the current count, increments it, and saves to the temporary file.

type History

type History struct {
	InstanceID      string          `json:"instanceID"`
	RunTime         time.Time       `json:"runTime"`
	ModuleHistories []ModuleHistory `json:"moduleHistory"`
	Version         int             `json:"version"`
}

History contains an instance ID, run time and a slice of individual module histories.

type HistoryError

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

HistoryError wraps a normal error and gives the caller insight into the type of error. The caller can check the type of error and handle different types of error differently. Currently HistoryError only handles errors for invalid JSON but the struct is flexible and can be adjusted to handle several different errors differently.

func (HistoryError) Error

func (h HistoryError) Error() string

func (HistoryError) Unwrap

func (h HistoryError) Unwrap() error

type IMDSConfig

type IMDSConfig struct {
	InstanceID string
	// contains filtered or unexported fields
}

IMDS config contains the current instance ID and a place for the IMDSv2 token to be stored. Using IMDSv2: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html#instance-metadata-v2-how-it-works

func (*IMDSConfig) UpdateInstanceID

func (i *IMDSConfig) UpdateInstanceID() (err error)

UpdateInstanceID is a wrapper for getIMDSProperty that gets the current instance ID for the attached config.

type InitConfig

type InitConfig struct {
	HistoryFilename   string
	HistoryPath       string
	IMDS              IMDSConfig
	InstanceHistory   []History
	Log               *Logger
	Modules           []Module `toml:"Module"`
	ModulesByPriority [][]Module
	FatalCounts       FatalCount
}

InitConfig contains all fields expected from an init.toml file as well as things shared by all parts of the application.

func (*InitConfig) CreateDirectories

func (c *InitConfig) CreateDirectories() (err error)

CreateDirectories creates the instance directory, if it doesn't exist and a directory for the running instance.

func (*InitConfig) GetInstanceHistory

func (c *InitConfig) GetInstanceHistory() (err error)

GetInstanceHistory takes a path to instance history directory and a file name for history files and searches for any files that match. Then, for each file, it calls readHistoryFile() to read the file and add it to the InstanceHistory struct.

func (*InitConfig) PrioritizeModules

func (c *InitConfig) PrioritizeModules() (err error)

PrepareModules takes all modules and sorts them according to priority into the ModulesByPriority slice.

func (*InitConfig) ReadConfig

func (c *InitConfig) ReadConfig(fileLocation string) (err error)

ReadConfig reads the configuration file and decodes it into the InitConfig struct.

func (*InitConfig) RetriesExceeded

func (c *InitConfig) RetriesExceeded() (exceeded bool, err error)

RetriesExceeded checks if the number of previous fatal exits exceeds the limit.

func (*InitConfig) ValidateAndIdentify

func (c *InitConfig) ValidateAndIdentify() (err error)

ValidateConfig validates all modules and identifies type.

func (*InitConfig) WriteHistoryFile

func (c *InitConfig) WriteHistoryFile() (err error)

WriteHistoryFile takes ModulesByPriority and writes it to a given history path and filename as JSON.

type Logger

type Logger struct {
	LogToStdout    bool
	LogToSystemLog bool
	Tag            string
	SystemLog      *syslog.Writer
}

Logger contains booleans for where to log, a tag used in syslog and the syslog Writer itself.

func NewLogger

func NewLogger(tag string, systemLog bool, stdout bool) (logger *Logger, err error)

NewLogger creates a new logger. Logger writes using the LOG_LOCAL0 facility by default if system logging is enabled.

func (*Logger) Error

func (l *Logger) Error(v ...interface{})

Error writes an error to stdout and/or the system log.

func (*Logger) Errorf

func (l *Logger) Errorf(format string, v ...interface{})

Errorf writes a formatted error to stdout and/or the system log.

func (*Logger) Fatal

func (l *Logger) Fatal(e int, v ...interface{})

Fatal writes an error to stdout and/or the system log then exits with requested code.

func (*Logger) Fatalf

func (l *Logger) Fatalf(e int, format string, v ...interface{})

Fatalf writes a formatted error to stdout and/or the system log then exits with requested code.

func (*Logger) Info

func (l *Logger) Info(v ...interface{})

Info writes info to stdout and/or the system log.

func (*Logger) Infof

func (l *Logger) Infof(format string, v ...interface{})

Infof writes formatted info to stdout and/or the system log.

func (*Logger) Warn

func (l *Logger) Warn(v ...interface{})

Warn writes a warning to stdout and/or the system log.

func (*Logger) Warnf

func (l *Logger) Warnf(format string, v ...interface{})

Warnf writes a formatted warning to stdout and/or the system log.

type MOTDModule

type MOTDModule struct {
	UpdateName bool `toml:"UpdateName"` // UpdateName specifies if the MOTDModule should run or not
}

MOTDModule contains all necessary configuration fields for running a MOTD module.

func (*MOTDModule) Do

func (c *MOTDModule) Do(ctx *ModuleContext) (message string, err error)

Do for MOTDModule gets the OS's current product version and maps the name of the OS to that version. It then writes a string with the OS name and product version to /etc/motd.

type ModifyDefaults

type ModifyDefaults struct {
	Plist     string `toml:"plist"`
	Parameter string `toml:"parameter"`
	Type      string `toml:"type"`
	Value     string `toml:"value"`
}

ModifyDefaults contains the necessary values to change a parameter in a given plist

type ModifySysctl

type ModifySysctl struct {
	Value string `toml:"value"`
}

ModifySysctl contains sysctl values we want to modify

type Module

type Module struct {
	Type                 string
	Success              bool
	Name                 string               `toml:"Name"`
	PriorityGroup        int                  `toml:"PriorityGroup"`
	FatalOnError         bool                 `toml:"FatalOnError"`
	RunOnce              bool                 `toml:"RunOnce"`
	RunPerBoot           bool                 `toml:"RunPerBoot"`
	RunPerInstance       bool                 `toml:"RunPerInstance"`
	CommandModule        CommandModule        `toml:"Command"`
	MOTDModule           MOTDModule           `toml:"MOTD"`
	SSHKeysModule        SSHKeysModule        `toml:"SSHKeys"`
	UserDataModule       UserDataModule       `toml:"UserData"`
	NetworkCheckModule   NetworkCheckModule   `toml:"NetworkCheck"`
	SystemConfigModule   SystemConfigModule   `toml:"SystemConfig"`
	UserManagementModule UserManagementModule `toml:"UserManagement"`
}

Module contains a few fields common to all Module types and containers for the configuration of any potential module type.

func (*Module) ShouldRun

func (m *Module) ShouldRun(instanceID string, history []History) (shouldRun bool)

ShouldRun determines if a module should be run, given a current instance ID and history. There are three cases:

  1. RunPerBoot - The module should run every boot, no matter what. The simplest case.
  2. RunPerInstance - The module should run once on every instance. Here we must look for the current instance ID in the instance history and if found, compare the current module's key with all successfully run keys. If not found, run the module. If found and unsuccessful, run the module. If found and successful, skip.
  3. RunOnce - The module should run once, ever. The process here is similar to RunPerInstance except the key must be searched for in every instance history. If not found, run the module. If found and unsuccessful, run the module. If found and successful, skip.

type ModuleContext

type ModuleContext struct {
	Logger        *Logger
	IMDS          *IMDSConfig
	BaseDirectory string
}

ModuleContext contains fields that may need to be passed to the Do function for modules.

func (ModuleContext) InstanceHistoryPath

func (m ModuleContext) InstanceHistoryPath() string

InstanceHistoryPath provides the history storage path for the current instance.

type ModuleHistory

type ModuleHistory struct {
	Key     string `json:"key"`
	Success bool   `json:"success"`
}

ModuleHistory contains a key of the configuration struct for future comparison and whether that run was successful.

type NetworkCheckModule

type NetworkCheckModule struct {
	PingCount int `toml:"PingCount"`
}

NetworkCheckModule contains contains all necessary configuration fields for running a NetworkCheck module.

func (*NetworkCheckModule) Do

func (c *NetworkCheckModule) Do(ctx *ModuleContext) (message string, err error)

Do for NetworkCheck Module gets the default gateway and pings it to check if the network is up.

type SSHKeysModule

type SSHKeysModule struct {
	DedupKeys               bool     `toml:"DedupKeys"`
	GetIMDSOpenSSHKey       bool     `toml:"GetIMDSOpenSSHKey"`
	StaticOpenSSHKeys       []string `toml:"StaticOpenSSHKeys"`
	OverwriteAuthorizedKeys bool     `toml:"OverwriteAuthorizedKeys"`
	User                    string   `toml:"User"`
}

SSHKeysModule contains all necessary configuration fields for running an SSH Keys module.

func (*SSHKeysModule) Do

func (c *SSHKeysModule) Do(ctx *ModuleContext) (message string, err error)

Do for the SSHKeysModule does some brief validation, gets the IMDS key (if configured), appends static keys (if configured), and then writes them to the authorized_keys file for the user.

type SystemConfigModule

type SystemConfigModule struct {
	SecureSSHDConfig *bool            `toml:"secureSSHDConfig"`
	ModifySysctl     []ModifySysctl   `toml:"Sysctl"`
	ModifyDefaults   []ModifyDefaults `toml:"Defaults"`
}

SystemConfigModule contains all necessary configuration fields for running a System Configuration module.

func (*SystemConfigModule) Do

func (c *SystemConfigModule) Do(ctx *ModuleContext) (message string, err error)

Do for the SystemConfigModule modifies system configuration such as sysctl, plist defaults, and secures the SSHD configuration file.

type UserDataModule

type UserDataModule struct {
	// ExecuteUserData must be set to `true` for the userdata script contents to
	// be executed.
	ExecuteUserData bool `toml:"ExecuteUserData"`
}

UserDataModule contains contains all necessary configuration fields for running a User Data module.

func (*UserDataModule) Do

func (m *UserDataModule) Do(mctx *ModuleContext) (message string, err error)

Do fetches userdata and writes it to a file in the instance history. The written script is then executed when ExecuteUserData is true.

type UserManagementModule

type UserManagementModule struct {
	RandomizePassword bool   `toml:"RandomizePassword"`
	User              string `toml:"User"`
}

UserManagementModule contains the necessary values to run a User Management Module

func (*UserManagementModule) Do

func (c *UserManagementModule) Do(ctx *ModuleContext) (message string, err error)

Do for the UserManagementModule is the primary entry point for the User Management Module.

Jump to

Keyboard shortcuts

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