Class: Yast::GPGClass

Inherits:
Module
  • Object
show all
Defined in:
library/gpg/src/modules/GPG.rb

Instance Method Summary collapse

Instance Method Details

#buildGPGcommand(options) ⇒ String

Build GPG option string

Parameters:

  • options (String)

    additional gpg options

Returns:

  • (String)

    gpg option string



91
92
93
94
95
96
97
# File 'library/gpg/src/modules/GPG.rb', line 91

def buildGPGcommand(options)
  home_opt = @home.empty? ? "" : "--homedir '#{String.Quote(@home)}' "
  ret = "gpg #{home_opt} #{options}"
  Builtins.y2milestone("gpg command: %1", ret)

  ret
end

#callGPG(options) ⇒ Hash

Execute gpg with the specified parameters, –homedir is added to the options

Parameters:

  • options (String)

    additional gpg options

Returns:

  • (Hash)

    result of the execution



102
103
104
105
106
107
108
109
110
111
112
# File 'library/gpg/src/modules/GPG.rb', line 102

def callGPG(options)
  command = Ops.add("LC_ALL=en_US.UTF-8 ", buildGPGcommand(options))

  ret = Convert.to_map(SCR.Execute(path(".target.bash_output"), command))

  if Ops.get_integer(ret, "exit", -1) != 0
    Builtins.y2error("gpg error: %1", ret)
  end

  deep_copy(ret)
end

#CreateKeyObject

Create a new gpg key. Executes 'gpg –gen-key' in an xterm window (in the QT UI) or in the terminal window (in the ncurses UI).



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
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
# File 'library/gpg/src/modules/GPG.rb', line 222

def CreateKey
  xterm = "/usr/bin/xterm"
  command = Ops.add("GPG_AGENT_INFO='' ", buildGPGcommand("--gen-key"))
  text_mode = Ops.get_boolean(UI.GetDisplayInfo, "TextMode", false)

  Builtins.y2debug("text_mode: %1", text_mode)

  ret = false

  if !text_mode
    if Ops.less_than(SCR.Read(path(".target.size"), xterm), 0)
      # FIXME: do it
      Report.Error(_("Xterm is missing, install xterm package."))
      return false
    end

    exit_file = Ops.add(
      Convert.to_string(SCR.Read(path(".target.tmpdir"))),
      "/gpg_tmp_exit_file"
    )
    if FileUtils.Exists(exit_file)
      SCR.Execute(path(".target.bash"), Ops.add("rm -f ", exit_file))
    end

    command = Ops.add(
      Ops.add(
        Ops.add(
          Ops.add(
            Ops.add(Ops.add("LC_ALL=en_US.UTF-8 ", xterm), " -e \""),
            command
          ),
          "; echo $? > "
        ),
        exit_file
      ),
      "\""
    )
    Builtins.y2internal("Executing: %1", command)

    # in Qt start GPG in a xterm window
    SCR.Execute(path(".target.bash"), command)

    if FileUtils.Exists(exit_file)
      # read the exit code from file
      # (the exit code from the SCR call above is the xterm exit code which is not what we want here)
      exit_code = Convert.to_string(
        SCR.Read(path(".target.string"), exit_file)
      )
      Builtins.y2milestone(
        "Read exit code from tmp file %1: %2",
        exit_file,
        exit_code
      )

      ret = exit_code == "0\n"
    else
      Builtins.y2warning("Exit file is missing, the gpg command has failed")
      ret = false
    end
  else
    command = Ops.add("LC_ALL=en_US.UTF-8 ", command)
    Builtins.y2internal("Executing in terminal: %1", command)
    # in ncurses use UI::RunInTerminal
    ret = UI.RunInTerminal(command) == 0
  end

  if ret
    # invalidate cache, force reloading
    Init(@home, true)
  end

  ret
end

#ExportAsciiPublicKey(keyid, file) ⇒ Boolean

Export a public gpg key in ACSII armored file.

Parameters:

  • keyid (String)

    id of the key

  • file (String)

    the target file

Returns:

  • (Boolean)

    true if the file has been successfuly signed



397
398
399
400
401
402
403
404
405
406
407
# File 'library/gpg/src/modules/GPG.rb', line 397

def ExportAsciiPublicKey(keyid, file)
  out = callGPG(
    Builtins.sformat(
      "-a --export '%1' > '%2'",
      String.Quote(keyid),
      String.Quote(file)
    )
  )

  Ops.get_integer(out, "exit", -1) == 0
end

#ExportPublicKey(keyid, file) ⇒ Boolean

Export a public gpg key in binary format.

Parameters:

  • keyid (String)

    id of the key

  • file (String)

    the target file

Returns:

  • (Boolean)

    true if the file has been successfuly signed



413
414
415
416
417
418
419
420
421
422
423
# File 'library/gpg/src/modules/GPG.rb', line 413

