Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return actionable error message when enrolling #6144

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
1eb05ab
enhancement(4889): updated enroll command to reexec the command if th…
kaanyalti Nov 25, 2024
e39d270
enhancement(4889): added savepassword function
kaanyalti Nov 26, 2024
5c77aa9
enhancement(4889): removed user impersonation, implemented noop for w…
kaanyalti Nov 26, 2024
74b256f
enhancement(4889): added changelog
kaanyalti Nov 26, 2024
3cadda9
enhancement(4889): added windows implementation
kaanyalti Nov 26, 2024
93ba22c
enhancement(4889): added license headers
kaanyalti Nov 26, 2024
e150906
enhancement(4889): update test case to execute different commands bas…
kaanyalti Nov 27, 2024
999f7ae
enhancement(4889): ran mage clean
kaanyalti Nov 27, 2024
a1ef893
enhancement(4889): updated function name, updated integration tests
kaanyalti Dec 2, 2024
b26256c
enhancmenet(4889): updated function name
kaanyalti Dec 2, 2024
912e0b6
enhancement(4889): updated function name, fixed test assertions
kaanyalti Dec 2, 2024
df8b1bf
enhancement(4889): update error messages
kaanyalti Dec 5, 2024
50ac231
enhancement(4889): ran mage update
kaanyalti Dec 5, 2024
5c57d7d
enhancements(4889): fix integration test
kaanyalti Dec 5, 2024
adb6989
enhancement(4889): remove commented code
kaanyalti Dec 6, 2024
fc56d9f
enhancement(4889): commiting now, don't push though
kaanyalti Dec 6, 2024
4b77196
enhancement(4889): added windows unit test
kaanyalti Dec 6, 2024
cc07760
enhancement(4889): close test file
kaanyalti Dec 6, 2024
6492b43
enhancement(4889): updated isOwnerExec function, added tests
kaanyalti Dec 6, 2024
9243ae2
enchancement(4889): added log in test
kaanyalti Dec 6, 2024
729316a
enhancement(4889): remove unused types
kaanyalti Dec 6, 2024
06d62e1
enhancement(4889): added test for isOwnerExec for windows
kaanyalti Dec 6, 2024
c7a3a26
enhancement(4889): added unix tests, ran mage addLicenseHeaders
kaanyalti Dec 6, 2024
9c2fba8
enhancement(4889): added testisfileownerunix test
kaanyalti Dec 6, 2024
df5ddb7
enhancement(4889): added TestIsOwnerExecUnix test
kaanyalti Dec 6, 2024
0ab7181
enhancement(4889): updated test function name
kaanyalti Dec 6, 2024
5a3df58
enhancement(4889): set file ownership of the test file
kaanyalti Dec 6, 2024
e89e126
enhancement(4889): remove unnecessary change
kaanyalti Dec 6, 2024
9c67aea
enhancment(4889): updated iOwnerExec windows test
kaanyalti Dec 7, 2024
ab4e753
enhancement(4889): fix file creation in tests
kaanyalti Dec 7, 2024
1f66c83
Update internal/pkg/agent/cmd/enroll.go
kaanyalti Dec 11, 2024
8e05185
Update internal/pkg/agent/cmd/enroll_match_fileowner_windows.go
kaanyalti Dec 11, 2024
ffba277
Update internal/pkg/agent/cmd/enroll_match_fileowner_unix.go
kaanyalti Dec 11, 2024
81b3e60
enhancement(4889): updated summary and issue in changelog
kaanyalti Dec 11, 2024
f152fcc
enhancement(4889): updated variable name, wrap error when returning e…
kaanyalti Dec 11, 2024
f7a9367
enhancement(4889): added comments describing isOwnerExec. fixed type …
kaanyalti Dec 11, 2024
58b7e1e
enhancement(4889): refactored isOwnerExec return
kaanyalti Dec 11, 2024
4ef5ca7
enhancement(4889): differentiating between sid errors
kaanyalti Dec 11, 2024
65f6592
enhancment(4889): removed redundant unit tests
kaanyalti Dec 11, 2024
ce809c1
enhancement(4889): update command execution in integration tests
kaanyalti Dec 13, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Kind can be one of:
# - breaking-change: a change to previously-documented behavior
# - deprecation: functionality that is being removed in a later release
# - bug-fix: fixes a problem in a previous version
# - enhancement: extends functionality but does not break or fix existing behavior
# - feature: new functionality
# - known-issue: problems that we are aware of in a given version
# - security: impacts on the security of a product or a user’s deployment.
# - upgrade: important information for someone upgrading from a prior version
# - other: does not fit into any of the other categories
kind: enhancement

