| 1 | # safetext |
| 2 | |
| 3 | **This is not an officially supported Google product.** |
| 4 | |
| 5 | Safe-by-construction libraries for producing formats like YAML, to replace |
| 6 | syntax-unaware libraries like `text/template` and `sprintf` that are at risk of |
| 7 | injection vulnerabilities. |
| 8 | |
| 9 | ## Example use-case |
| 10 | |
| 11 | Since `text/template` is not syntax-aware of the formats it produces, it does |
| 12 | not offer any protection against injection vulnerabilities. |
| 13 | |
| 14 | Consider the following `produceConfig` function which uses `text/template` to |
| 15 | generate YAML: |
| 16 | |
| 17 | ``` |
| 18 | package main |
| 19 | |
| 20 | import ( |
| 21 | "bytes" |
| 22 | "fmt" |
| 23 | "text/template" |
| 24 | ) |
| 25 | |
| 26 | func produceConfig(params any) (error, string) { |
| 27 | tmpl, _ := template.New("test").Parse("{ hello: {{ .addressee }} }") |
| 28 | |
| 29 | var buf bytes.Buffer |
| 30 | err := tmpl.Execute(&buf, params) |
| 31 | if err != nil { |
| 32 | return err, "" |
| 33 | } |
| 34 | |
| 35 | return nil, buf.String() |
| 36 | } |
| 37 | |
| 38 | func main() { |
| 39 | goodReplacements := map[string]interface{}{ |
| 40 | "addressee": "safe", |
| 41 | } |
| 42 | |
| 43 | err, config := produceConfig(goodReplacements) |
| 44 | |
| 45 | if err == nil { |
| 46 | fmt.Println(config) |
| 47 | } else { |
| 48 | fmt.Printf("Error: %v\n", err) |
| 49 | } |
| 50 | |
| 51 | badReplacements := map[string]interface{}{ |
| 52 | "addressee": "world, oops: true", |
| 53 | } |
| 54 | |
| 55 | err, config = produceConfig(badReplacements) |
| 56 | |
| 57 | if err == nil { |
| 58 | fmt.Println(config) |
| 59 | } else { |
| 60 | fmt.Printf("Error: %v\n", err) |
| 61 | } |
| 62 | } |
| 63 | ``` |
| 64 | |
| 65 | This program demonstrates how a malicious `addressee` input can cause injection |
| 66 | of new YAML keys in the template execution result. |
| 67 | |
| 68 | With `text/template`, no errors will be encountered when this happens, and the |
| 69 | program output will be: |
| 70 | |
| 71 | ``` |
| 72 | { hello: safe } |
| 73 | { hello: world, oops: true } |
| 74 | ``` |
| 75 | |
| 76 | By instead switching from `text/template`to `safetext/yamltemplate`, the |
| 77 | injection would have been prevented, with the output instead being: |
| 78 | |
| 79 | ``` |
| 80 | { hello: safe } |
| 81 | Error: YAML Injection Detected |
| 82 | ``` |
| 83 | |
| 84 | ## Instructions for `text/template` replacements |
| 85 | |
| 86 | Injection detection is automatically applied when accessing input data fields. |
| 87 | |
| 88 | - It can also be manually enabled on the result of any function call: |
| 89 | |
| 90 | ``` |
| 91 | {{ RetrieveUntrustedData | ApplyInjectionDetection }} |
| 92 | ``` |
| 93 | |
| 94 | - The injection logic can be disabled on certain fields by applying the |
| 95 | `StructuralData` annotation: |
| 96 | |
| 97 | ``` |
| 98 | {{ (StructuralData .x) }} |
| 99 | ``` |
| 100 | |
| 101 | - The `StructuralData` annotation is also needed when passing an input to a |
| 102 | function where the input should not be mutated, such as a performing some |
| 103 | kind of lookup: |
| 104 | |
| 105 | ``` |
| 106 | name: {{ readFile (StructuralData .pathToName) | ApplyInjectionDetection }} |
| 107 | ``` |
| 108 | |
| 109 | - It is recommended to make full use of `text/template` features like |
| 110 | conditional expressions, range loops, etc to avoid the `StructuralData` |
| 111 | annotation where possible. For example, instead of: |
| 112 | |
| 113 | ``` |
| 114 | properties: |
| 115 | {{ (StructuralData .PropertiesYaml) }} |
| 116 | ``` |
| 117 | |
| 118 | Consider: |
| 119 | |
| 120 | ``` |
| 121 | properties:{{ range .Properties }} |
| 122 | - {{ . }}{{ end }} |
| 123 | ``` |
| 124 | |
| 125 | ### `yamltemplate` |
| 126 | |
| 127 | The intention of `yamltemplate` is to ensure that by-default none of the strings |
| 128 | in the input data affect the structure of the resultant YAML (just the values). |
| 129 | |
| 130 | - For example, the below template would be compatible with yamltemplate as-is, |
| 131 | whilst automatically preventing any injections from the `Name` input: |
| 132 | |
| 133 | ``` |
| 134 | name: {{.Name}} |
| 135 | ``` |
| 136 | |
| 137 | - However, any template nodes that *are* expected to change the resultant YAML |
| 138 | structure, such as inserting arbitrary YAML config, would need to be |
| 139 | annotated explicitly as `StructuralData`: |
| 140 | |
| 141 | ``` |
| 142 | config: {{ (StructuralData .Config) }} |
| 143 | ``` |
| 144 | |
| 145 | - Another case of needing the `StructuralData` annotation would be where you |
| 146 | need to include a complete map into the yaml structure. Using |
| 147 | `StructuralData` alone may let injections pass through via the key so we |
| 148 | need an extra layer of validation here: |
| 149 | |
| 150 | ~~~ |
| 151 | labels: |
| 152 | {{- range $key, $value := .Labels }} |
| 153 | {{ (StructuralData $key | MapKey) }}: {{ $value }} |
| 154 | {{- end }} |
| 155 | ``` |
| 156 | |
| 157 | The corresponding golang side could look like this: |
| 158 | |
| 159 | ~~~ |
| 160 | |
| 161 | func mapKeyFunc(data any) (string, error) { if v, ok := data.(string); ok { |
| 162 | matched, err := regexp.MatchString(`^[a-zA-Z0-9/\-.]+$`, v) if err != nil { |
| 163 | return "", err } if !matched { return "", fmt.Errorf("invalid characters in |
| 164 | the key: %v", v) } return v, nil } |
| 165 | |
| 166 | ``` |
| 167 | return "", errors.New("invalid input") |
| 168 | ``` |
| 169 | |
| 170 | } ... |
| 171 | |
| 172 | tmp:= template.New("something") tmp.Funcs(map[string]any{"MapKey": |
| 173 | mapKeyFunc}) tmpl := template.Must(tmp.Parse(yamlTemplate)) ``` |
| 174 | |
| 175 | - You can combine `yamltemplate` with `shprintf`. Consider the following |
| 176 | cloud-init yaml template: |
| 177 | |
| 178 | ``` |
| 179 | --- |
| 180 | write_files: |
| 181 | - path: /etc/nginx/refresh.sh |
| 182 | owner: root:root |
| 183 | permissions: 0755 # Don't forget the 0 (you are probably using octal...) |
| 184 | content: | |
| 185 | #!/bin/bash |
| 186 | set -euo pipefail |
| 187 | |
| 188 | {{ shprintf `curl %s > /tmp/something` .userInput }} |
| 189 | ``` |
| 190 | |
| 191 | Evaluating this template with safetext/yamltemplate, both shell command and |
| 192 | YAML injections will be prevented. |
| 193 | |
| 194 | To do this, you need to setup the golang side like this: |
| 195 | |
| 196 | ``` |
| 197 | tmp:= addons.WithShsprintf(template.New("something")) |
| 198 | tmpl := template.Must(tmp.Parse(yamlTemplate)) |
| 199 | ``` |
| 200 | |
| 201 | #### Unsupported use cases for `yamltemplate` |
| 202 | |
| 203 | - YAML with duplicate keys. Duplicate keys are non-standard YAML, and not |
| 204 | supported by this library. Please refactor your YAML template to remove |
| 205 | duplicate keys. For example: |
| 206 | |
| 207 | ``` |
| 208 | - project: |
| 209 | members: member-a |
| 210 | members: member-b |
| 211 | ``` |
| 212 | |
| 213 | To: |
| 214 | |
| 215 | ``` |
| 216 | - project: |
| 217 | members: member-b |
| 218 | ``` |
| 219 | |
| 220 | ### `shtemplate` |
| 221 | |
| 222 | `shtemplate` is designed to allow you to generate shell scripts with the |
| 223 | guarantee that none of the input data strings will be able to inject new |
| 224 | commands or flags, without explicit annotation. |
| 225 | |
| 226 | - For example, a template script designed to just print one string will fail |
| 227 | to render if that string injects a new command `` `./evil` ``: |
| 228 | |
| 229 | ``` |
| 230 | echo "{{ .addressee }}" |
| 231 | ``` |
| 232 | |
| 233 | - To explicitly allow an input string to contain new commands not from the |
| 234 | template string, the `StructuralData` annotation can be used: |
| 235 | |
| 236 | ``` |
| 237 | {{ (StructuralData .commands) }} |
| 238 | ``` |
| 239 | |
| 240 | - Flags (arguments starting with `-`) are also forbidden by-default. For |
| 241 | example, the below template will fail to render if `Filename` is |
| 242 | `--interactive`: |
| 243 | |
| 244 | ``` |
| 245 | git add {{ .Filename }} |
| 246 | ``` |
| 247 | |
| 248 | - To explicitly allow an input string passed as a command argument to be a |
| 249 | flag, the `AllowFlags` annotation can be used: |
| 250 | |
| 251 | ``` |
| 252 | git add {{ (AllowFlags .FilenameOrGitAddFlag) }} |
| 253 | ``` |
| 254 | |
| 255 | - Multiple arguments from a single input string is also forbidden by-default. |
| 256 | This construct should instead be implemented using an array and `range` |
| 257 | expression: |
| 258 | |
| 259 | ``` |
| 260 | ls {{ range .Paths }}{{.}} {{end}} |
| 261 | ``` |
| 262 | |
| 263 | ### Unsupported use-cases for `text/template` replacements |
| 264 | |
| 265 | - Escaping logic outside of the templating system. Instead, you should |
| 266 | annotate the escaping logic into your template (EG: `.UntrustedField | |
| 267 | escape`). |
| 268 | |
| 269 | - Partial formats. The libraries are designed to be used for generating |
| 270 | complete files. If you generate segments and then concatenate them together, |
| 271 | you should instead move this logic into the templating system itself (using |
| 272 | constructs like `if` or `range`). |
| 273 | |
| 274 | - Functions with side effects. The libraries work by performing multiple |
| 275 | template executions, so if you register functions that have side effects, |
| 276 | this could cause unexpected behaviour (EG: `id: {{ AllocateID }}`). |
| 277 | |
| 278 | ## `shsprintf` |
| 279 | |
| 280 | `shsprintf` is designed to allow you to generate shell scripts with the |
| 281 | guarantee that none of the input data strings will be able to inject new |
| 282 | commands or flags regardless of potentially incorrect escaping. See the below |
| 283 | example, which will return the error `shsprintf.ErrShInjection` instead of the |
| 284 | script with an injected command: |
| 285 | |
| 286 | ``` |
| 287 | message := "`whoami`" |
| 288 | result, err := shsprintf.Sprintf("git commit -m %s", message) |
| 289 | ``` |
| 290 | |
| 291 | `shsprintf.Sprintf` adds an error return value compared to `fmt.Sprintf`, but |
| 292 | the API is otherwise the same. `shsprintf.MustSprintf` is available for cases |
| 293 | where panic is acceptable. |
| 294 | |
| 295 | `shsprintf` comes with an escaping function that is recommended for use: |
| 296 | |
| 297 | ``` |
| 298 | message := "`whoami`" |
| 299 | result := shsprintf.MustSprintf("git commit -m %s", shsprintf.EscapeDefaultContext(message)) |
| 300 | ``` |
| 301 | |
| 302 | Unlike with `text/template` there are no special annotations. If you need to |
| 303 | pass multiple arguments for example, this should be done by altering the format |
| 304 | string: |
| 305 | |
| 306 | ``` |
| 307 | files := []any{ "file1", "file2", "file3" } |
| 308 | result, err := shsprintf.Sprintf("cat" + strings.Repeat(" %s", len(files)), files...) |
| 309 | ``` |