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

feat: add casbin engine support #31

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,6 @@

# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
.glide/

.idea/
.vscode/
1 change: 1 addition & 0 deletions README.md
Copy link

Choose a reason for hiding this comment

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

This repository includes two Policy Engine Plugins:

should be:

This repository includes three Policy Engine Plugins:

Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ When authoring a new policy engine plugin, the plugin must implement the `Engine
This repository includes two Policy Engine Plugins:
* *themis* - enables Infoblox's Themis policy engine to be used as a CoreDNS firewall policy engine
* *opa* - enables OPA to be used as a CoreDNS firewall policy engine.
* *casbin* - enables Casbin to be used as a CoreDNS firewall policy engine.
## External Plugin
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.12

require (
github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible
github.com/casbin/casbin/v2 v2.31.9
github.com/coredns/caddy v1.1.0
github.com/coredns/coredns v1.8.3
github.com/infobloxopen/go-trees v0.0.0-20190313150506-2af4e13f9062
Expand Down
306 changes: 4 additions & 302 deletions go.sum

Large diffs are not rendered by default.

65 changes: 65 additions & 0 deletions plugin/casbin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Casbin

*casbin* - enables Casbin to be used as a CoreDNS *firewall* policy engine.

## Syntax

```
casbin ENGINE-NAME {
model /path/to/model
policy /path/to/policy
}
```

* **ENGINE-NAME** is the name of the policy engine, used by the firewall
plugin to uniquely identify the instance. Each instance of _opa_ in
the Corefile must have a unique **ENGINE-NAME**.

* **model** & **policy** are concepts in casbin. More details, please refer to [casbin](https://casbin.org/docs/en/how-it-works)

## Firewall Policy Engine

This plugin is not a standalone plugin. It must be used in conjunction
with the _firewall_ plugin to function. For this plugin to be active,
the _firewall_ plugin must reference it in a rule. See the "Policy
Engine Plugins" section of the _firewall_ plugin README for more
information.

## Examples

`myengine` points to a Casbin instance.

```txt
. {
casbin myengine {
model ./examples/model.conf
policy ./examples/policy.csv
}

firewall query {
casbin myengine
}
}
```

model:

```conf
[request_definition]
r = client_ip, name

