Class: Puppet::Application::Ssl

Inherits:
Puppet::Application show all
Defined in:
lib/puppet/application/ssl.rb

Constant Summary

Constants inherited from Puppet::Application

DOCPATTERN

Constants included from Util

Util::AbsolutePathPosix, Util::AbsolutePathWindows, Util::DEFAULT_POSIX_MODE, Util::DEFAULT_WINDOWS_MODE, Util::RFC_3986_URI_REGEX

Constants included from Util::SymbolicFileMode

Util::SymbolicFileMode::SetGIDBit, Util::SymbolicFileMode::SetUIDBit, Util::SymbolicFileMode::StickyBit, Util::SymbolicFileMode::SymbolicMode, Util::SymbolicFileMode::SymbolicSpecialToBit

Constants included from Util::POSIX

Util::POSIX::LOCALE_ENV_VARS, Util::POSIX::USER_ENV_VARS

Instance Attribute Summary

Attributes inherited from Puppet::Application

#command_line, #options

Instance Method Summary collapse

Methods inherited from Puppet::Application

[], #app_defaults, available_application_names, banner, clear!, clear?, clear_everything_for_tests, #configure_indirector_routes, controlled_run, #deprecate, #deprecated?, environment_mode, exit, find, get_environment_mode, #handle_logdest_arg, #handlearg, #initialize_app_defaults, interrupted?, #log_runtime_environment, #name, option, option_parser_commands, #parse_options, #preinit, restart!, restart_requested?, #run, #run_command, run_mode, #set_log_level, #setup, stop!, stop_requested?, try_load_class

Methods included from Util

absolute_path?, benchmark, chuser, clear_environment, default_env, deterministic_rand, deterministic_rand_int, exit_on_fail, get_env, get_environment, logmethods, merge_environment, path_to_uri, pretty_backtrace, replace_file, safe_posix_fork, set_env, symbolizehash, thinmark, uri_encode, uri_query_encode, uri_to_path, which, withenv, withumask

Methods included from Util::SymbolicFileMode

#normalize_symbolic_mode, #symbolic_mode_to_int, #valid_symbolic_mode?

Methods included from Util::POSIX

#get_posix_field, #gid, groups_of, #idfield, #methodbyid, #methodbyname, #search_posix_field, #uid

Constructor Details

#initialize(command_line = Puppet::Util::CommandLine.new) ⇒ Ssl


87
88
89
90
91
92
93
94
# File 'lib/puppet/application/ssl.rb', line 87

def initialize(command_line = Puppet::Util::CommandLine.new)
  super(command_line)

  @cert_provider = Puppet::X509::CertProvider.new
  @ssl_provider = Puppet::SSL::SSLProvider.new
  @machine = Puppet::SSL::StateMachine.new
  @session = Puppet.runtime['http'].create_session
end

Instance Method Details

#clean(certname) ⇒ Object


221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/puppet/application/ssl.rb', line 221

def clean(certname)
  # make sure cert has been removed from the CA
  if certname == Puppet[:ca_server]
    cert = nil

    begin
      ssl_context = @machine.ensure_ca_certificates
      route = create_route(ssl_context)
      cert = route.get_certificate(certname, ssl_context: ssl_context)
    rescue Puppet::HTTP::ResponseError => e
      if e.response.code.to_i != 404
        raise Puppet::Error.new(_("Failed to connect to the CA to determine if certificate %{certname} has been cleaned") % { certname: certname }, e)
      end
    rescue => e
      raise Puppet::Error.new(_("Failed to connect to the CA to determine if certificate %{certname} has been cleaned") % { certname: certname }, e)
    end

    if cert
      raise Puppet::Error, _("The certificate %{certname} must be cleaned from the CA first. To fix this,\nrun the following commands on the CA:\npuppetserver ca clean --certname %{certname}\npuppet ssl clean\n") % { certname: certname }
    end
  end

  paths = {
    'private key' => Puppet[:hostprivkey],
    'public key'  => Puppet[:hostpubkey],
    'certificate request' => File.join(Puppet[:requestdir], "#{Puppet[:certname]}.pem"),
    'certificate' => Puppet[:hostcert],
    'private key password file' => Puppet[:passfile]
  }
  if options[:localca]
    paths['local CA certificate'] = Puppet[:localcacert]
    paths['local CRL'] = Puppet[:hostcrl]
  end
  paths.each_pair do |label, path|
    if Puppet::FileSystem.exist?(path)
      Puppet::FileSystem.unlink(path)
      Puppet.notice _("Removed %{label} %{path}") % { label: label, path: path }
    end
  end
