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

Generate audit log entries on unauthorized access attempts #375

Merged
merged 5 commits into from
Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
27 changes: 24 additions & 3 deletions cmd/api/src/api/middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ import (
"strings"
"time"

"github.com/specterops/bloodhound/log"
"github.com/specterops/bloodhound/src/ctx"
"github.com/specterops/bloodhound/src/database"

"github.com/gofrs/uuid"
"github.com/gorilla/mux"
Expand All @@ -34,6 +36,22 @@ import (
"github.com/specterops/bloodhound/headers"
)

func auditLogUnauthorizedAccess(db database.Database, request *http.Request) {
// Ignore read logs as they are less likely to occur from malicious access
if request.Method != "GET" {
if err := db.AppendAuditLog(
request.Context(),
model.AuditEntry{
Action: "UnauthorizedAccessAttempt",
Model: model.AuditData{"endpoint": request.Method + " " + request.URL.Path},
Status: model.AuditStatusFailure,
},
); err != nil {
log.Errorf("error creating audit log for unauthorized access: %s", err.Error())
}
}
}

func parseAuthorizationHeader(request *http.Request) (string, string, *api.ErrorWrapper) {
if authorizationHeader := request.Header.Get(headers.Authorization.String()); authorizationHeader == "" {
return "", "", nil
Expand Down Expand Up @@ -101,12 +119,13 @@ func AuthMiddleware(authenticator api.Authenticator) mux.MiddlewareFunc {

// PermissionsCheckAll is a middleware func generator that returns a http.Handler which closes around a list of
// permissions that an actor must have in the request auth context to access the wrapped http.Handler.
func PermissionsCheckAll(authorizer auth.Authorizer, permissions ...model.Permission) mux.MiddlewareFunc {
func PermissionsCheckAll(db database.Database, authorizer auth.Authorizer, permissions ...model.Permission) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
if bhCtx := ctx.FromRequest(request); !bhCtx.AuthCtx.Authenticated() {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusUnauthorized, "not authenticated", request), response)
} else if !authorizer.AllowsAllPermissions(bhCtx.AuthCtx, permissions) {
auditLogUnauthorizedAccess(db, request)
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusForbidden, "not authorized", request), response)
} else {
next.ServeHTTP(response, request)
Expand All @@ -117,12 +136,13 @@ func PermissionsCheckAll(authorizer auth.Authorizer, permissions ...model.Permis

// PermissionsCheckAtLeastOne is a middleware func generator that returns a http.Handler which closes around a list of
// permissions that an actor must have at least one in the request auth context to access the wrapped http.Handler.
func PermissionsCheckAtLeastOne(authorizer auth.Authorizer, permissions ...model.Permission) mux.MiddlewareFunc {
func PermissionsCheckAtLeastOne(db database.Database, authorizer auth.Authorizer, permissions ...model.Permission) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
if bhCtx := ctx.FromRequest(request); !bhCtx.AuthCtx.Authenticated() {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusUnauthorized, "not authenticated", request), response)
} else if !authorizer.AllowsAtLeastOnePermission(bhCtx.AuthCtx, permissions) {
auditLogUnauthorizedAccess(db, request)
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusForbidden, "not authorized", request), response)
} else {
next.ServeHTTP(response, request)
Expand Down Expand Up @@ -160,7 +180,7 @@ func RequireUserId() mux.MiddlewareFunc {
//
// An actor may operate on other actor entities if they have the permission "permission://auth/ManageUsers." If not the
// actor may only exercise auth management calls on auth entities that are explicitly owned by the actor.
func AuthorizeAuthManagementAccess(permissions auth.PermissionSet, authorizer auth.Authorizer) mux.MiddlewareFunc {
func AuthorizeAuthManagementAccess(db database.Database, permissions auth.PermissionSet, authorizer auth.Authorizer) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
bhCtx := ctx.FromRequest(request)
Expand Down Expand Up @@ -188,6 +208,7 @@ func AuthorizeAuthManagementAccess(permissions auth.PermissionSet, authorizer au
}

if !authorized {
auditLogUnauthorizedAccess(db, request)
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusUnauthorized, fmt.Sprintf("not authorized for %s", userID), request), response)
} else {
next.ServeHTTP(response, request)
Expand Down
46 changes: 29 additions & 17 deletions cmd/api/src/api/middleware/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,20 @@ import (
"github.com/specterops/bloodhound/src/api"
"github.com/specterops/bloodhound/src/auth"
"github.com/specterops/bloodhound/src/ctx"
dbmocks "github.com/specterops/bloodhound/src/database/mocks"
"github.com/specterops/bloodhound/src/model"
"github.com/specterops/bloodhound/src/test/must"
"github.com/specterops/bloodhound/src/utils/test"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
)

func permissionsCheckAllHandler(internalHandler http.HandlerFunc, permissions ...model.Permission) http.Handler {
return PermissionsCheckAll(auth.NewAuthorizer(), permissions...)(internalHandler)
func permissionsCheckAllHandler(db *dbmocks.MockDatabase, internalHandler http.HandlerFunc, permissions ...model.Permission) http.Handler {
return PermissionsCheckAll(db, auth.NewAuthorizer(), permissions...)(internalHandler)
}

func permissionsCheckAtLeastOneHandler(internalHandler http.HandlerFunc, permissions ...model.Permission) http.Handler {
return PermissionsCheckAtLeastOne(auth.NewAuthorizer(), permissions...)(internalHandler)
func permissionsCheckAtLeastOneHandler(db *dbmocks.MockDatabase, internalHandler http.HandlerFunc, permissions ...model.Permission) http.Handler {
return PermissionsCheckAtLeastOne(db, auth.NewAuthorizer(), permissions...)(internalHandler)
}

func Test_parseAuthorizationHeader(t *testing.T) {
Expand All @@ -61,13 +63,17 @@ func TestPermissionsCheckAll(t *testing.T) {
handlerReturn200 = func(response http.ResponseWriter, request *http.Request) {
response.WriteHeader(http.StatusOK)
}
mockCtrl = gomock.NewController(t)
mockDB = dbmocks.NewMockDatabase(mockCtrl)
)
defer mockCtrl.Finish()

mockDB.EXPECT().AppendAuditLog(gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
test.Request(t).
WithURL("http//example.com").
WithHeader(headers.RequestID.String(), "requestID").
WithContext(&ctx.Context{}).
OnHandler(permissionsCheckAllHandler(handlerReturn200, auth.Permissions().AuthManageSelf)).
OnHandler(permissionsCheckAllHandler(mockDB, handlerReturn200, auth.Permissions().AuthManageSelf)).
Require().
ResponseStatusCode(http.StatusUnauthorized)

Expand All @@ -87,10 +93,11 @@ func TestPermissionsCheckAll(t *testing.T) {
Session: model.UserSession{},
},
}).
OnHandler(permissionsCheckAllHandler(handlerReturn200, auth.Permissions().AuthManageSelf)).
OnHandler(permissionsCheckAllHandler(mockDB, handlerReturn200, auth.Permissions().AuthManageSelf)).
Require().
ResponseStatusCode(http.StatusForbidden)

mockDB.EXPECT().AppendAuditLog(gomock.Any(), gomock.Any()).Return(nil).Times(0) // No audit logs should be created on successful login
test.Request(t).
WithURL("http//example.com").
WithHeader(headers.RequestID.String(), "requestID").
Expand All @@ -109,7 +116,7 @@ func TestPermissionsCheckAll(t *testing.T) {
Session: model.UserSession{},
},
}).
OnHandler(permissionsCheckAllHandler(handlerReturn200, auth.Permissions().AuthManageSelf)).
OnHandler(permissionsCheckAllHandler(mockDB, handlerReturn200, auth.Permissions().AuthManageSelf)).
Require().
ResponseStatusCode(http.StatusOK)
}
Expand All @@ -119,8 +126,12 @@ func TestPermissionsCheckAtLeastOne(t *testing.T) {
handlerReturn200 = func(response http.ResponseWriter, request *http.Request) {
response.WriteHeader(http.StatusOK)
}
mockCtrl = gomock.NewController(t)
mockDB = dbmocks.NewMockDatabase(mockCtrl)
)
defer mockCtrl.Finish()

mockDB.EXPECT().AppendAuditLog(gomock.Any(), gomock.Any()).Return(nil).Times(0)
test.Request(t).
WithURL("http//example.com").
WithContext(&ctx.Context{
Expand All @@ -138,7 +149,7 @@ func TestPermissionsCheckAtLeastOne(t *testing.T) {
Session: model.UserSession{},
},
}).
OnHandler(permissionsCheckAtLeastOneHandler(handlerReturn200, auth.Permissions().AuthManageSelf)).
OnHandler(permissionsCheckAtLeastOneHandler(mockDB, handlerReturn200, auth.Permissions().AuthManageSelf)).
Require().
ResponseStatusCode(http.StatusOK)

Expand All @@ -159,7 +170,7 @@ func TestPermissionsCheckAtLeastOne(t *testing.T) {
Session: model.UserSession{},
},
}).
OnHandler(permissionsCheckAtLeastOneHandler(handlerReturn200, auth.Permissions().AuthManageSelf)).
OnHandler(permissionsCheckAtLeastOneHandler(mockDB, handlerReturn200, auth.Permissions().AuthManageSelf)).
Require().
ResponseStatusCode(http.StatusOK)