[policy_definition]
p = client_ip, name, action

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = r.client_ip == p.client_ip && r.name == p.name
```

policy:

```csv
p, 10.240.0.1, example.org., allow
```
157 changes: 157 additions & 0 deletions plugin/casbin/casbin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
package casbin

import (
"context"
"errors"
"fmt"
casbin2 "github.com/casbin/casbin/v2"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/metadata"
"github.com/coredns/coredns/request"
"github.com/coredns/policy/plugin/firewall/policy"
"github.com/coredns/policy/plugin/pkg/rqdata"
"github.com/miekg/dns"
"reflect"
"strings"
)

type casbin struct {
engines map[string]*engine
next plugin.Handler
}

type engine struct {
modelPath string
policyPath string
enforcer *casbin2.Enforcer
fields []string
actionIndex int
mapping *rqdata.Mapping
}

func newCasbin() *casbin {
return &casbin{
engines: make(map[string]*engine),
}
}

func newEngine(m *rqdata.Mapping) *engine {
return &engine{
mapping: m,
}
}

func (c *casbin) Name() string {
return "casbin"
}

func (c *casbin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
return plugin.NextOrFailure(c.Name(), c.next, ctx, w, r)
}

func (c *casbin) Engine(name string) policy.Engine {
return c.engines[name]
}

func (e *engine) BuildQueryData(ctx context.Context, state request.Request) (interface{}, error) {
return e.buildData(ctx, state, make(map[string]string)), nil
}

func (e *engine) BuildReplyData(ctx context.Context, state request.Request, queryData interface{}) (interface{}, error) {
return e.buildData(ctx, state, queryData.(map[string]string)), nil
}

func (e *engine) buildData(ctx context.Context, state request.Request, data map[string]string) map[string]string {
extractor := rqdata.NewExtractor(state, e.mapping)
for _, f := range e.fields {
if _, ok := data[f]; ok {
continue
}
var (
v string
ok bool
)
if e.mapping.ValidField(f) {
v, ok = extractor.Value(f)
if !ok {
continue
}
} else {
mdf := metadata.ValueFunc(ctx, f)
v := mdf()
if v == "" {
continue
}
}
if len(v) > 0 && v[0] == '[' && strings.HasSuffix(f, "_ip") {
v = v[1 : len(v)-1]
}
data[f] = v
}
return data
}

func (e *engine) getFields() {
m := e.enforcer.GetModel()
fields := make([]string, 0)
ast := m["r"]["r"]
for _, token := range ast.Tokens {
field := strings.TrimPrefix(token, "r_")
fields = append(fields, field)
}
e.fields = fields
}

func (e *engine) getActionIndex() error {
m := e.enforcer.GetModel()
index := -1
key := "p_action"
for i, k := range m["p"]["p"].Tokens {
if k == key {
index = i
}
}
if index == -1 {
return errors.New("could not get action column")
}
e.actionIndex = index
return nil
}

func (e *engine) BuildRule(args []string) (policy.Rule, error) {
return e, nil
}

func (e *engine) Evaluate(data interface{}) (int, error) {
pdata, ok := data.(map[string]string)
if !ok {
return 0, fmt.Errorf("input should be map[string]string instead of %v", reflect.TypeOf(data))
}
params := make([]interface{}, 0, len(pdata))
for _, v := range pdata {
params = append(params, v)
}

ok, p, err := e.enforcer.EnforceEx(params...)
if err != nil {
return 0, err
}
if len(p) == 0 {
return policy.TypeNone, nil
}
if ok {
switch p[e.actionIndex] {
case "allow":
return policy.TypeAllow, nil
case "refuse":
return policy.TypeRefuse, nil
case "block":
return policy.TypeBlock, nil
case "drop":
return policy.TypeDrop, nil
default:
return 0, fmt.Errorf("unknown action: '%s'", p[3])
}
}
return policy.TypeNone, nil
}
69 changes: 69 additions & 0 deletions plugin/casbin/casbin_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package casbin

import (
"context"
"github.com/coredns/caddy"
"github.com/coredns/coredns/plugin/test"
"github.com/coredns/coredns/request"
"github.com/coredns/policy/plugin/firewall/policy"
"github.com/coredns/policy/plugin/pkg/response"
"github.com/miekg/dns"
"testing"
)

func TestEvaluate(t *testing.T) {
o, err := parse(caddy.NewTestController("dns",
`casbin myengine {
model ./examples/model.conf
policy ./examples/policy.csv
}`))

if err != nil {
t.Fatal(err)
}

data := map[string]string{
"client_ip": "10.240.0.1",
"name": "example.org.",
}

result, err := o.engines["myengine"].Evaluate(data)

if err != nil {
t.Fatal(err)
}

if result != policy.TypeAllow {
t.Errorf("Expected %d, got %d.", policy.TypeAllow, result)
}
}

func TestBuildQueryData(t *testing.T) {
w := response.NewReader(&test.ResponseWriter{})
r := new(dns.Msg)
r.SetQuestion("example.org.", dns.TypeA)
state := request.Request{W: w, Req: r}

o, err := parse(caddy.NewTestController("dns",
`casbin myengine {
model ./examples/model.conf
policy ./examples/policy.csv
}`))
if err != nil {
t.Fatal(err)
}
ctx := context.TODO()

d, err := o.Engine("myengine").BuildQueryData(ctx, state)
if err != nil {
t.Error(err)
}
data := d.(map[string]string)

if data["client_ip"] != "10.240.0.1" {
t.Errorf("expected client_ip == '10.240.0.1'. Got '%v'", data["client_ip"])
}
if data["name"] != "example.org." {
t.Errorf("expected name == 'example.org.'. Got '%v'", data["name"])
}
}
11 changes: 11 additions & 0 deletions plugin/casbin/examples/model.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[request_definition]
r = client_ip, name

[policy_definition]
p = client_ip, name, action

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = r.client_ip == p.client_ip && r.name == p.name
1 change: 1 addition & 0 deletions plugin/casbin/examples/policy.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
p, 10.240.0.1, example.org., allow
Loading