end

#download_cert(ssl_context) ⇒ Object


178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/puppet/application/ssl.rb', line 178

def download_cert(ssl_context)
  key = @cert_provider.load_private_key(Puppet[:certname])

  # try to download cert
  route = create_route(ssl_context)
  Puppet.info _("Downloading certificate '%{name}' from %{url}") % { name: Puppet[:certname], url: route.url }

  x509 = route.get_certificate(Puppet[:certname], ssl_context: ssl_context)
  cert = OpenSSL::X509::Certificate.new(x509)
  Puppet.notice _("Downloaded certificate '%{name}' with fingerprint %{fingerprint}") % { name: Puppet[:certname], fingerprint: fingerprint(cert) }

  # verify client cert before saving
  @ssl_provider.create_context(
    cacerts: ssl_context.cacerts, crls: ssl_context.crls, private_key: key, client_cert: cert
  )
  @cert_provider.save_client_cert(Puppet[:certname], cert)
  @cert_provider.delete_request(Puppet[:certname])
  cert
rescue Puppet::HTTP::ResponseError => e
  if e.response.code == 404
    return nil
  else
    raise Puppet::Error.new(_("Failed to download certificate: %{message}") % { message: e.message }, e)
  end
rescue => e
  raise Puppet::Error.new(_("Failed to download certificate: %{message}") % { message: e.message }, e)
end

#helpObject


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
# File 'lib/puppet/application/ssl.rb', line 12

def help
  "puppet-ssl(8) -- \#{summary}\n========\n\nSYNOPSIS\n--------\nManage SSL keys and certificates for SSL clients needing\nto communicate with a puppet infrastructure.\n\nUSAGE\n-----\npuppet ssl <action> [-h|--help] [-v|--verbose] [-d|--debug] [--localca] [--target CERTNAME]\n\n\nOPTIONS\n-------\n\n* --help:\nPrint this help messsge.\n\n* --verbose:\nPrint extra information.\n\n* --debug:\nEnable full debugging.\n\n* --localca\nAlso clean the local CA certificate and CRL.\n\n* --target CERTNAME\nClean the specified device certificate instead of this host's certificate.\n\nACTIONS\n-------\n\n* bootstrap:\nPerform all of the steps necessary to request and download a client\ncertificate. If autosigning is disabled, then puppet will wait every\n`waitforcert` seconds for its certificate to be signed. To only attempt\nonce and never wait, specify a time of 0. Since `waitforcert` is a\nPuppet setting, it can be specified as a time interval, such as 30s,\n5m, 1h.\n\n* submit_request:\nGenerate a certificate signing request (CSR) and submit it to the CA. If\na private and public key pair already exist, they will be used to generate\nthe CSR. Otherwise a new key pair will be generated. If a CSR has already\nbeen submitted with the given `certname`, then the operation will fail.\n\n* download_cert:\nDownload a certificate for this host. If the current private key matches\nthe downloaded certificate, then the certificate will be saved and used\nfor subsequent requests. If there is already an existing certificate, it\nwill be overwritten.\n\n* verify:\nVerify the private key and certificate are present and match, verify the\ncertificate is issued by a trusted CA, and check revocation status.\n\n* clean:\nRemove the private key and certificate related files for this host. If\n`--localca` is specified, then also remove this host's local copy of the\nCA certificate(s) and CRL bundle. if `--target CERTNAME` is specified, then\nremove the files for the specified device on this host instead of this host.\n"
end

#mainObject


101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/puppet/application/ssl.rb', line 101