def ExportPublicKey(keyid, file)
  out = callGPG(
    Builtins.sformat(
      "--export '%1' > '%2'",
      String.Quote(keyid),
      String.Quote(file)
    )
  )

  Ops.get_integer(out, "exit", -1) == 0
end

#Init(home_dir, force) ⇒ Object

(Re)initialize the module, the cache is invalidated if the home directory is changed.

Parameters:

  • home_dir (String)

    home directory for gpg (location of the keyring)

  • force (Boolean)

    unconditionaly clear the key caches



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'library/gpg/src/modules/GPG.rb', line 71

def Init(home_dir, force)
  if home_dir != "" && FileUtils.IsDirectory(home_dir) != true
    Builtins.y2error("Path %1 is not a directory", home_dir)
    return false
  end

  if home_dir != @home || force
    # clear the cache, home has been changed
    @public_keys = nil
    @private_keys = nil
  end

  @home = home_dir

  true
end

#mainObject



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
# File 'library/gpg/src/modules/GPG.rb', line 37

def main
  Yast.import "UI"

  Yast.import "String"
  Yast.import "Report"
  Yast.import "FileUtils"

  textdomain "base"

  # value for --homedir gpg option, empty string means default home directory
  @home = ""

  # key cache
  @public_keys = nil
  # key cache
  @private_keys = nil

  # Map for parsing gpg output. Key is regexp, value is the key returned
  # in the result of the parsing.
  @parsing_map = {
    # secret key ID
    "^sec  .*/([^ ]*) "             => "id",
    # public key id
    "^pub  .*/([^ ]*) "             => "id",
    # user id
    "^uid *(.*)"                    => "uid",
    # fingerprint
    "^      Key fingerprint = (.*)" => "fingerprint"
  }
end

#parse_key(lines) ⇒ Hash

Parse gpg output using the parsing map

Parameters:

  • lines (Array<String>)

    gpg output (splitted into lines)

Returns:

  • (Hash)

    parsed output



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
# File 'library/gpg/src/modules/GPG.rb', line 117

def parse_key(lines)
  lines = deep_copy(lines)
  ret = {}

  Builtins.foreach(lines) do |line|
    Builtins.foreach(@parsing_map) do |regexp, key|
      parsed = Builtins.regexpsub(line, regexp, "\\1")
      if !parsed.nil?
        # there might be more UIDs
        if key == "uid"
          Builtins.y2milestone("%1: %2", key, parsed)
          Ops.set(ret, key, Builtins.add(Ops.get_list(ret, key, []), parsed))
        else
          if Builtins.haskey(ret, key)
            Builtins.y2warning(
              "Key %1: replacing old value '%2' with '%3'",
              key,
              Ops.get_string(ret, key, ""),
              parsed
            )
          end
          Ops.set(ret, key, parsed)
        end
      end
    end
  end

  Builtins.y2milestone("Parsed key: %1", ret)

  deep_copy(ret)
end

#parseKeys(input) ⇒ Array<Hash>

Parse gpg output

Parameters:

  • input (String)

    gpg output

Returns:

  • (Array<Hash>)

    parsed keys



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
177
178
179
180
181
182
183
184
185
186
187
188
# File 'library/gpg/src/modules/GPG.rb', line 152

def parseKeys(input)
  # note: see /usr/share/doc/packages/gpg/DETAILS for another way

  ret = []
  lines = Builtins.splitstring(input, "\n")

  if Ops.greater_than(Builtins.size(input), 2)
    # remove the header
    lines = Builtins.remove(lines, 0)
    lines = Builtins.remove(lines, 0)
  end

  key_lines = []
  key_line_list = []

  # create groups
  Builtins.foreach(lines) do |line|
    if line == ""
      key_lines = Builtins.add(key_lines, key_line_list)
      key_line_list = []
    else
      key_line_list = Builtins.add(key_line_list, line)
    end
  end

  # parse each group to map
  Builtins.foreach(key_lines) do |keylines|
    parsed = parse_key(keylines)
    if Ops.greater_than(Builtins.size(parsed), 0)
      ret = Builtins.add(ret, parsed)
    end
  end

  Builtins.y2milestone("Parsed keys: %1", ret)

  deep_copy(ret)
end

#PrivateKeysArray<Hash> public keys: [ $["fingerprint": String key_fingerprint, "id": String key_ID, "uid": Array<String>] user_ids], ...

Return list of the private keys in the keyring.

Returns:

  • (Array<Hash> public keys: [ $["fingerprint": String key_fingerprint, "id": String key_ID, "uid": Array<String>] user_ids], ...)


207
208
209
210
211
212
213
214
215
216
217
218
# File 'library/gpg/src/modules/GPG.rb', line 207

def PrivateKeys
  # return the cached values if available
  return deep_copy(@private_keys) if !@private_keys.nil?

  out = callGPG("--list-secret-keys --fingerprint")

  if Ops.get_integer(out, "exit", -1) == 0
    @private_keys = parseKeys(Ops.get_string(out, "stdout", ""))
  end

  deep_copy(@private_keys)
