How do you keep `sh` commands safe from injection inside library steps?
AdvancedConceptShared libraries
Answer
Arguments interpolated into sh strings can come from branch names, PR titles or parameters, which attackers control. Pass values through the environment instead of interpolating, and quote them in the shell.
withEnv(["IMAGE_REF=${cfg.image}"]) {
sh 'crane push image.tar "$IMAGE_REF"'
}
Validate inputs with a regex (cfg.image ==~ /^[a-z0-9.\/:_-]+$/) before use.
More on Shared libraries
What is the directory structure of a shared library?BeginnerHow does a `vars/` global step work?BeginnerWhat goes in `src/` and how is it used?IntermediateHow do classes in `src/` call pipeline steps?IntermediateWhat is `libraryResource` used for?IntermediateWhat are the ways to load a library in a Jenkinsfile?Intermediate