#
# Cookbook:: metasploitable
# Recipe:: Log4Shell vulnerability CVE-2021-44228
#
# Copyright:: 2021, juanjo sanz
# ref:https://vulndev.io/2021/12/11/lab-exploiting-log4shell-cve-2021-44228/

include_recipe 'iptables::default'

recipe_port = 8888

iptables_rule '1_log4shell' do
  lines "-A INPUT -p tcp --dport #{recipe_port} -j ACCEPT"
end

# apt_repository 'java-8-debian' do
#   uri          "ppa:webupd8team/java"
#   arch         'amd64'
#   distribution 'trusty'
#   components   ['main']
# #  keyserver "keyserver.ubuntu.com"
# #  key       "EEA14886"
# end

apt_repository 'openjdk-8' do
  uri   "ppa:openjdk-r/ppa"
end

package "openjdk-8-jdk" do
  action :upgrade
end

execute "set-default-java" do
  command   "update-alternatives --config java && update-alternatives --config javac"
  live_stream true
  action :run
end

execute "java -version" do
  command "java -version"
  live_stream true
  action :run
end

package 'maven' do
  action :install
end

package 'git' do
  action :install
end

git "/opt/log4shell" do
  repository "https://github.com/MscDevOpsSecurity/marshalsec"
  action :checkout
end

bash "Install dependencies" do
  code <<-EOH
    cd /opt/log4shell
    #mvn package -DskipTests
    mvn -X clean package -DskipTests
    # mvn -X package -DskipTests
    # exec # java -cp target/marshalsec-0.0.3-SNAPSHOT-all.jar marshalsec.jndi.LDAPRefServer "http://localhost:#{recipe_port}/#RCE"
  EOH
end

template '/opt/log4shell/start.sh' do
  variables( log4shell_port: recipe_port )
  source 'log4shell/start.sh.erb'
end

cookbook_file '/etc/init/log4shell.conf' do
  source 'log4shell/log4shell.conf'
  mode '0644'
end

bash 'set permissions' do
  cwd '/opt/log4shell'
  code <<-EOH
    chown -R chewbacca:users .
    git ls-files | xargs chmod 0644
    git ls-files | xargs -n 1 dirname | uniq | xargs chmod 755
    chmod 0755 ./start.sh
  EOH
end

service 'log4shell' do
  supports restart: false, start: true, reload: false, status: false
  action [:enable, :start]
end
