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::ALNUM, Util::ALPHA, Util::AbsolutePathPosix, Util::AbsolutePathWindows, Util::DEFAULT_POSIX_MODE, Util::DEFAULT_WINDOWS_MODE, Util::ESCAPED, Util::HEX, Util::HttpProxy, Util::PUPPET_STACK_INSERTION_FRAME, Util::RESERVED, Util::RFC_3986_URI_REGEX, Util::UNRESERVED, Util::UNSAFE

Constants included from Util::POSIX

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

Constants included from Util::SymbolicFileMode

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

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, create_erb, default_env, deterministic_rand, deterministic_rand_int, exit_on_fail, format_backtrace_array, format_puppetstack_frame, get_env, get_environment, logmethods, merge_environment, path_to_uri, pretty_backtrace, replace_file, resolve_stackframe, rfc2396_escape, safe_posix_fork, set_env, skip_external_facts, symbolizehash, thinmark, uri_encode, uri_query_encode, uri_to_path, uri_unescape, which, withenv, withumask

Methods included from Util::POSIX

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

Methods included from Util::SymbolicFileMode

#display_mode, #normalize_symbolic_mode, #symbolic_mode_to_int, #valid_symbolic_mode?

Constructor Details

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

Returns a new instance of Ssl.



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

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



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/puppet/application/ssl.rb', line 260

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, _(<<~END) % { certname: certname }
        The certificate %{certname} must be cleaned from the CA first. To fix this,
        run the following commands on the CA:
          puppetserver ca clean --certname %{certname}
          puppet ssl clean
      END
    end
  end

  paths = {
    'private key' => Puppet[:hostprivkey],
    'public key' => Puppet[:hostpubkey],
    'certificate request' => Puppet[:hostcsr],
    '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



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/puppet/application/ssl.rb', line 217

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
    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

#generate_request(certname) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/puppet/application/ssl.rb', line 203

def generate_request(certname)
  key = @cert_provider.load_private_key(certname)
  unless key
    key = create_key(certname)
    @cert_provider.save_private_key(certname, key)
  end

  csr = @cert_provider.create_request(certname, key)
  @cert_provider.save_request(certname, csr)
  Puppet.notice _("Generated certificate request in '%{path}'") % { path: @cert_provider.to_path(Puppet[:requestdir], certname) }
rescue => e
  raise Puppet::Error.new(_("Failed to generate certificate request: %{message}") % { message: e.message }, e)
end

#helpObject



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

def help
  <<~HELP
    puppet-ssl(8) -- #{summary}
    ========

    SYNOPSIS
    --------
    Manage SSL keys and certificates for SSL clients needing
    to communicate with a puppet infrastructure.

    USAGE
    -----
    puppet ssl <action> [-h|--help] [-v|--verbose] [-d|--debug] [--localca] [--target CERTNAME]


    OPTIONS
    -------

    * --help:
      Print this help message.

    * --verbose:
      Print extra information.

    * --debug:
      Enable full debugging.

    * --localca
      Also clean the local CA certificate and CRL.

    * --target CERTNAME
      Clean the specified device certificate instead of this host's certificate.

    ACTIONS
    -------

    * bootstrap:
      Perform all of the steps necessary to request and download a client
      certificate. If autosigning is disabled, then puppet will wait every
      `waitforcert` seconds for its certificate to be signed. To only attempt
      once and never wait, specify a time of 0. Since `waitforcert` is a
      Puppet setting, it can be specified as a time interval, such as 30s,
      5m, 1h.

    * submit_request:
      Generate a certificate signing request (CSR) and submit it to the CA. If
      a private and public key pair already exist, they will be used to generate
      the CSR. Otherwise, a new key pair will be generated. If a CSR has already
      been submitted with the given `certname`, then the operation will fail.

    * generate_request:
      Generate a certificate signing request (CSR). If a private and public key
      pair exist, they will be used to generate the CSR. Otherwise a new key
      pair will be generated.

    * download_cert:
      Download a certificate for this host. If the current private key matches
      the downloaded certificate, then the certificate will be saved and used
      for subsequent requests. If there is already an existing certificate, it
      will be overwritten.

    * verify:
      Verify the private key and certificate are present and match, verify the
      certificate is issued by a trusted CA, and check revocation status.

    * clean:
      Remove the private key and certificate related files for this host. If
      `--localca` is specified, then also remove this host's local copy of the
      CA certificate(s) and CRL bundle. if `--target CERTNAME` is specified, then
      remove the files for the specified device on this host instead of this host.

     * show:
      Print the full-text version of this host's certificate.
  HELP
end

#mainObject



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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/puppet/application/ssl.rb', line 110

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
  Puppet::SSL::Oids.load_custom_oid_file(Puppet[:trusted_oid_mapping_file])

  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 'generate_request'
    generate_request(certname)
  when 'verify'
    verify(certname)
  when 'clean'
    possible_extra_args = command_line.args.drop(1)
    unless possible_extra_args.empty?
      raise Puppet::Error, _(<<~END) % { args: possible_extra_args.join(' ') }
        Extra arguments detected: %{args}
        Did you mean to run:
          puppetserver ca clean --certname <name>
        Or:
          puppet ssl clean --target <name>
      END
    end

    clean(certname)
  when 'bootstrap'
    unless Puppet::Util::Log.sendlevel?(:info)
      Puppet::Util::Log.level = :info
    end
    @machine.ensure_client_certificate
    Puppet.notice(_("Completed SSL initialization"))
  when 'show'
    show(certname)
  else
    raise Puppet::Error, _("Unknown action '%{action}'") % { action: action }
  end
end

#setup_logsObject



105
106
107
108
# File 'lib/puppet/application/ssl.rb', line 105

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

#show(certname) ⇒ Object



175
176
177
178
179
# File 'lib/puppet/application/ssl.rb', line 175

def show(certname)
  password = @cert_provider.load_private_key_password
  ssl_context = @ssl_provider.load_context(certname: certname, password: password)
  puts ssl_context.client_cert.to_text
end

#submit_request(ssl_context) ⇒ Object



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

def submit_request(ssl_context)
  key = @cert_provider.load_private_key(Puppet[:certname])
  unless key
    key = create_key(Puppet[:certname])
    @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, _("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



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

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

#verify(certname) ⇒ Object



245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/puppet/application/ssl.rb', line 245

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