1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
# frozen_string_literal: true
module License
module Management
class Shell
SPLIT_SCRIPT = "'BEGIN {x=0;} /BEGIN CERT/{x++} { print > \"custom.\" x \".crt\" }'"
attr_reader :default_certificate_path, :custom_certificate_path, :logger
def initialize(logger: License::Management.logger, certificate: ENV['ADDITIONAL_CA_CERT_BUNDLE'])
@logger = logger
@custom_certificate_path = Pathname.new('/usr/local/share/ca-certificates/custom.crt')
@default_certificate_path = Pathname.new('/etc/ssl/certs/ca-certificates.crt')
trust!(certificate) if present?(certificate)
end
def execute(command, env: {})
expanded_command = expand(command)
collapsible_section(expanded_command) do
logger.debug(expanded_command)
stdout, stderr, status = Open3.capture3(env, expanded_command)
record(stdout, stderr, status)
[stdout, stderr, status]
end
end
def sh(command, env: {})
execute("sh -c '#{expand(command)}'", env: env)
end
def custom_certificate_installed?
present?(ENV['ADDITIONAL_CA_CERT_BUNDLE']) && custom_certificate_path.exist?
end
private
def expand(command)
Array(command).flatten.map(&:to_s).join(' ')
end
def trust!(certificate)
custom_certificate_path.write(certificate)
Dir.chdir custom_certificate_path.dirname do
execute([:awk, SPLIT_SCRIPT, '<', custom_certificate_path])
execute('update-ca-certificates -v')
Dir.glob('custom.*.crt').each do |path|
full_path = File.expand_path(path)
execute([:openssl, :x509, '-in', full_path, '-text', '-noout'])
execute(keytool_import_command(full_path))
execute(keytool_list_command)
end
end
execute([:cp, custom_certificate_path.to_s, "/usr/lib/ssl/certs/"])
execute([:c_rehash, '-v'])
end
def keytool_import_command(file_path)
[
:keytool,
'-importcert',
'-alias', Time.now.to_i,
'-file', file_path,
'-trustcacerts',
'-noprompt',
'-storepass', 'changeit',
'-keystore', keystore_path
]
end
def keytool_list_command
[:keytool, '-list', '-v', '-storepass changeit', '-keystore', keystore_path]
end
def keystore_path
"#{ENV['JAVA_HOME']}/jre/lib/security/cacerts"
end
def present?(item)
!item.nil? && !item.empty?
end
def record(stdout, stderr, status)
severity = status.success? ? Logger::DEBUG : Logger::ERROR
flush(stdout, severity)
flush(stderr, severity)
end
def flush(message, severity)
logger.add(severity, message) if present?(message)
end
def collapsible_section(header)
id = header.downcase.gsub(/[[:space:]]/, '_').gsub(/[^0-9a-z ]/i, '_')
logger.debug("\nsection_start:#{Time.now.to_i}:#{id}\r\e[0K#{header}")
yield
ensure
logger.debug("\nsection_end:#{Time.now.to_i}:#{id}\r\e[0K")
end
end
end
end
|