def main
  if command_line.args.empty?
    raise Puppet::Error, _("An action must be specified.")
  end

  if options[:target]
    # Override the following, as per lib/puppet/application/device.rb
    Puppet[:certname] = options[:target]
    Puppet[:confdir]  = File.join(Puppet[:devicedir], Puppet[:certname])
    Puppet[:vardir]   = File.join(Puppet[:devicedir], Puppet[:certname])
    Puppet.settings.use(:main, :agent, :device)
  else
    Puppet.settings.use(:main, :agent)
  end

  Puppet::SSL::Oids.register_puppet_oids

  certname = Puppet[:certname]
  action = command_line.args.first
  case action
  when 'submit_request'
    ssl_context = @machine.ensure_ca_certificates
    if submit_request(ssl_context)
      cert = download_cert(ssl_context)
      unless cert
        Puppet.info(_("The certificate for '%{name}' has not yet been signed") % { name: certname })
      end
    end
  when 'download_cert'
    ssl_context = @machine.ensure_ca_certificates
    cert = download_cert(ssl_context)
    unless cert
      raise Puppet::Error, _("The certificate for '%{name}' has not yet been signed") % { name: certname }
    end
  when 'verify'
    verify(certname)
  when 'clean'
    clean(certname)
  when 'bootstrap'
    if !Puppet::Util::Log.sendlevel?(:info)
      Puppet::Util::Log.level = :info
    end
    @machine.ensure_client_certificate
    Puppet.notice(_("Completed SSL initialization"))
  else
    raise Puppet::Error, _("Unknown action '%{action}'") % { action: action }
  end
end

#setup_logsObject


96
97
98
99
# File 'lib/puppet/application/ssl.rb', line 96

def setup_logs
  set_log_level(options)
  Puppet::Util::Log.newdestination(:console)
end

#submit_request(ssl_context) ⇒ Object


150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/puppet/application/ssl.rb', line 150

def submit_request(ssl_context)
  key = @cert_provider.load_private_key(Puppet[:certname])
  unless key
    if Puppet[:key_type] == 'ec'
      Puppet.info _("Creating a new EC SSL key for %{name} using curve %{curve}") % { name: Puppet[:certname], curve: Puppet[:named_curve] }
      key = OpenSSL::PKey::EC.generate(Puppet[:named_curve])
    else
      Puppet.info _("Creating a new SSL key for %{name}") % { name: Puppet[:certname] }
      key = OpenSSL::PKey::RSA.new(Puppet[:keylength].to_i)
    end
    @cert_provider.save_private_key(Puppet[:certname], key)
  end

  csr = @cert_provider.create_request(Puppet[:certname], key)
  route = create_route(ssl_context)
  route.put_certificate_request(Puppet[:certname], csr, ssl_context: ssl_context)
  @cert_provider.save_request(Puppet[:certname], csr)
  Puppet.notice _("Submitted certificate request for '%{name}' to %{url}") % { name: Puppet[:certname], url: route.url }
rescue Puppet::HTTP::ResponseError => e
  if e.response.code == 400
    raise Puppet::Error.new(_("Could not submit certificate request for '%{name}' to %{url} due to a conflict on the server") % { name: Puppet[:certname], url: route.url })
  else
    raise Puppet::Error.new(_("Failed to submit certificate request: %{message}") % { message: e.message }, e)
  end
rescue => e
  raise Puppet::Error.new(_("Failed to submit certificate request: %{message}") % { message: e.message }, e)
end

#summaryObject


8
9
10
# File 'lib/puppet/application/ssl.rb', line 8

def summary
  _("Manage SSL keys and certificates for puppet SSL clients")
end

#verify(certname) ⇒ Object


206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/puppet/application/ssl.rb', line 206

def verify(certname)
  password = @cert_provider.load_private_key_password
  ssl_context = @ssl_provider.load_context(certname: certname, password: password)

  # print from root to client
  ssl_context.client_chain.reverse.each_with_index do |cert, i|
    digest = Puppet::SSL::Digest.new('SHA256', cert.to_der)
    if i == ssl_context.client_chain.length - 1
      Puppet.notice("Verified client certificate '#{cert.subject.to_utf8}' fingerprint #{digest}")
    else
      Puppet.notice("Verified CA certificate '#{cert.subject.to_utf8}' fingerprint #{digest}")
    end
  end
end