# Change summary; a 80ish characters long description of the change.
summary: Elastic agent returns an actionable error message when a the use trying to execute the enroll command is not the same as the onwer of the elastic-agent program files

# Long description; in case the summary is not enough to describe the change
# this field accommodate a description without length limits.
# NOTE: This field will be rendered only for breaking-change and known-issue kinds at the moment.
#description:

# Affected component; usually one of "elastic-agent", "fleet-server", "filebeat", "metricbeat", "auditbeat", "all", etc.
component: elastic-agent

# PR URL; optional; the PR number that added the changeset.
# If not present is automatically filled by the tooling finding the PR where this changelog fragment has been added.
# NOTE: the tooling supports backports, so it's able to fill the original PR number instead of the backport PR number.
# Please provide it if you are adding a fragment for a different PR.
pr: https://github.com/elastic/elastic-agent/pull/6144
# Issue URL; optional; the GitHub issue related to this changeset (either closes or is part of).
# If not present is automatically filled by the tooling with the issue linked to the PR number.
issue: https://github.com/elastic/elastic-agent/issues/4889
19 changes: 18 additions & 1 deletion internal/pkg/agent/cmd/enroll.go
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,24 @@ func enroll(streams *cli.IOStreams, cmd *cobra.Command) error {

fromInstall, _ := cmd.Flags().GetBool(fromInstallArg)

hasRoot, err := utils.HasRoot()
if err != nil {
return fmt.Errorf("checking if running with root/Administrator privileges: %w", err)
}
if hasRoot && !fromInstall {
binPath, err := os.Executable()
if err != nil {
return fmt.Errorf("error while getting executable path: %w", err)
}
isOwner, err := isOwnerExec(binPath)
if err != nil {
return fmt.Errorf("ran into an error while figuring out if user is allowed to execute the enroll command: %w", err)
}
if !isOwner {
return UserOwnerMismatchError
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On Windows you cannot actually open a shell as the elastic-agent-user so how would they be able to run enroll command on Windows as the elastic-agent-user.

Copy link
Contributor Author

@kaanyalti kaanyalti Dec 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can return an error message stating the fact that user cannot execute the command as admin for windows. Linux/mac error message can still mention running the command as the elastic-agent-user

}
}

pathConfigFile := paths.ConfigFile()
rawConfig, err := config.LoadFile(pathConfigFile)
if err != nil {
Expand Down Expand Up @@ -525,7 +543,6 @@ func enroll(streams *cli.IOStreams, cmd *cobra.Command) error {
pathConfigFile,
store,
)

if err != nil {
return err
}
Expand Down
59 changes: 59 additions & 0 deletions internal/pkg/agent/cmd/enroll_match_fileowner_unix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License 2.0;
// you may not use this file except in compliance with the Elastic License 2.0.

//go:build !windows

package cmd

import (
"fmt"
"os"
"strconv"
"syscall"

"github.com/elastic/elastic-agent/internal/pkg/agent/errors"
)

var UserOwnerMismatchError = errors.New("the command is executed as root but the program files are not owned by the root user. execute the command as the user that owns the program files")

func getFileOwner(filePath string) (string, error) {
fileInfo, err := os.Stat(filePath)
if err != nil {
return "", fmt.Errorf("failed to get file info: %w", err)
}

stat, ok := fileInfo.Sys().(*syscall.Stat_t)
if !ok {
return "", fmt.Errorf("failed to get system specific file info: %w", err)
}
return strconv.Itoa(int(stat.Uid)), nil
}

func getCurrentUser() (string, error) {
return strconv.Itoa(os.Geteuid()), nil
}

func isFileOwner(curUser string, fileOwner string) (bool, error) {
return curUser == fileOwner, nil
}

// Checks if the provided file is owned by the user that initiated the process
func isOwnerExec(filePath string) (bool, error) {
kaanyalti marked this conversation as resolved.
Show resolved Hide resolved
owner, err := getFileOwner(filePath)
if err != nil {
return false, fmt.Errorf("failed to get file owner: %w", err)
}

curUser, err := getCurrentUser()
if err != nil {
return false, fmt.Errorf("failed to get current user: %w", err)
}

isOwner, err := isFileOwner(curUser, owner)
if err != nil {
return false, fmt.Errorf("error while checking if current user is the file owner: %w", err)
}

return isOwner, nil
}
28 changes: 28 additions & 0 deletions internal/pkg/agent/cmd/enroll_match_fileowner_unix_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License 2.0;
// you may not use this file except in compliance with the Elastic License 2.0.

//go:build !windows

package cmd

import (
"os"
"path/filepath"
"testing"

"github.com/stretchr/testify/require"
)

func TestIsOwnerExecUnix(t *testing.T) {
path := t.TempDir()
fp := filepath.Join(path, "testfile")
fi, err := os.Create(fp)
require.NoError(t, err)
defer fi.Close()

isOwner, err := isOwnerExec(fp)
require.NoError(t, err)

require.True(t, isOwner)
}
92 changes: 92 additions & 0 deletions internal/pkg/agent/cmd/enroll_match_fileowner_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License 2.0;
// you may not use this file except in compliance with the Elastic License 2.0.

//go:build windows

package cmd

import (
"fmt"

"golang.org/x/sys/windows"

"github.com/elastic/elastic-agent/internal/pkg/agent/errors"
)

var UserOwnerMismatchError = errors.New("the command is executed as root but the program files are not owned by the root user.")

func getFileOwner(filePath string) (string, error) {
// Get security information of the file
sd, err := windows.GetNamedSecurityInfo(
filePath,
windows.SE_FILE_OBJECT,
windows.OWNER_SECURITY_INFORMATION,
)
if err != nil {
return "", fmt.Errorf("failed to get security info: %w", err)
}
owner, _, err := sd.Owner()
if err != nil {
return "", fmt.Errorf("failed to get security descriptor owner: %w", err)
}

return owner.String(), nil
}

// Helper to get the current user's SID
func getCurrentUser() (string, error) {
// Get the token for the current process
var token windows.Token
err := windows.OpenProcessToken(windows.CurrentProcess(), windows.TOKEN_QUERY, &token)
if err != nil {
return "", fmt.Errorf("failed to open process token: %w", err)
}
defer token.Close()

// Get the token use
tokenUser, err := token.GetTokenUser()
if err != nil {
return "", fmt.Errorf("failed to get token user: %w", err)
}

return tokenUser.User.Sid.String(), nil
}

func isFileOwner(curUser string, fileOwner string) (bool, error) {
var cSid *windows.SID
err := windows.ConvertStringSidToSid(windows.StringToUTF16Ptr(curUser), &cSid)
if err != nil {
return false, fmt.Errorf("failed to convert user SID string to SID: %w", err)
}

var fSid *windows.SID
err = windows.ConvertStringSidToSid(windows.StringToUTF16Ptr(fileOwner), &fSid)
if err != nil {
return false, fmt.Errorf("failed to convert file SID string to SID: %w", err)
}

isEqual := fSid.Equals(cSid)

return isEqual, nil
}

// Checks if the provided file is owned by the user that initiated the process
func isOwnerExec(filePath string) (bool, error) {
fileOwner, err := getFileOwner(filePath)
if err != nil {
return false, fmt.Errorf("getting file owner: %w", err)
}

user, err := getCurrentUser()
if err != nil {
return false, fmt.Errorf("ran into an error while retrieving current user: %w", err)
}

isOwner, err := isFileOwner(user, fileOwner)
if err != nil {
return false, fmt.Errorf("error while checking if current user is the file owner: %w", err)
}

return isOwner, nil
}
52 changes: 52 additions & 0 deletions internal/pkg/agent/cmd/enroll_match_fileowner_windows_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License 2.0;
// you may not use this file except in compliance with the Elastic License 2.0.

//go:build windows

package cmd

import (
"fmt"
"os"
"path/filepath"
"testing"

"github.com/stretchr/testify/require"
"golang.org/x/sys/windows"
)

func TestIsOwnerExecWindows(t *testing.T) {
path := t.TempDir()
fp := filepath.Join(path, "testfile")
fi, err := os.Create(fp)
require.NoError(t, err)
defer fi.Close()

var token windows.Token
err = windows.OpenProcessToken(windows.CurrentProcess(), windows.TOKEN_QUERY, &token)
require.NoError(t, err)
defer token.Close()

tokenUser, err := token.GetTokenUser()
require.NoError(t, err)

err = windows.SetNamedSecurityInfo(
fp,
windows.SE_FILE_OBJECT,
windows.OWNER_SECURITY_INFORMATION,
tokenUser.User.Sid,
nil,
nil,
nil,
)
require.NoError(t, err)

require.NoError(t, err)
defer fi.Close()

isOwner, err := isOwnerExec(fp)
require.NoError(t, err)

require.True(t, isOwner, fmt.Sprintf("expected isOwnerExec to return \"true\", received \"%v\"", isOwner))
}
38 changes: 30 additions & 8 deletions pkg/testing/tools/tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ func InstallAgentWithPolicy(ctx context.Context, t *testing.T,
installOpts atesting.InstallOpts,
agentFixture *atesting.Fixture,
kibClient *kibana.Client,
createPolicyReq kibana.AgentPolicy) (kibana.PolicyResponse, error) {
createPolicyReq kibana.AgentPolicy,
) (kibana.PolicyResponse, error) {
t.Helper()

// Create policy
Expand Down Expand Up @@ -85,21 +86,41 @@ func InstallAgentForPolicy(ctx context.Context, t *testing.T,
installOpts atesting.InstallOpts,
agentFixture *atesting.Fixture,
kibClient *kibana.Client,
policyID string) error {
t.Helper()
policyID string,
) error {
enrollmentToken, err := CreateEnrollmentToken(t, ctx, kibClient, policyID)
if err != nil {
return fmt.Errorf("failed to create enrollment token while preparing to install agent for policy: %w", err)
}
return InstallAgentForPolicyWithToken(ctx, t, installOpts, agentFixture, kibClient, policyID, enrollmentToken)
}

func CreateEnrollmentToken(t *testing.T, ctx context.Context, kibClient *kibana.Client, policyID string) (kibana.CreateEnrollmentAPIKeyResponse, error) {
// Create enrollment API key
createEnrollmentAPIKeyReq := kibana.CreateEnrollmentAPIKeyRequest{
PolicyID: policyID,
}

t.Logf("Creating enrollment API key...")
enrollmentToken, err := kibClient.CreateEnrollmentAPIKey(ctx, createEnrollmentAPIKeyReq)
if err != nil {
return kibana.CreateEnrollmentAPIKeyResponse{}, fmt.Errorf("failed creating enrollment API key: %w", err)
}

return enrollmentToken, nil
}

func InstallAgentForPolicyWithToken(ctx context.Context, t *testing.T,
installOpts atesting.InstallOpts,
agentFixture *atesting.Fixture,
kibClient *kibana.Client,
policyID string,
enrollmentToken kibana.CreateEnrollmentAPIKeyResponse,
) error {
t.Helper()

if installOpts.EnrollmentToken == "" {
t.Logf("Creating enrollment API key...")
enrollmentToken, err := kibClient.CreateEnrollmentAPIKey(ctx, createEnrollmentAPIKeyReq)
if err != nil {
return fmt.Errorf("failed creating enrollment API key: %w", err)
}

installOpts.EnrollmentToken = enrollmentToken.APIKey
}

Expand Down Expand Up @@ -138,5 +159,6 @@ func InstallAgentForPolicy(ctx context.Context, t *testing.T,
10*time.Second,
"Elastic Agent status is not online",
)

return nil
}
Loading
Loading