| 1 | // Copyright 2023 Google LLC. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | // Package common implements common functionality for dealing with text/template. |
| 16 | package common |
| 17 | |
| 18 | import ( |
| 19 | "io" |
| 20 | "reflect" |
| 21 | "text/template" |
| 22 | "text/template/parse" |
| 23 | "unicode" |
| 24 | "unicode/utf8" |
| 25 | |
| 26 | "github.com/google/safetext/lockedcallbacks" |
| 27 | ) |
| 28 | |
| 29 | const textTemplateRemediationFuncName = "ApplyInjectionDetection" |
| 30 | |
| 31 | // EchoString is a nop string callback |
| 32 | func EchoString(in string) string { |
| 33 | return in |
| 34 | } |
| 35 | |
| 36 | // BaselineString is a string callback function that just returns a constant string, |
| 37 | // used to get a baseline of how the resultant YAML is structured. |
| 38 | func BaselineString(string) string { |
| 39 | return "baseline" |
| 40 | } |
| 41 | |
| 42 | // The safetext library is executing each template multiple times. The goal is to see differences |
| 43 | // when user's input are used and detect modifications to the structure (e.g. YAML keys). |
| 44 | // text/template have a FuncMap that can be used to add functions called during the execution of |
| 45 | // templates. Yet, those functions cannot be updated once the template has been parsed. As safetext |
| 46 | // is modifying a specific function (to detect injection) during executions, a wrapper was |
| 47 | // introduced and a function pointer is updated for each template. |
| 48 | // statesmap hold those function pointers for each template that is processed by the library |
| 49 | // instance. |
| 50 | var statesmap = lockedcallbacks.New() |
| 51 | |
| 52 | // BuildTextTemplateFuncMap generates a per template (using its name as identifier) FuncMap. |
| 53 | // A Virtual callback is created as once Template.Parse() is called this is not something we can |
| 54 | // update. However, in its current design, safetext requires changing the methods as templates are |
| 55 | // executed multiple times and outputs are diffed to detect injection |
| 56 | func BuildTextTemplateFuncMap(safeTmplUUID string) map[string]any { |
| 57 | templateRemediationFunc := statesmap.BuildTextTemplateRemediationFunc(safeTmplUUID, DeepCopyMutateStrings) |
| 58 | templateFuncMap := map[string]any{ |
| 59 | textTemplateRemediationFuncName: templateRemediationFunc, |
| 60 | "StructuralData": func(data any) any { return data }, |
| 61 | |
| 62 | // Sh specific callbacks |
| 63 | "AllowFlags": statesmap.BuildAllowFlagsCallbackFunc(safeTmplUUID, DeepCopyMutateStrings), |
| 64 | } |
| 65 | return templateFuncMap |
| 66 | } |
| 67 | |
| 68 | // ExecuteWithCallback performs an execution on a callback-applied template |
| 69 | // (WalkApplyFuncToNonDeclaractiveActions) with a specified callback. |
| 70 | func ExecuteWithCallback(tmpl *template.Template, safeTmplUUID string, cb func(string) string, result io.Writer, data any) error { |
| 71 | return statesmap.SetAndExecuteWithCallback(tmpl, safeTmplUUID, cb, result, data) |
| 72 | } |
| 73 | |
| 74 | // ExecuteWithShCallback is like ExecuteWithCallback, but with the additional sh-specific callbacks specified. |
| 75 | func ExecuteWithShCallback(tmpl *template.Template, safeTmplUUID string, cb func(string) string, allowFlagsCb func(string) string, result io.Writer, data any) error { |
| 76 | return statesmap.SetAndExecuteWithShCallback(tmpl, safeTmplUUID, cb, allowFlagsCb, result, data) |
| 77 | } |
| 78 | |
| 79 | func makePointer(data any) any { |
| 80 | rtype := reflect.New(reflect.TypeOf(data)) |
| 81 | rtype.Elem().Set(reflect.ValueOf(data)) |
| 82 | return rtype.Interface() |
| 83 | } |
| 84 | |
| 85 | func dereference(data any) any { |
| 86 | return reflect.ValueOf(data).Elem().Interface() |
| 87 | } |
| 88 | |
| 89 | // DeepCopyMutateStrings performs a deep copy, but mutates any strings according to the mutation callback. |
| 90 | func DeepCopyMutateStrings(data any, mutateF func(string) string) any { |
| 91 | var r any |
| 92 | |
| 93 | if data == nil { |
| 94 | return nil |
| 95 | } |
| 96 | |
| 97 | switch reflect.TypeOf(data).Kind() { |
| 98 | case reflect.Pointer: |
| 99 | p := reflect.ValueOf(data) |
| 100 | if p.IsNil() { |
| 101 | r = data |
| 102 | } else { |
| 103 | c := DeepCopyMutateStrings(dereference(data), mutateF) |
| 104 | r = makePointer(c) |
| 105 | |
| 106 | // Sometimes we accidentally introduce one too many layers of indirection (seems related to protobuf generated fields like ReleaseNamespace *ReleaseNamespace `... reflect:"unexport"`) |
| 107 | if reflect.TypeOf(r) != reflect.TypeOf(data) { |
| 108 | r = c |
| 109 | } |
| 110 | } |
| 111 | case reflect.String: |
| 112 | return mutateF(reflect.ValueOf(data).String()) |
| 113 | case reflect.Slice, reflect.Array: |
| 114 | rc := reflect.MakeSlice(reflect.TypeOf(data), reflect.ValueOf(data).Len(), reflect.ValueOf(data).Len()) |
| 115 | for i := 0; i < reflect.ValueOf(data).Len(); i++ { |
| 116 | rc.Index(i).Set(reflect.ValueOf(DeepCopyMutateStrings(reflect.ValueOf(data).Index(i).Interface(), mutateF))) |
| 117 | } |
| 118 | r = rc.Interface() |
| 119 | case reflect.Map: |
| 120 | rc := reflect.MakeMap(reflect.TypeOf(data)) |
| 121 | dataIter := reflect.ValueOf(data).MapRange() |
| 122 | for dataIter.Next() { |
| 123 | rc.SetMapIndex(dataIter.Key(), reflect.ValueOf(DeepCopyMutateStrings(dataIter.Value().Interface(), mutateF))) |
| 124 | } |
| 125 | r = rc.Interface() |
| 126 | case reflect.Struct: |
| 127 | s := reflect.New(reflect.TypeOf(data)) |
| 128 | |
| 129 | t := reflect.TypeOf(data) |
| 130 | v := reflect.ValueOf(data) |
| 131 | n := v.NumField() |
| 132 | for i := 0; i < n; i++ { |
| 133 | r, _ := utf8.DecodeRuneInString(t.Field(i).Name) |
| 134 | |
| 135 | // Don't copy unexported fields |
| 136 | if unicode.IsUpper(r) { |
| 137 | reflect.Indirect(s).Field(i).Set( |
| 138 | reflect.ValueOf(DeepCopyMutateStrings(v.Field(i).Interface(), mutateF)), |
| 139 | ) |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | r = s.Interface() |
| 144 | default: |
| 145 | // No other types need special handling (int, bool, etc) |
| 146 | r = data |
| 147 | } |
| 148 | |
| 149 | return r |
| 150 | } |
| 151 | |
| 152 | func applyPipeCmds(cmds []*parse.CommandNode) { |
| 153 | for _, c := range cmds { |
| 154 | newArgs := make([]parse.Node, 0) |
| 155 | for i, a := range c.Args { |
| 156 | switch a := a.(type) { |
| 157 | case *parse.DotNode, *parse.FieldNode, *parse.VariableNode: |
| 158 | if i == 0 && len(c.Args) > 1 { |
| 159 | // If this is the first "argument" of multiple, then it is really a function |
| 160 | newArgs = append(newArgs, a) |
| 161 | } else { |
| 162 | // If this node is an argument to a call to "StructuralData", then pass it through as-is |
| 163 | switch identifier := c.Args[0].(type) { |
| 164 | case *parse.IdentifierNode: |
| 165 | if identifier.Ident == "StructuralData" { |
| 166 | newArgs = append(newArgs, a) |
| 167 | continue |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | newPipe := &parse.PipeNode{NodeType: parse.NodePipe, Decl: nil} |
| 172 | newPipe.Cmds = []*parse.CommandNode{ |
| 173 | &parse.CommandNode{NodeType: parse.NodeCommand, Args: []parse.Node{a}}, |
| 174 | &parse.CommandNode{NodeType: parse.NodeCommand, Args: []parse.Node{ |
| 175 | &parse.IdentifierNode{ |
| 176 | NodeType: parse.NodeIdentifier, |
| 177 | Ident: textTemplateRemediationFuncName, |
| 178 | }, |
| 179 | }}, |
| 180 | } |
| 181 | newArgs = append(newArgs, newPipe) |
| 182 | } |
| 183 | case *parse.PipeNode: |
| 184 | applyPipeCmds(a.Cmds) |
| 185 | newArgs = append(newArgs, a) |
| 186 | default: |
| 187 | newArgs = append(newArgs, a) |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | c.Args = newArgs |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | func branchNode(node parse.Node) *parse.BranchNode { |
| 196 | switch node := node.(type) { |
| 197 | case *parse.IfNode: |
| 198 | return &node.BranchNode |
| 199 | case *parse.RangeNode: |
| 200 | return &node.BranchNode |
| 201 | case *parse.WithNode: |
| 202 | return &node.BranchNode |
| 203 | } |
| 204 | |
| 205 | return nil |
| 206 | } |
| 207 | |
| 208 | // WalkApplyFuncToNonDeclaractiveActions walks the AST, applying a pipeline function to any "paste" nodes (non-declarative action nodes) |
| 209 | func WalkApplyFuncToNonDeclaractiveActions(template *template.Template, node parse.Node) { |
| 210 | switch node := node.(type) { |
| 211 | case *parse.ActionNode: |
| 212 | // Non-declarative actions are paste actions |
| 213 | if len(node.Pipe.Decl) == 0 { |
| 214 | applyPipeCmds(node.Pipe.Cmds) |
| 215 | } |
| 216 | |
| 217 | case *parse.IfNode, *parse.RangeNode, *parse.WithNode: |
| 218 | nodeBranch := branchNode(node) |
| 219 | WalkApplyFuncToNonDeclaractiveActions(template, nodeBranch.List) |
| 220 | if nodeBranch.ElseList != nil { |
| 221 | WalkApplyFuncToNonDeclaractiveActions(template, nodeBranch.ElseList) |
| 222 | } |
| 223 | case *parse.ListNode: |
| 224 | for _, node := range node.Nodes { |
| 225 | WalkApplyFuncToNonDeclaractiveActions(template, node) |
| 226 | } |
| 227 | case *parse.TemplateNode: |
| 228 | tmpl := template.Lookup(node.Name) |
| 229 | if tmpl != nil { |
| 230 | treeCopy := tmpl.Tree.Copy() |
| 231 | WalkApplyFuncToNonDeclaractiveActions(tmpl, treeCopy.Root) |
| 232 | template.AddParseTree(node.Name, treeCopy) |
| 233 | } |
| 234 | } |
| 235 | } |