Expand All @@ -180,12 +191,13 @@ func TestPermissionsCheckAtLeastOne(t *testing.T) {
Session: model.UserSession{},
},
}).
OnHandler(permissionsCheckAtLeastOneHandler(handlerReturn200, auth.Permissions().GraphDBRead)).
OnHandler(permissionsCheckAtLeastOneHandler(mockDB, handlerReturn200, auth.Permissions().GraphDBRead)).
Require().
ResponseStatusCode(http.StatusOK)

test.Request(t).
WithURL("http//example.com").
WithHeader(headers.RequestID.String(), "requestID").
WithContext(&ctx.Context{
AuthCtx: auth.Context{
PermissionOverrides: auth.PermissionOverrides{},
Expand All @@ -194,20 +206,20 @@ func TestPermissionsCheckAtLeastOne(t *testing.T) {
{
Name: "Big Boy",
Description: "The big boy.",
Permissions: model.Permissions{auth.Permissions().AuthManageSelf, auth.Permissions().GraphDBRead},
Permissions: auth.Permissions().All(),
},
},
},
Session: model.UserSession{},
},
}).
OnHandler(permissionsCheckAtLeastOneHandler(handlerReturn200, auth.Permissions().GraphDBWrite)).
OnHandler(permissionsCheckAtLeastOneHandler(mockDB, handlerReturn200, auth.Permissions().AuthManageSelf)).
Require().
ResponseStatusCode(http.StatusForbidden)
ResponseStatusCode(http.StatusOK)

mockDB.EXPECT().AppendAuditLog(gomock.Any(), gomock.Any()).Return(nil).Times(1)
test.Request(t).
WithURL("http//example.com").
WithHeader(headers.RequestID.String(), "requestID").
WithContext(&ctx.Context{
AuthCtx: auth.Context{
PermissionOverrides: auth.PermissionOverrides{},
Expand All @@ -216,14 +228,14 @@ func TestPermissionsCheckAtLeastOne(t *testing.T) {
{
Name: "Big Boy",
Description: "The big boy.",
Permissions: auth.Permissions().All(),
Permissions: model.Permissions{auth.Permissions().AuthManageSelf, auth.Permissions().GraphDBRead},
},
},
},
Session: model.UserSession{},
},
}).
OnHandler(permissionsCheckAtLeastOneHandler(handlerReturn200, auth.Permissions().AuthManageSelf)).
OnHandler(permissionsCheckAtLeastOneHandler(mockDB, handlerReturn200, auth.Permissions().GraphDBWrite)).
Require().
ResponseStatusCode(http.StatusOK)
ResponseStatusCode(http.StatusForbidden)
}
Loading
Loading