end

#PublicKeysArray<Hash> public keys: [ $["fingerprint": String key_fingerprint, "id": String key_ID, "uid": Array<String>] user_ids], ...

Return list of the public keys in the keyring.

Returns:

  • (Array<Hash> public keys: [ $["fingerprint": String key_fingerprint, "id": String key_ID, "uid": Array<String>] user_ids], ...)


192
193
194
195
196
197
198
199
200
201
202
203
# File 'library/gpg/src/modules/GPG.rb', line 192

def PublicKeys
  # return the cached values if available
  return deep_copy(@public_keys) if !@public_keys.nil?

  out = callGPG("--list-keys --fingerprint")

  if Ops.get_integer(out, "exit", -1) == 0
    @public_keys = parseKeys(Ops.get_string(out, "stdout", ""))
  end

  deep_copy(@public_keys)
end

#SignAsciiDetached(keyid, file, passphrase) ⇒ Boolean

Sign a file. The ASCII armored signature is stored in file with .asc suffix

Parameters:

  • keyid (String)

    id of the signing key

  • file (String)

    the file to sign

  • passphrase (String)

    passphrase to unlock the private key

Returns:

  • (Boolean)

    true if the file has been successfuly signed



364
365
366
# File 'library/gpg/src/modules/GPG.rb', line 364

def SignAsciiDetached(keyid, file, passphrase)
  SignFile(keyid, file, passphrase, true)
end

#SignDetached(keyid, file, passphrase) ⇒ Boolean

Sign a file. The binary signature is stored in file with .sig suffix

Parameters:

  • keyid (String)

    id of the signing key

  • file (String)

    the file to sign

  • passphrase (String)

    passphrase to unlock the private key

Returns:

  • (Boolean)

    true if the file has been successfuly signed



373
374
375
# File 'library/gpg/src/modules/GPG.rb', line 373

def SignDetached(keyid, file, passphrase)
  SignFile(keyid, file, passphrase, false)
end

#SignFile(keyid, file, passphrase, ascii_signature) ⇒ Boolean

Sign a file. The ASCII armored signature is stored in file with .asc suffix

Parameters:

  • keyid (String)

    id of the signing key

  • file (String)

    the file to sign

  • passphrase (String)

    passphrase to unlock the private key

  • ascii_signature (Boolean)

    if true ASCII armored signature is created (with suffix .asc) otherwise binary signature (with suffix .sig) is created

Returns:

  • (Boolean)

    true if the file has been successfuly signed



303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'library/gpg/src/modules/GPG.rb', line 303

def SignFile(keyid, file, passphrase, ascii_signature)
  if passphrase.nil? || keyid.nil? || keyid == "" || file.nil? ||
      file == ""
    Builtins.y2error(
      "Invalid parameters: keyid: %1, file: %2, passphrase: %3",
      keyid,
      file,
      passphrase
    )
    return false
  end

  # signature suffix depends on the format
  suffix = ascii_signature ? ".asc" : ".sig"

  if Ops.greater_or_equal(
    Convert.to_integer(
      SCR.Read(path(".target.size"), Ops.add(file, suffix))
    ),
    0
  )
    # remove the existing key
    SCR.Execute(
      path(".target.bash"),
      Builtins.sformat("rm -f '%1%2'", String.Quote(file), suffix)
    )
  end

  # save the passphrase to a file
  tmpfile = Ops.add(
    Convert.to_string(SCR.Read(path(".target.tmpdir"))),
    "/stdin"
  )

  written = SCR.Write(
    path(".target.string"),
    tmpfile,
    Ops.add(passphrase, "\n")
  )

  return false if !written

  # use the passphrase
  out = callGPG(
    Builtins.sformat(
      "--detach-sign -u '%1' --no-tty --batch --command-fd=0 --passphrase-fd 0 %2 '%3' < '%4'",
      String.Quote(keyid),
      ascii_signature ? "-a" : "",
      String.Quote(file),
      String.Quote(tmpfile)
    )
  )

  Ops.get_integer(out, "exit", -1) == 0
end

#VerifyFile(sig_file, file) ⇒ Boolean

Verify a file using a signature file. The key which has been used for signing must be imported in the keyring.

Parameters:

  • sig_file (String)

    file with the signature

  • file (String)

    file to verify

Returns:

  • (Boolean)

    true if the file has been successfuly verified



381
382
383
384
385
386
387
388
389
390
391
# File 'library/gpg/src/modules/GPG.rb', line 381

def VerifyFile(sig_file, file)
  out = callGPG(
    Builtins.sformat(
      "--verify '%1' '%2'",
      String.Quote(sig_file),
      String.Quote(file)
    )
  )

  Ops.get_integer(out, "exit", -1) == 0
end