-
Notifications
You must be signed in to change notification settings - Fork 14
/
datalog_guard.go
869 lines (805 loc) · 22.9 KB
/
datalog_guard.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
// Copyright (c) 2014, Kevin Walsh. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This interface was derived from the code in src/tao/tao_guard.h.
package tao
import (
"crypto/sha256"
"fmt"
"io/ioutil"
"os"
"strings"
"time"
"github.com/golang/glog"
"github.com/golang/protobuf/proto"
"github.com/jlmucb/cloudproxy/go/tao/auth"
"github.com/jlmucb/cloudproxy/go/util"
"github.com/kevinawalsh/datalog"
"github.com/kevinawalsh/datalog/dlengine"
)
// Signing context for signatures on a set of Tao datalog rules.
const (
DatalogRulesSigningContext = "Datalog Rules Signing Context V1"
)
// DatalogGuard implements a datalog-based policy engine. Rules in this engine
// have the form:
// (forall X, Y, Z... : F implies G)
// where
// F is a predicate or a conjunction of predicates
// G is a predicate
// All predicate arguments must be either concrete terms (Int, Str, Prin, etc.)
// or term-valued variables (TermVar) bound by the quantification. Any variable
// appearing in G must also appear in F. If there are no variables, the
// quantification can be omitted. The implication and its antecedent F can be
// omitted (in which case there can be no variables so the quantification must
// be omitted as well).
//
// TODO(kwalsh) We could easily support a slightly broader class of formulas,
// e.g. by allowing G to be a conjunct of predicates, or by allowing a
// disjunction of conjunctions for F. Anything beyond that seems complicated.
//
// Datalog translation
//
// We assume K speaksfor the guard, where K is the key used to sign the policy
// file. If there is no signing key, a temporary principal (with a bogus key) is
// used for K instead. All deduction takes place within the worldview of Guard.
// Other than this relationship between K and the guard, we don't model the says
// and speaksfor logic within datalog.
//
// Term objects are usually translated to datalog by just printing them. In this
// case, a Prin object must not contain any TermVar objects. TermVar objects
// must be uppercase.
//
// "Term says Pred(...)" is translated to "says(Term, \"Pred\", ...)".
//
// "Pred(...)" alone is translated to "says(K, \"Pred\", ...)".
//
// "forall ... F1 and F2 and ... imp G" is translated to "G :- F1, F2, ...".
// Not safe for concurrent use by goroutines.
type DatalogGuard struct {
Config DatalogGuardDetails
Key *Verifier
// TODO(kwalsh) maybe use a version number or timestamp inside the file?
modTime time.Time // Modification time of signed rules file at time of reading.
db DatalogRules
dl *dlengine.Engine
sp *subprinPrim
}
// subprinPrim is a custom datalog primitive that implements subprincipal
// detection. The predicate Subprin(S, P, E) in auth is special-cased in
// DatalogGuard to write in datalog to subprin/3 with arguments S, P, E.
type subprinPrim struct {
datalog.DistinctPred
max int
}
// String returns a string representation of the subprin custom datalog
// predicate.
func (sp *subprinPrim) String() string {
return "subprin"
}
func (sp *subprinPrim) Assert(c *datalog.Clause) error {
return newError("datalog: can't assert for custom predicates")
}
func (sp *subprinPrim) Retract(c *datalog.Clause) error {
return newError("datalog: can't retract for custom predicates")
}
// parseRootExtPrins parses a pair of terms as a key/tpm principal and an
// extension principal tail. Both Terms must implement fmt.Stringer.
func parseRootExtPrins(o datalog.Term, e datalog.Term) (oprin auth.Prin, eprin auth.PrinTail, err error) {
// Report subprin(O.E, O, E) as discovered.
ostringer, ok1 := o.(fmt.Stringer)
estringer, ok2 := e.(fmt.Stringer)
if !ok1 || !ok2 {
err = fmt.Errorf("arguments 2 and 3 must implement fmt.Stringer in subprin/3")
return
}
// The first must be a regular rooted principal, and the second must be
// an ext principal tail.
var ostr string
if _, err = fmt.Sscanf(ostringer.String(), "%q", &ostr); err != nil {
return
}
var estr string
if _, err = fmt.Sscanf(estringer.String(), "%q", &estr); err != nil {
return
}
if _, err = fmt.Sscanf(ostr, "%v", &oprin); err != nil {
return
}
if _, err = fmt.Sscanf(estr, "%v", &eprin); err != nil {
return
}
return
}
// parseCompositePrin parses a Term (which must implement fmt.Stringer) as a
// principal with at least one extension.
func parseCompositePrin(p datalog.Term) (prin auth.Prin, err error) {
// Parse p as Parent.Ext and report subprin(Parent.Ext, Parent, Ext).
pstringer, ok := p.(fmt.Stringer)
if !ok {
err = fmt.Errorf("A composite principal must be a Stringer")
return
}
// Due to the way the translation works between DatalogGuard and the Datalog
// engine, this is a quoted string. So, trim the quotes at the beginning and
// the end of the string before parsing it.
var pstr string
if _, err = fmt.Sscanf(pstringer.String(), "%q", &pstr); err != nil {
return
}
if _, err = fmt.Sscanf(pstr, "%v", &prin); err != nil {
return
}
if len(prin.Ext) < 1 {
err = fmt.Errorf("A composite principal must have extensions")
return
}
return
}
// Search implements the subprinPrim custom datalog primitive by parsing
// constant arguments of subprin/3 as principals and reporting any clauses it
// discovers.
func (sp *subprinPrim) Search(target *datalog.Literal, discovered func(c *datalog.Clause)) {
p := target.Arg[0]
o := target.Arg[1]
e := target.Arg[2]
if p.Constant() && o.Variable() && e.Variable() {
prin, err := parseCompositePrin(p)
if err != nil {
return
}
extIndex := len(prin.Ext) - 1
trimmedPrin := auth.Prin{
Type: prin.Type,
KeyHash: prin.KeyHash,
Ext: prin.Ext[:extIndex],
}
extPrin := auth.PrinTail{
Ext: []auth.PrinExt{prin.Ext[extIndex]},
}
parentIdent := dlengine.NewIdent(fmt.Sprintf("%q", trimmedPrin.String()))
extIdent := dlengine.NewIdent(fmt.Sprintf("%q", extPrin.String()))
discovered(datalog.NewClause(datalog.NewLiteral(sp, p, parentIdent, extIdent)))
} else if p.Variable() && o.Constant() && e.Constant() {
oprin, eprin, err := parseRootExtPrins(o, e)
if err != nil {
return
}
oprin.Ext = append(oprin.Ext, eprin.Ext...)
oeIdent := dlengine.NewIdent(fmt.Sprintf("%q", oprin.String()))
if len(oprin.Ext)+1 <= sp.max {
discovered(datalog.NewClause(datalog.NewLiteral(sp, oeIdent, o, e)))
}
} else if p.Constant() && o.Constant() && e.Constant() {
// Check that the constraint holds and report it as discovered.
prin, err := parseCompositePrin(p)
if err != nil {
return
}
oprin, eprin, err := parseRootExtPrins(o, e)
if err != nil {
return
}
// Extend the root principal with the extension from the ext principal
// and check identity. Make sure the constructed principal does
// not exceed the given maximum principal length.
oprin.Ext = append(oprin.Ext, eprin.Ext...)
if prin.Identical(oprin) {
discovered(datalog.NewClause(datalog.NewLiteral(sp, p, o, e)))
}
}
}
// NewTemporaryDatalogGuard returns a new datalog guard with a fresh, unsigned,
// non-persistent rule set. It adds a custom predicate subprin(P, O, E) to check
// if a principal P is a subprincipal O.E.
func NewTemporaryDatalogGuard() Guard {
sp := &subprinPrim{max: 1}
sp.SetArity(3)
eng := dlengine.NewEngine()
eng.AddPred(sp)
return &DatalogGuard{dl: eng, sp: sp}
}
// NewDatalogGuardFromConfig returns a new datalog guard that uses a signed,
// persistent rule set. ReloadIfModified() should be called to load the rule
// set.
func NewDatalogGuardFromConfig(verifier *Verifier, config DatalogGuardDetails) (*DatalogGuard, error) {
if verifier == nil || config.GetSignedRulesPath() == "" {
return nil, newError("datalog guard missing key or path")
}
dg := NewDatalogGuard(verifier)
dg.Config = config
return dg, nil
}
// NewDatalogGuard returns a new datalog guard without configuring a rules
// file.
func NewDatalogGuard(verifier *Verifier) *DatalogGuard {
sp := &subprinPrim{max: 1}
sp.SetArity(3)
eng := dlengine.NewEngine()
eng.AddPred(sp)
dg := &DatalogGuard{Key: verifier, dl: eng, sp: sp}
dg.Config.SignedRulesPath = nil
return dg
}
// Subprincipal returns subprincipal DatalogGuard, for temporary guards, or
// DatalogGuard(<key>) for persistent guards.
func (g *DatalogGuard) Subprincipal() auth.SubPrin {
if g.Key == nil {
rules, err := proto.Marshal(&g.db)
if err != nil {
return nil
}
hash := sha256.Sum256(rules)
e := auth.PrinExt{Name: "DatalogGuard", Arg: []auth.Term{auth.Bytes(hash[:])}}
return auth.SubPrin{e}
}
e := auth.PrinExt{Name: "DatalogGuard", Arg: []auth.Term{g.Key.ToPrincipal()}}
return auth.SubPrin{e}
}
// ReloadIfModified reads all persistent policy data from disk if the file
// timestamp is more recent than the last time it was read.
func (g *DatalogGuard) ReloadIfModified() error {
if g.Key == nil {
return nil
}
file, err := os.Open(g.Config.GetSignedRulesPath())
if err != nil {
return err
}
defer file.Close()
// before parsing, check the timestamp
info, err := file.Stat()
if err != nil {
return err
}
if !info.ModTime().After(g.modTime) {
return nil
}
serialized, err := ioutil.ReadAll(file)
if err != nil {
return err
}
var sdb SignedDatalogRules
if err := proto.Unmarshal(serialized, &sdb); err != nil {
return err
}
if ok, err := g.Key.Verify(sdb.SerializedRules, DatalogRulesSigningContext, sdb.Signature); !ok {
if err != nil {
return err
}
return newError("datalog rule signature did not verify")
}
var db DatalogRules
if err := proto.Unmarshal(sdb.SerializedRules, &db); err != nil {
return err
}
// Only clear the rules set, since g.assert already skips datalog rules that
// are already present in the engine.
g.db.Rules = nil
g.modTime = info.ModTime()
for _, rule := range db.Rules {
r, err := auth.UnmarshalForm(rule)
if err != nil {
return err
}
err = g.assert(r)
if err != nil {
return err
}
}
return nil
}
// GetSignedDatalogRules serializes and signs the datalog rules and returns
// a SignedDatalogRules pointer.
func (g *DatalogGuard) GetSignedDatalogRules(signer *Signer) (*SignedDatalogRules, error) {
if signer == nil {
return nil, newError("datalog temporary ruleset can't be saved")
}
rules, err := proto.Marshal(&g.db)
if err != nil {
return nil, err
}
sig, err := signer.Sign(rules, DatalogRulesSigningContext)
if err != nil {
return nil, err
}
sdb := &SignedDatalogRules{
SerializedRules: rules,
Signature: sig,
}
return sdb, nil
}
// Save writes all persistent policy data to disk, signed by key.
func (g *DatalogGuard) Save(signer *Signer) error {
sdb, err := g.GetSignedDatalogRules(signer)
if err != nil {
return err
}
serialized, err := proto.Marshal(sdb)
if err != nil {
return err
}
if err := util.WritePath(g.Config.GetSignedRulesPath(), serialized, 0777, 0666); err != nil {
return err
}
return nil
}
func setContains(vars []string, v string) bool {
for _, s := range vars {
if s == v {
return true
}
}
return false
}
func setRemove(vars *[]string, v string) {
if vars == nil {
return
}
for i := 0; i < len(*vars); i++ {
if (*vars)[i] == v {
(*vars)[i] = (*vars)[len(*vars)-1]
*vars = (*vars)[:len(*vars)-1]
i--
}
}
}
func stripQuantifiers(q auth.Form) (f auth.Form, vars []string) {
for {
var v string
switch f := q.(type) {
case auth.Forall:
v = f.Var
q = f.Body
case *auth.Forall:
v = f.Var
q = f.Body
default:
return q, vars
}
if !setContains(vars, v) {
vars = append(vars, v)
}
}
}
func flattenConjuncts(f ...auth.Form) (conjuncts []auth.Form) {
for _, f := range f {
switch f := f.(type) {
case auth.And:
conjuncts = append(conjuncts, flattenConjuncts(f.Conjunct...)...)
case *auth.And:
conjuncts = append(conjuncts, flattenConjuncts(f.Conjunct...)...)
default:
conjuncts = append(conjuncts, f)
}
}
return
}
func stripConditions(f auth.Form) (conds []auth.Form, consequent auth.Form) {
switch f := f.(type) {
case auth.Implies:
conds = flattenConjuncts(f.Antecedent)
consequent = f.Consequent
case *auth.Implies:
conds = flattenConjuncts(f.Antecedent)
consequent = f.Consequent
default:
consequent = f
}
return
}
func checkTermVarUsage(vars []string, unusedVars *[]string, e ...auth.Term) error {
for _, e := range e {
switch e := e.(type) {
case auth.TermVar, *auth.TermVar:
if !setContains(vars, e.String()) {
return fmt.Errorf("illegal quantification variable: %v\n", e)
}
setRemove(unusedVars, e.String())
case auth.Prin:
err := checkTermVarUsage(vars, unusedVars, e.KeyHash)
if err != nil {
return err
}
for _, ext := range e.Ext {
err := checkTermVarUsage(vars, unusedVars, ext.Arg...)
if err != nil {
return err
}
}
case *auth.Prin:
err := checkTermVarUsage(vars, unusedVars, e.KeyHash)
if err != nil {
return err
}
for _, ext := range e.Ext {
err := checkTermVarUsage(vars, unusedVars, ext.Arg...)
if err != nil {
return err
}
}
}
}
return nil
}
func checkFormVarUsage(vars []string, unusedVars *[]string, e ...auth.Form) error {
for _, e := range e {
switch e := e.(type) {
case auth.Pred:
err := checkTermVarUsage(vars, unusedVars, e.Arg...)
if err != nil {
return err
}
case *auth.Pred:
err := checkTermVarUsage(vars, unusedVars, e.Arg...)
if err != nil {
return err
}
}
}
return nil
}
func (g *DatalogGuard) stmtToDatalog(f auth.Form, vars []string, unusedVars *[]string) (string, error) {
speaker := "guard"
if g.Key != nil {
speaker = g.Key.ToPrincipal().String()
}
stmt, ok := f.(*auth.Says)
if !ok {
var val auth.Says
val, ok = (f).(auth.Says)
if ok {
stmt = &val
}
}
if ok {
err := checkTermVarUsage(vars, unusedVars, stmt.Speaker)
if err != nil {
return "", err
}
}
err := checkFormVarUsage(vars, unusedVars, f)
if err != nil {
return "", err
}
pred, ok := f.(*auth.Pred)
if !ok {
var val auth.Pred
val, ok = f.(auth.Pred)
if ok {
pred = &val
}
}
if !ok {
return "", fmt.Errorf("unsupported datalog statement: %v", f)
}
// Special-case: the principal named "Subprin" maps directly to subprinPrim.
var args []string
if pred.Name != "Subprin" {
args = []string{fmt.Sprintf("%q", speaker), fmt.Sprintf("%q", pred.Name)}
}
for _, arg := range pred.Arg {
if _, ok := arg.(auth.TermVar); ok {
// Don't quote variables, since otherwise they won't work as
// variables in the datalog representation.
args = append(args, fmt.Sprintf("%s", arg.String()))
} else {
args = append(args, fmt.Sprintf("%q", arg.String()))
}
}
if pred.Name == "Subprin" {
s := "subprin(" + strings.Join(args, ", ") + ")"
return s, nil
}
return "says(" + strings.Join(args, ", ") + ")", nil
}
// formToDatalogRule converts (a subset of) auth.Form to datalog syntax.
func (g *DatalogGuard) formToDatalogRule(f auth.Form) (string, error) {
f, vars := stripQuantifiers(f)
conditions, consequent := stripConditions(f)
// vars must be upper-case
for _, v := range vars {
if len(v) == 0 || v[0] < 'A' || v[0] > 'Z' {
return "", fmt.Errorf("illegal quantification variable")
}
}
// convert the conditions
dcond := make([]string, len(conditions))
unusedVars := append([]string{}, vars...)
for i, cond := range conditions {
var err error
dcond[i], err = g.stmtToDatalog(cond, vars, &unusedVars)
if err != nil {
return "", err
}
}
// check for safety
if len(unusedVars) > 0 {
return "", fmt.Errorf("unsafe datalog variable usage: % s", unusedVars)
}
goal, err := g.stmtToDatalog(consequent, vars, nil)
if err != nil {
return "", err
}
if len(dcond) > 0 {
return goal + " :- " + strings.Join(dcond, ", "), nil
}
return goal, nil
}
func (g *DatalogGuard) findRule(f auth.Form) (string, int, error) {
rule, err := g.formToDatalogRule(f)
if err != nil {
return "", -1, err
}
for i, ser := range g.db.Rules {
f2, err := auth.UnmarshalForm(ser)
if err != nil {
continue
}
rule2, err := g.formToDatalogRule(f2)
if err != nil {
continue
}
if rule == rule2 {
return rule, i, nil
}
}
return rule, -1, nil
}
func (g *DatalogGuard) assert(f auth.Form) error {
rule, idx, err := g.findRule(f)
if err != nil {
return err
}
if idx >= 0 {
return nil
}
err = g.dl.Assert(rule)
if err != nil {
return err
}
g.db.Rules = append(g.db.Rules, auth.Marshal(f))
return nil
}
func (g *DatalogGuard) retract(f auth.Form) error {
rule, idx, err := g.findRule(f)
if err != nil {
return err
}
if idx < 0 {
return fmt.Errorf("no such rule")
}
err = g.dl.Retract(rule)
if err != nil {
return err
}
g.db.Rules = append(g.db.Rules[:idx], g.db.Rules[idx+1:]...)
return nil
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
// Figure out the max length of a principal in a term, where the length of a
// principal is one more than the length of the extensions of the principal.
func getMaxTermLength(t auth.Term) int {
if t == nil {
return 0
}
switch t.(type) {
case auth.Prin:
// TODO(tmroeder): this and the next case are not fully
// general, since there might be an Arg that has a longer
// principal.
return 1 + len(t.(auth.Prin).Ext)
case *auth.Prin:
return 1 + len(t.(*auth.Prin).Ext)
case auth.PrinTail:
return len(t.(auth.PrinTail).Ext)
case *auth.PrinTail:
return len(t.(*auth.PrinTail).Ext)
case auth.Str, auth.Bytes, auth.Int, auth.TermVar:
return 0
default:
return 0
}
}
// Figure out the max length of a principal in a form, where the length of a
// principal is one more than the length of the extensions of the principal.
func getMaxFormLength(f auth.Form) int {
if f == nil {
return 0
}
m := 0
switch f.(type) {
case auth.Pred:
for _, t := range f.(auth.Pred).Arg {
m = max(m, getMaxTermLength(t))
}
case *auth.Pred:
for _, t := range f.(*auth.Pred).Arg {
m = max(m, getMaxTermLength(t))
}
case auth.Const, *auth.Const:
return 0
case auth.Not:
return getMaxFormLength(f.(auth.Not).Negand)
case *auth.Not:
return getMaxFormLength(f.(*auth.Not).Negand)
case auth.And:
for _, c := range f.(auth.And).Conjunct {
m = max(m, getMaxFormLength(c))
}
case *auth.And:
for _, c := range f.(*auth.And).Conjunct {
m = max(m, getMaxFormLength(c))
}
case auth.Or:
for _, d := range f.(auth.Or).Disjunct {
m = max(m, getMaxFormLength(d))
}
case *auth.Or:
for _, d := range f.(*auth.Or).Disjunct {
m = max(m, getMaxFormLength(d))
}
case auth.Implies:
first := getMaxFormLength(f.(auth.Implies).Antecedent)
second := getMaxFormLength(f.(auth.Implies).Consequent)
return max(first, second)
case *auth.Implies:
first := getMaxFormLength(f.(*auth.Implies).Antecedent)
second := getMaxFormLength(f.(*auth.Implies).Consequent)
return max(first, second)
case auth.Speaksfor:
first := getMaxTermLength(f.(auth.Speaksfor).Delegate)
second := getMaxTermLength(f.(auth.Speaksfor).Delegator)
return max(first, second)
case *auth.Speaksfor:
first := getMaxTermLength(f.(*auth.Speaksfor).Delegate)
second := getMaxTermLength(f.(*auth.Speaksfor).Delegator)
return max(first, second)
case auth.Says:
sl := getMaxTermLength(f.(auth.Says).Speaker)
ml := getMaxFormLength(f.(auth.Says).Message)
return max(sl, ml)
case *auth.Says:
sl := getMaxTermLength(f.(*auth.Says).Speaker)
ml := getMaxFormLength(f.(*auth.Says).Message)
return max(sl, ml)
case auth.Forall:
return getMaxFormLength(f.(auth.Forall).Body)
case *auth.Forall:
return getMaxFormLength(f.(*auth.Forall).Body)
case auth.Exists:
return getMaxFormLength(f.(auth.Exists).Body)
case *auth.Exists:
return getMaxFormLength(f.(*auth.Exists).Body)
default:
return 0
}
return m
}
func (g *DatalogGuard) query(f auth.Form) (bool, error) {
g.sp.max = getMaxFormLength(f)
q, err := g.stmtToDatalog(f, nil, nil)
if err != nil {
return false, err
}
ans, err := g.dl.Query(q)
if err != nil {
return false, err
}
return len(ans) > 0, nil
}
func makeDatalogPredicate(p auth.Prin, op string, args []string) auth.Pred {
a := []interface{}{p, op}
for _, s := range args {
a = append(a, s)
}
return auth.MakePredicate("Authorized", a...)
}
// Authorize adds an authorization for p to perform op(args).
func (g *DatalogGuard) Authorize(p auth.Prin, op string, args []string) error {
return g.assert(makeDatalogPredicate(p, op, args))
}
// Retract removes an authorization for p to perform op(args).
func (g *DatalogGuard) Retract(p auth.Prin, op string, args []string) error {
return g.retract(makeDatalogPredicate(p, op, args))
}
// IsAuthorized checks whether p is authorized to perform op(args).
func (g *DatalogGuard) IsAuthorized(p auth.Prin, op string, args []string) bool {
ok, _ := g.query(makeDatalogPredicate(p, op, args))
return ok
}
// AddRule adds a policy rule.
func (g *DatalogGuard) AddRule(rule string) error {
glog.Infof("Adding rule '%s'", rule)
var r auth.AnyForm
_, err := fmt.Sscanf("("+rule+")", "%v", &r)
if err != nil {
return err
}
return g.assert(r.Form)
}
// RetractRule removes a rule previously added via AddRule() or the
// equivalent Authorize() call.
func (g *DatalogGuard) RetractRule(rule string) error {
err := g.ReloadIfModified()
if err != nil {
return err
}
var r auth.AnyForm
_, err = fmt.Sscanf("("+rule+")", "%v", &r)
if err != nil {
return err
}
return g.retract(r.Form)
}
// Clear removes all rules.
func (g *DatalogGuard) Clear() error {
g.db.Rules = nil
g.dl = dlengine.NewEngine()
return nil
}
// Query the policy. Implementations of this interface should support
// at least queries of the form: Authorized(P, op, args...).
func (g *DatalogGuard) Query(query string) (bool, error) {
err := g.ReloadIfModified()
if err != nil {
return false, err
}
var r auth.AnyForm
_, err = fmt.Sscanf("("+query+")", "%v", &r)
if err != nil {
return false, err
}
return g.query(r.Form)
}
// RuleCount returns a count of the total number of rules.
func (g *DatalogGuard) RuleCount() int {
return len(g.db.Rules)
}
// GetRule returns the ith policy rule, if it exists.
func (g *DatalogGuard) GetRule(i int) string {
if i < 0 || i >= len(g.db.Rules) {
return ""
}
rule := g.db.Rules[i]
r, err := auth.UnmarshalForm(rule)
if err != nil {
return ""
}
return r.String()
}
// RuleDebugString returns a debug string for the ith policy rule, if it exists.
func (g *DatalogGuard) RuleDebugString(i int) string {
if i < 0 || i >= len(g.db.Rules) {
return ""
}
rule := g.db.Rules[i]
r, err := auth.UnmarshalForm(rule)
if err != nil {
return ""
}
return r.ShortString()
}
// String returns a string suitable for showing users authorization info.
func (g *DatalogGuard) String() string {
rules := make([]string, len(g.db.Rules))
for i := range g.db.Rules {
rules[i] = g.GetRule(i)
}
return "DatalogGuard{\n" + strings.Join(rules, "\n") + "}\n"
}