2021-08-24 20:24:52 +00:00
|
|
|
package mysql
|
|
|
|
|
|
|
|
import (
|
2021-09-14 12:11:07 +00:00
|
|
|
"context"
|
2021-08-24 20:24:52 +00:00
|
|
|
"fmt"
|
|
|
|
"sort"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2021-12-03 18:33:33 +00:00
|
|
|
"github.com/doug-martin/goqu/v9"
|
2021-11-15 14:11:38 +00:00
|
|
|
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
2021-08-24 20:24:52 +00:00
|
|
|
"github.com/fleetdm/fleet/v4/server/fleet"
|
2021-12-03 18:33:33 +00:00
|
|
|
"github.com/go-kit/kit/log/level"
|
2021-08-24 20:24:52 +00:00
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
)
|
|
|
|
|
2021-11-24 17:16:42 +00:00
|
|
|
func (ds *Datastore) NewGlobalPolicy(ctx context.Context, authorID *uint, args fleet.PolicyPayload) (*fleet.Policy, error) {
|
|
|
|
if args.QueryID != nil {
|
|
|
|
q, err := ds.Query(ctx, *args.QueryID)
|
|
|
|
if err != nil {
|
|
|
|
return nil, ctxerr.Wrap(ctx, err, "fetching query from id")
|
|
|
|
}
|
|
|
|
args.Name = q.Name
|
|
|
|
args.Query = q.Query
|
|
|
|
args.Description = q.Description
|
|
|
|
}
|
|
|
|
res, err := ds.writer.ExecContext(ctx,
|
2021-12-03 18:33:33 +00:00
|
|
|
`INSERT INTO policies (name, query, description, resolution, author_id, platforms) VALUES (?, ?, ?, ?, ?, ?)`,
|
2021-12-06 16:56:28 +00:00
|
|
|
args.Name, args.Query, args.Description, args.Resolution, authorID, args.Platform,
|
2021-11-24 17:16:42 +00:00
|
|
|
)
|
|
|
|
switch {
|
|
|
|
case err == nil:
|
|
|
|
// OK
|
|
|
|
case isDuplicate(err):
|
|
|
|
return nil, ctxerr.Wrap(ctx, alreadyExists("Policy", args.Name))
|
|
|
|
default:
|
2021-11-15 14:11:38 +00:00
|
|
|
return nil, ctxerr.Wrap(ctx, err, "inserting new policy")
|
2021-08-24 20:24:52 +00:00
|
|
|
}
|
|
|
|
lastIdInt64, err := res.LastInsertId()
|
|
|
|
if err != nil {
|
2021-11-15 14:11:38 +00:00
|
|
|
return nil, ctxerr.Wrap(ctx, err, "getting last id after inserting policy")
|
2021-08-24 20:24:52 +00:00
|
|
|
}
|
2021-09-20 14:00:57 +00:00
|
|
|
return policyDB(ctx, ds.writer, uint(lastIdInt64), nil)
|
2021-08-24 20:24:52 +00:00
|
|
|
}
|
|
|
|
|
2021-09-14 12:11:07 +00:00
|
|
|
func (ds *Datastore) Policy(ctx context.Context, id uint) (*fleet.Policy, error) {
|
2021-09-20 14:00:57 +00:00
|
|
|
return policyDB(ctx, ds.reader, id, nil)
|
2021-09-09 20:23:35 +00:00
|
|
|
}
|
|
|
|
|
2021-09-20 14:00:57 +00:00
|
|
|
func policyDB(ctx context.Context, q sqlx.QueryerContext, id uint, teamID *uint) (*fleet.Policy, error) {
|
|
|
|
teamWhere := "TRUE"
|
|
|
|
args := []interface{}{id}
|
|
|
|
if teamID != nil {
|
|
|
|
teamWhere = "team_id = ?"
|
|
|
|
args = append(args, *teamID)
|
|
|
|
}
|
|
|
|
|
2021-08-24 20:24:52 +00:00
|
|
|
var policy fleet.Policy
|
2021-09-14 14:44:02 +00:00
|
|
|
err := sqlx.GetContext(ctx, q, &policy,
|
2021-11-24 17:16:42 +00:00
|
|
|
fmt.Sprintf(`SELECT p.*,
|
|
|
|
COALESCE(u.name, '<deleted>') AS author_name,
|
|
|
|
COALESCE(u.email, '') AS author_email,
|
2021-09-01 19:50:52 +00:00
|
|
|
(select count(*) from policy_membership where policy_id=p.id and passes=true) as passing_host_count,
|
2021-08-24 20:24:52 +00:00
|
|
|
(select count(*) from policy_membership where policy_id=p.id and passes=false) as failing_host_count
|
2021-11-24 17:16:42 +00:00
|
|
|
FROM policies p
|
|
|
|
LEFT JOIN users u ON p.author_id = u.id
|
|
|
|
WHERE p.id=? AND %s`, teamWhere),
|
2021-09-20 14:00:57 +00:00
|
|
|
args...)
|
2021-08-24 20:24:52 +00:00
|
|
|
if err != nil {
|
2021-11-15 14:11:38 +00:00
|
|
|
return nil, ctxerr.Wrap(ctx, err, "getting policy")
|
2021-08-24 20:24:52 +00:00
|
|
|
}
|
|
|
|
return &policy, nil
|
|
|
|
}
|
|
|
|
|
2021-11-24 17:16:42 +00:00
|
|
|
// SavePolicy updates some fields of the given policy on the datastore.
|
|
|
|
func (ds *Datastore) SavePolicy(ctx context.Context, p *fleet.Policy) error {
|
|
|
|
sql := `
|
|
|
|
UPDATE policies
|
2021-12-03 18:33:33 +00:00
|
|
|
SET name = ?, query = ?, description = ?, resolution = ?, platforms = ?
|
2021-11-24 17:16:42 +00:00
|
|
|
WHERE id = ?
|
|
|
|
`
|
2021-12-06 16:56:28 +00:00
|
|
|
result, err := ds.writer.ExecContext(ctx, sql, p.Name, p.Query, p.Description, p.Resolution, p.Platform, p.ID)
|
2021-11-24 17:16:42 +00:00
|
|
|
if err != nil {
|
|
|
|
return ctxerr.Wrap(ctx, err, "updating policy")
|
|
|
|
}
|
|
|
|
rows, err := result.RowsAffected()
|
|
|
|
if err != nil {
|
|
|
|
return ctxerr.Wrap(ctx, err, "rows affected updating policy")
|
|
|
|
}
|
|
|
|
if rows == 0 {
|
|
|
|
return ctxerr.Wrap(ctx, notFound("Policy").WithID(p.ID))
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-11-08 14:42:37 +00:00
|
|
|
func (ds *Datastore) RecordPolicyQueryExecutions(ctx context.Context, host *fleet.Host, results map[uint]*bool, updated time.Time, deferredSaveHost bool) error {
|
2021-08-24 20:24:52 +00:00
|
|
|
// Sort the results to have generated SQL queries ordered to minimize
|
|
|
|
// deadlocks. See https://github.com/fleetdm/fleet/issues/1146.
|
|
|
|
orderedIDs := make([]uint, 0, len(results))
|
2021-08-24 21:49:56 +00:00
|
|
|
for policyID := range results {
|
2021-08-24 20:24:52 +00:00
|
|
|
orderedIDs = append(orderedIDs, policyID)
|
|
|
|
}
|
|
|
|
sort.Slice(orderedIDs, func(i, j int) bool { return orderedIDs[i] < orderedIDs[j] })
|
|
|
|
|
|
|
|
// Loop through results, collecting which labels we need to insert/update
|
|
|
|
vals := []interface{}{}
|
|
|
|
bindvars := []string{}
|
|
|
|
for _, policyID := range orderedIDs {
|
|
|
|
matches := results[policyID]
|
|
|
|
bindvars = append(bindvars, "(?,?,?,?)")
|
|
|
|
vals = append(vals, updated, policyID, host.ID, matches)
|
|
|
|
}
|
|
|
|
|
|
|
|
query := fmt.Sprintf(
|
2021-12-03 16:10:11 +00:00
|
|
|
`INSERT INTO policy_membership (updated_at, policy_id, host_id, passes)
|
|
|
|
VALUES %s ON DUPLICATE KEY UPDATE updated_at=VALUES(updated_at), passes=VALUES(passes)`,
|
2021-08-24 20:24:52 +00:00
|
|
|
strings.Join(bindvars, ","),
|
|
|
|
)
|
|
|
|
|
2021-11-08 14:42:37 +00:00
|
|
|
err := ds.withRetryTxx(ctx, func(tx sqlx.ExtContext) error {
|
2021-10-01 21:27:57 +00:00
|
|
|
_, err := tx.ExecContext(ctx, query, vals...)
|
|
|
|
if err != nil {
|
2021-11-15 14:11:38 +00:00
|
|
|
return ctxerr.Wrapf(ctx, err, "insert policy_membership (%v)", vals)
|
2021-10-01 21:27:57 +00:00
|
|
|
}
|
2021-08-24 20:24:52 +00:00
|
|
|
|
2021-11-08 14:42:37 +00:00
|
|
|
// if we are deferring host updates, we return at this point and do the change outside of the tx
|
|
|
|
if deferredSaveHost {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = tx.ExecContext(ctx, `UPDATE hosts SET policy_updated_at = ? WHERE id=?`, updated, host.ID)
|
2021-10-01 21:27:57 +00:00
|
|
|
if err != nil {
|
2021-11-15 14:11:38 +00:00
|
|
|
return ctxerr.Wrap(ctx, err, "updating hosts policy updated at")
|
2021-10-01 21:27:57 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
2021-11-08 14:42:37 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if deferredSaveHost {
|
|
|
|
errCh := make(chan error, 1)
|
|
|
|
defer close(errCh)
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
case ds.writeCh <- itemToWrite{
|
|
|
|
ctx: ctx,
|
|
|
|
errCh: errCh,
|
|
|
|
item: hostXUpdatedAt{
|
|
|
|
hostID: host.ID,
|
|
|
|
updatedAt: updated,
|
|
|
|
what: "policy_updated_at",
|
|
|
|
},
|
|
|
|
}:
|
|
|
|
return <-errCh
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
2021-08-24 20:24:52 +00:00
|
|
|
}
|
|
|
|
|
2021-09-14 12:11:07 +00:00
|
|
|
func (ds *Datastore) ListGlobalPolicies(ctx context.Context) ([]*fleet.Policy, error) {
|
2021-09-20 14:00:57 +00:00
|
|
|
return listPoliciesDB(ctx, ds.reader, nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
func listPoliciesDB(ctx context.Context, q sqlx.QueryerContext, teamID *uint) ([]*fleet.Policy, error) {
|
|
|
|
teamWhere := "p.team_id is NULL"
|
|
|
|
var args []interface{}
|
|
|
|
if teamID != nil {
|
|
|
|
teamWhere = "p.team_id = ?"
|
|
|
|
args = append(args, *teamID)
|
|
|
|
}
|
2021-08-24 20:24:52 +00:00
|
|
|
var policies []*fleet.Policy
|
2021-09-14 14:44:02 +00:00
|
|
|
err := sqlx.SelectContext(
|
|
|
|
ctx,
|
2021-09-20 14:00:57 +00:00
|
|
|
q,
|
2021-08-24 20:24:52 +00:00
|
|
|
&policies,
|
2021-11-24 17:16:42 +00:00
|
|
|
fmt.Sprintf(`SELECT p.*,
|
|
|
|
COALESCE(u.name, '<deleted>') AS author_name,
|
|
|
|
COALESCE(u.email, '') AS author_email,
|
2021-09-01 19:50:52 +00:00
|
|
|
(select count(*) from policy_membership where policy_id=p.id and passes=true) as passing_host_count,
|
|
|
|
(select count(*) from policy_membership where policy_id=p.id and passes=false) as failing_host_count
|
2021-11-24 17:16:42 +00:00
|
|
|
FROM policies p
|
|
|
|
LEFT JOIN users u ON p.author_id = u.id
|
|
|
|
WHERE %s`, teamWhere), args...,
|
2021-08-24 20:24:52 +00:00
|
|
|
)
|
|
|
|
if err != nil {
|
2021-11-15 14:11:38 +00:00
|
|
|
return nil, ctxerr.Wrap(ctx, err, "listing policies")
|
2021-08-24 20:24:52 +00:00
|
|
|
}
|
|
|
|
return policies, nil
|
|
|
|
}
|
|
|
|
|
2021-09-14 12:11:07 +00:00
|
|
|
func (ds *Datastore) DeleteGlobalPolicies(ctx context.Context, ids []uint) ([]uint, error) {
|
2021-09-20 14:00:57 +00:00
|
|
|
return deletePolicyDB(ctx, ds.writer, ids, nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
func deletePolicyDB(ctx context.Context, q sqlx.ExtContext, ids []uint, teamID *uint) ([]uint, error) {
|
|
|
|
stmt := `DELETE FROM policies WHERE id IN (?) AND %s`
|
2021-08-24 20:24:52 +00:00
|
|
|
stmt, args, err := sqlx.In(stmt, ids)
|
|
|
|
if err != nil {
|
2021-11-15 14:11:38 +00:00
|
|
|
return nil, ctxerr.Wrap(ctx, err, "IN for DELETE FROM policies")
|
2021-08-24 20:24:52 +00:00
|
|
|
}
|
2021-09-20 14:00:57 +00:00
|
|
|
stmt = q.Rebind(stmt)
|
|
|
|
|
|
|
|
teamWhere := "TRUE"
|
|
|
|
if teamID != nil {
|
|
|
|
teamWhere = "team_id = ?"
|
|
|
|
args = append(args, *teamID)
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := q.ExecContext(ctx, fmt.Sprintf(stmt, teamWhere), args...); err != nil {
|
2021-11-15 14:11:38 +00:00
|
|
|
return nil, ctxerr.Wrap(ctx, err, "delete policies")
|
2021-08-24 20:24:52 +00:00
|
|
|
}
|
|
|
|
return ids, nil
|
|
|
|
}
|
|
|
|
|
2021-12-03 18:33:33 +00:00
|
|
|
// PolicyQueriesForHost returns the policy queries that are to be executed on the given host.
|
2021-09-20 14:00:57 +00:00
|
|
|
func (ds *Datastore) PolicyQueriesForHost(ctx context.Context, host *fleet.Host) (map[string]string, error) {
|
2021-12-03 18:33:33 +00:00
|
|
|
var rows []struct {
|
|
|
|
ID string `db:"id"`
|
2021-08-26 14:56:05 +00:00
|
|
|
Query string `db:"query"`
|
2021-08-24 20:24:52 +00:00
|
|
|
}
|
2021-12-03 18:33:33 +00:00
|
|
|
if host.FleetPlatform() == "" {
|
|
|
|
// We log to help troubleshooting in case this happens, as the host
|
|
|
|
// won't be receiving any policies targeted for specific platforms.
|
|
|
|
level.Error(ds.logger).Log("err", fmt.Sprintf("host %d with empty platform", host.ID))
|
|
|
|
}
|
|
|
|
q := dialect.From("policies").Select(
|
|
|
|
goqu.I("id"),
|
|
|
|
goqu.I("query"),
|
|
|
|
).Where(
|
|
|
|
goqu.And(
|
|
|
|
goqu.Or(
|
|
|
|
goqu.I("platforms").Eq(""),
|
|
|
|
goqu.L("FIND_IN_SET(?, ?)",
|
|
|
|
host.FleetPlatform(),
|
|
|
|
goqu.I("platforms"),
|
|
|
|
).Neq(0),
|
|
|
|
),
|
|
|
|
goqu.Or(
|
|
|
|
goqu.I("team_id").IsNull(), // global policies
|
|
|
|
goqu.I("team_id").Eq(host.TeamID), // team policies
|
|
|
|
),
|
|
|
|
),
|
2021-09-20 14:00:57 +00:00
|
|
|
)
|
2021-12-03 18:33:33 +00:00
|
|
|
sql, args, err := q.ToSQL()
|
2021-08-24 20:24:52 +00:00
|
|
|
if err != nil {
|
2021-12-03 18:33:33 +00:00
|
|
|
return nil, ctxerr.Wrap(ctx, err, "selecting policies sql build")
|
2021-08-24 20:24:52 +00:00
|
|
|
}
|
2021-12-03 18:33:33 +00:00
|
|
|
if err := sqlx.SelectContext(ctx, ds.reader, &rows, sql, args...); err != nil {
|
|
|
|
return nil, ctxerr.Wrap(ctx, err, "selecting policies for host")
|
2021-09-20 14:00:57 +00:00
|
|
|
}
|
2021-12-03 18:33:33 +00:00
|
|
|
results := make(map[string]string)
|
|
|
|
for _, row := range rows {
|
|
|
|
results[row.ID] = row.Query
|
2021-08-24 20:24:52 +00:00
|
|
|
}
|
|
|
|
return results, nil
|
|
|
|
}
|
2021-09-20 14:00:57 +00:00
|
|
|
|
2021-11-24 17:16:42 +00:00
|
|
|
func (ds *Datastore) NewTeamPolicy(ctx context.Context, teamID uint, authorID *uint, args fleet.PolicyPayload) (*fleet.Policy, error) {
|
|
|
|
if args.QueryID != nil {
|
|
|
|
q, err := ds.Query(ctx, *args.QueryID)
|
|
|
|
if err != nil {
|
|
|
|
return nil, ctxerr.Wrap(ctx, err, "fetching query from id")
|
|
|
|
}
|
|
|
|
args.Name = q.Name
|
|
|
|
args.Query = q.Query
|
|
|
|
args.Description = q.Description
|
|
|
|
}
|
|
|
|
res, err := ds.writer.ExecContext(ctx,
|
2021-12-03 18:33:33 +00:00
|
|
|
`INSERT INTO policies (name, query, description, team_id, resolution, author_id, platforms) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
2021-12-06 16:56:28 +00:00
|
|
|
args.Name, args.Query, args.Description, teamID, args.Resolution, authorID, args.Platform)
|
2021-11-24 17:16:42 +00:00
|
|
|
switch {
|
|
|
|
case err == nil:
|
|
|
|
// OK
|
|
|
|
case isDuplicate(err):
|
|
|
|
return nil, ctxerr.Wrap(ctx, alreadyExists("Policy", args.Name))
|
|
|
|
default:
|
|
|
|
return nil, ctxerr.Wrap(ctx, err, "inserting new policy")
|
2021-09-20 14:00:57 +00:00
|
|
|
}
|
|
|
|
lastIdInt64, err := res.LastInsertId()
|
|
|
|
if err != nil {
|
2021-11-15 14:11:38 +00:00
|
|
|
return nil, ctxerr.Wrap(ctx, err, "getting last id after inserting policy")
|
2021-09-20 14:00:57 +00:00
|
|
|
}
|
2021-11-24 17:16:42 +00:00
|
|
|
return policyDB(ctx, ds.writer, uint(lastIdInt64), &teamID)
|
2021-09-20 14:00:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (ds *Datastore) ListTeamPolicies(ctx context.Context, teamID uint) ([]*fleet.Policy, error) {
|
|
|
|
return listPoliciesDB(ctx, ds.reader, &teamID)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ds *Datastore) DeleteTeamPolicies(ctx context.Context, teamID uint, ids []uint) ([]uint, error) {
|
|
|
|
return deletePolicyDB(ctx, ds.writer, ids, &teamID)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ds *Datastore) TeamPolicy(ctx context.Context, teamID uint, policyID uint) (*fleet.Policy, error) {
|
|
|
|
return policyDB(ctx, ds.reader, policyID, &teamID)
|
|
|
|
}
|
2021-10-15 10:34:11 +00:00
|
|
|
|
2021-11-24 17:16:42 +00:00
|
|
|
// ApplyPolicySpecs applies the given policy specs, creating new policies and updating the ones that
|
|
|
|
// already exist (a policy is identified by its name and the team it belongs to).
|
|
|
|
//
|
|
|
|
// NOTE: Similar to ApplyQueries, ApplyPolicySpecs will update the author_id of the policies
|
|
|
|
// that are updated.
|
|
|
|
func (ds *Datastore) ApplyPolicySpecs(ctx context.Context, authorID uint, specs []*fleet.PolicySpec) error {
|
2021-10-15 10:34:11 +00:00
|
|
|
return ds.withRetryTxx(ctx, func(tx sqlx.ExtContext) error {
|
2021-11-24 17:16:42 +00:00
|
|
|
sql := `
|
|
|
|
INSERT INTO policies (
|
|
|
|
name,
|
|
|
|
query,
|
|
|
|
description,
|
|
|
|
author_id,
|
|
|
|
resolution,
|
2021-12-03 18:33:33 +00:00
|
|
|
team_id,
|
|
|
|
platforms
|
|
|
|
) VALUES ( ?, ?, ?, ?, ?, (SELECT IFNULL(MIN(id), NULL) FROM teams WHERE name = ?), ? )
|
2021-11-24 17:16:42 +00:00
|
|
|
ON DUPLICATE KEY UPDATE
|
|
|
|
name = VALUES(name),
|
|
|
|
query = VALUES(query),
|
|
|
|
description = VALUES(description),
|
|
|
|
author_id = VALUES(author_id),
|
|
|
|
resolution = VALUES(resolution),
|
2021-12-03 18:33:33 +00:00
|
|
|
team_id = VALUES(team_id),
|
|
|
|
platforms = VALUES(platforms)
|
2021-11-24 17:16:42 +00:00
|
|
|
`
|
2021-10-15 10:34:11 +00:00
|
|
|
for _, spec := range specs {
|
2021-11-24 17:16:42 +00:00
|
|
|
if _, err := tx.ExecContext(ctx,
|
2021-12-06 16:56:28 +00:00
|
|
|
sql, spec.Name, spec.Query, spec.Description, authorID, spec.Resolution, spec.Team, spec.Platform,
|
2021-11-24 17:16:42 +00:00
|
|
|
); err != nil {
|
|
|
|
return ctxerr.Wrap(ctx, err, "exec ApplyPolicySpecs insert")
|
2021-10-15 10:34:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
}
|
2021-12-06 20:39:00 +00:00
|
|
|
|
|
|
|
func amountPoliciesDB(db sqlx.Queryer) (int, error) {
|
|
|
|
var amount int
|
|
|
|
err := sqlx.Get(db, &amount, `SELECT count(*) FROM policies`)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
return amount, nil
|
|
|
|
}
|