gpgmeh 0.1.5

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 18ad47927216f1fc2f0198efac0bee249bd14c10
4
+ data.tar.gz: 445dc578d888ef956021084712d8aa5e62147388
5
+ SHA512:
6
+ metadata.gz: 0ae6b61433e1c7031cdc3d114d87270161226ae366e313f3e8455692160abd3c8553789a4d04cc0741e639c311bc2348d02b61ac214534a969f0cf661d1bab9b
7
+ data.tar.gz: f7d397aa7cd1de1c50bbf155de91c529fdf4bcfab78e50e21e670392ce4f19714b6e3ca541d6cf234d8a2f760ada644102e759ec72e8106625880ba098e85e29
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ spec/support/rickhardslab/random_seed
11
+ spec/support/spacemanspiff/random_seed
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.rubocop.yml ADDED
@@ -0,0 +1,48 @@
1
+ AllCops:
2
+ DisplayCopNames: true
3
+ TargetRubyVersion: 2.4
4
+ Exclude:
5
+ - 'bin/*'
6
+ - 'spec/support/**/*'
7
+
8
+ ClassLength:
9
+ Max: 300
10
+
11
+ LineLength:
12
+ Max: 128
13
+
14
+ MethodLength:
15
+ Max: 40
16
+
17
+ Encoding:
18
+ Enabled: false
19
+
20
+ Lint/RescueWithoutErrorClass:
21
+ Enabled: false
22
+
23
+ Metrics/AbcSize:
24
+ Max: 70
25
+
26
+ Metrics/BlockLength:
27
+ Enabled: false
28
+
29
+ Metrics/CyclomaticComplexity:
30
+ Max: 25
31
+
32
+ Metrics/PerceivedComplexity:
33
+ Max: 25
34
+
35
+ Metrics/ParameterLists:
36
+ Enabled: false
37
+
38
+ Style/AlignParameters:
39
+ Enabled: false
40
+
41
+ Style/Documentation:
42
+ Enabled: false
43
+
44
+ Style/EmptyLiteral:
45
+ Enabled: False
46
+
47
+ Style/StringLiterals:
48
+ Enabled: false
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.3.5
4
+ - 2.4.2
5
+ sudo: false
data/BUG-BOUNTY.md ADDED
@@ -0,0 +1,9 @@
1
+ Serious about security
2
+ ======================
3
+
4
+ Square recognizes the important contributions the security research community
5
+ can make. We therefore encourage reporting security issues with the code
6
+ contained in this repository.
7
+
8
+ If you believe you have discovered a security vulnerability, please follow the
9
+ guidelines at https://hackerone.com/square-open-source
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 0.1.5 / 2017-11-21
4
+
5
+ * Update NIO version requirement
data/Gemfile ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in gpgmeh.gemspec
6
+ gemspec
7
+
8
+ gem "pry"
9
+ gem "rake"
10
+ gem "rspec", "~> 3.7"
11
+ gem "rubocop", "0.51.0"
12
+
13
+ platform :ruby do
14
+ gem "pry-byebug"
15
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,255 @@
1
+ # GPGMeh: GPG Made Even _HARDER_!
2
+
3
+ [![Build Status](https://travis-ci.org/square/gpgmeh.svg?branch=master)](https://travis-ci.org/square/gpgmeh)
4
+
5
+ ## Why?
6
+
7
+ GPG can be complicated: this gem is just a high level wrapper around `gpg`.
8
+ GPGME also provides a nice API on top of GPG, but it has two drawbacks: it is
9
+ not thread safe and it holds the GIL when shelling out to `gpg`. This holds up
10
+ the entire ruby process for the duration of the GPG call, which can be
11
+ relatively slow.
12
+
13
+ ## Installation
14
+
15
+ Add this line to your application's Gemfile:
16
+
17
+ ```ruby
18
+ gem 'gpgmeh'
19
+ ```
20
+
21
+ And then execute:
22
+
23
+ $ bundle
24
+
25
+ Or install it yourself as:
26
+
27
+ $ gem install gpgmeh
28
+
29
+ ## Usage
30
+
31
+ ### Default Configuration
32
+
33
+ ```ruby
34
+ GPGMeh.default_cmd = "gpg" # first gpg found in your $PATH
35
+ GPGMeh.default_args = ["--armor", "--trust-model", "always"]` # --no-tty` and `--quiet` are always added to the argument list
36
+ GPGMeh.timeout_sec = 0.2 # wait up to 200ms for gpg to finish
37
+ ```
38
+
39
+ ### Troubleshooting your Configuration
40
+
41
+ Make sure `GPGMeh.default_cmd` uses `gpg`, *not* `gpg2`. If you get any of the following errors, check your `gpg` version.
42
+
43
+ `gpg2` has a slightly different format for `--list-keys --with-colons`:
44
+
45
+ ```
46
+ lib/gpgmeh/key.rb:74:in `rescue in creation_date=': invalid date="1454695279" (GPGMeh::Key::ParseError)
47
+ ```
48
+
49
+ `gpg2` may have trouble starting the agent:
50
+
51
+ ```
52
+ command get_passphrase failed: Inappropriate ioctl for device
53
+ ```
54
+
55
+
56
+ ### Public Key Encryption: Rick wants to encrypt and sign something for Spiff
57
+
58
+ ```ruby
59
+ # 7CAAAB91 is Spaceman Spiff's public key id; multiple recipients can be specified
60
+ GPGMeh.encrypt("boom", ["7CAAAB91"]) do |key_id|
61
+ # This is the passphrase callback. The argument is Rick's secret key id.
62
+ # Return value: the secret keyring passphrase
63
+ "rick's-secret-keyring-passphrase"
64
+ end
65
+ ```
66
+
67
+ ### Public Key Decryption: Spiff wants to decrypt something from Rick
68
+
69
+ ```ruby
70
+ encrypted_message = <<EOM
71
+ -----BEGIN PGP MESSAGE-----
72
+ Version: GnuPG v1
73
+
74
+ hQEMA5IgSfURq0FaAQf/TxrcB0EeC5XpEwVyjaKoMNR7d2PZFBLQL9wX81jEIPIN
75
+ 0tsq7/OSj/bZF1p9gkQ9YN+wzvS+1pLlPo1T/GNGrt6ay+ml4mOjezACfrQ+EBB+
76
+ ay5XrDbwemAW/tqLMkJMrx28dt8fkNlXv+uzPKpQI5cubBcDyoD/E53rqyybjt+D
77
+ pqA9bZ3OORqWHPBZy50eaTs/tyVgBpfXsgcTfbwSedSNnLXxdB0p2pKgPjeAYlCm
78
+ DGzxIRSSZjHSBieDm6ZUv/tcplXqrzQxZT/0rhneoG5FK+0g5sayEPQKozdVdFM3
79
+ B4a2jzcDbhkNEZ2HV2VVmRp2HHaFRFftuPeoECQGjckoxTo5u9K6cnOymDbf2lN0
80
+ /0Jec1LUDWLYUtzNonBpPdlUIxlllT6Q0Q==
81
+ =ANji
82
+ -----END PGP MESSAGE-----
83
+ EOM
84
+ GPGMeh.decrypt(encrypted_message) do |key_id|
85
+ # This is the passphrase callback. The argument is Spiff's secret sub key id
86
+ # that Rick used to encypt the message.
87
+ # Return value: the secret keyring passphrase
88
+ "spiff's-secret-keyring-passphrase"
89
+ end
90
+ ```
91
+
92
+ ### Symmetric Encryption: Rick wants to symmetrically encrypt and sign a message
93
+
94
+ ```ruby
95
+ GPGMeh.encrypt_symmetric("boom") do |key_id|
96
+ # This is the passphrase callback. The argument is Rick's secret key id OR :symmetric
97
+ if key_id == :symmetric
98
+ "the-symmetric-passphrase"
99
+ else
100
+ "rick's-secret-keyring-passphrase"
101
+ end
102
+ end
103
+ ```
104
+
105
+ ### Override default configuration
106
+
107
+ ```ruby
108
+ # 7CAAAB91 is Spaceman Spiff's public key id; multiple recipients can be specified
109
+ GPGMeh.encrypt(
110
+ "boom",
111
+ ["7CAAAB91"],
112
+ gpg_options: {
113
+ cmd: "/usr/local/bin/gpg",
114
+ homedir: "/tmp/.gnupg",
115
+ timeout_sec: 10
116
+ }
117
+ ) do |key_id|
118
+ # This is the passphrase callback. The argument is Rick's secret key id.
119
+ # Return value: the secret keyring passphrase
120
+ "rick's-secret-keyring-passphrase"
121
+ end
122
+ ```
123
+
124
+ ## GPG documentation
125
+
126
+ The gpg 1.4
127
+ [docs](https://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob;f=doc/DETAILS;hb=refs/heads/STABLE-BRANCH-1-4)
128
+ describe the key types and status-fd output format.
129
+
130
+ ## GPG setup (this was done to setup the tests, here for posterity)
131
+
132
+ Generate key for Rick Hardslab
133
+
134
+ ```
135
+ gpg --homedir spec/support/rickhardslab --gen-key
136
+ ```
137
+
138
+ Generate key for Spaceman Spiff
139
+
140
+ ```
141
+ gpg --homedir spec/support/spacemanspiff --gen-key
142
+ ```
143
+
144
+ Rick Hardslab imports Spaceman Spiff's public key
145
+
146
+ ```
147
+ gpg --homedir spec/support/rickhardslab --import spacemanspiff/pubring.gpg
148
+ ```
149
+
150
+ Rick Hardslab trusts Spaceman Spiff's public key
151
+
152
+ ```
153
+ gpg --homedir spec/support/spacemanspiff --export-ownertrust | gpg --homedir spec/support/rickhardslab --import-ownertrust
154
+ ```
155
+
156
+ Spaceman Spiff imports Rick Hardslab's public key
157
+
158
+ ```
159
+ gpg --homedir spec/support/spacemanspiff --import rickhardslab/pubring.gpg
160
+ ```
161
+
162
+ Spaceman Spiff trusts Rick Hardslab's public key
163
+
164
+ ```
165
+ gpg --homedir spec/support/rickhardslab --export-ownertrust | gpg --homedir spec/support/spacemanspiff --import-ownertrust
166
+ ```
167
+
168
+ Edit Rick's Key so a "uid" record exists for the tests to ignore ;)
169
+
170
+ ```
171
+ gpg --homedir spec/support/rickhardslab/ --edit-key 7A9910E0243D6FEB
172
+ # Edit the fields and "save" to exit
173
+ ```
174
+
175
+ Rick Hardslab's keys
176
+
177
+ ```
178
+ % gpg --homedir spec/support/rickhardslab/ -k
179
+ rickhardslab/pubring.gpg
180
+ ------------------------
181
+ pub 2048R/243D6FEB 2016-01-18
182
+ uid Richard Hardslab (The Real Rick) <richard@example.com>
183
+ uid Rick Hardslab <rick@example.com>
184
+ sub 2048R/7FCAE6B3 2016-01-18
185
+
186
+ pub 2048R/7CAAAB91 2016-01-18
187
+ uid Spaceman Spiff <spiff@example.com>
188
+ sub 2048R/11AB415A 2016-01-18
189
+
190
+ % gpg --homedir spec/support/rickhardslab -K
191
+ rickhardslab/secring.gpg
192
+ ------------------------
193
+ sec 2048R/243D6FEB 2016-01-18
194
+ uid Rick Hardslab <rick@example.com>
195
+ uid Richard Hardslab (The Real Rick) <richard@example.com>
196
+ ssb 2048R/7FCAE6B3 2016-01-18
197
+ ```
198
+
199
+ Spaceman Spiff's keys
200
+
201
+ ```
202
+ % gpg --homedir spec/support/spacemanspiff -K
203
+ spacemanspiff/secring.gpg
204
+ -------------------------
205
+ sec 2048R/7CAAAB91 2016-01-18
206
+ uid Spaceman Spiff <spiff@example.com>
207
+ ssb 2048R/11AB415A 2016-01-18
208
+
209
+ % gpg --homedir spec/support/spacemanspiff -k
210
+ spacemanspiff/pubring.gpg
211
+ -------------------------
212
+ pub 2048R/7CAAAB91 2016-01-18
213
+ uid Spaceman Spiff <spiff@example.com>
214
+ sub 2048R/11AB415A 2016-01-18
215
+ ```
216
+
217
+ ## Development
218
+
219
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run
220
+ `bundle exec rake` to run the tests. You can also run `bin/console` for an
221
+ interactive prompt that will allow you to experiment. If lots of tests fail,
222
+ check you are using the correct version of gpg. You can specify the `gpg`
223
+ binary with: `GPG=gpg1 bundle exec rake`.
224
+
225
+ To install this gem onto your local machine, run `bundle exec rake install`. To
226
+ release a new version, update the version number in `version.rb`, and then run
227
+ `bundle exec rake release`, which will create a git tag for the version, push
228
+ git commits and tags, and push the `.gem` file to
229
+ [rubygems.org](https://rubygems.org).
230
+
231
+ ## Contributing
232
+
233
+ We always welcome bug reports, on [GitHub's issue tracker](https://github.com/square/gpgmeh/issues).
234
+
235
+ If you would like to contribute code to GPGMeh, thank you! You can do so
236
+ through [GitHub](https://github.com/square/gpgmeh) by forking the repository and sending a [pull request](https://github.com/square/gpgmeh/pulls). However,
237
+ before your code can be accepted into the project we need you to sign Square's
238
+ (super simple) [Individual Contributor License Agreement
239
+ (CLA)](https://spreadsheets.google.com/spreadsheet/viewform?formkey=dDViT2xzUHAwRkI3X3k5Z0lQM091OGc6MQ&ndplr=1)
240
+
241
+ ## License
242
+
243
+ Copyright 2016 Square, Inc.
244
+
245
+ Licensed under the Apache License, Version 2.0 (the "License");
246
+ you may not use this file except in compliance with the License.
247
+ You may obtain a copy of the License at
248
+
249
+ http://www.apache.org/licenses/LICENSE-2.0
250
+
251
+ Unless required by applicable law or agreed to in writing, software
252
+ distributed under the License is distributed on an "AS IS" BASIS,
253
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
254
+ See the License for the specific language governing permissions and
255
+ limitations under the License.
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+ require "rubocop/rake_task"
6
+
7
+ RSpec::Core::RakeTask.new(:spec)
8
+ RuboCop::RakeTask.new
9
+
10
+ task default: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "gpgmeh"
5
+
6
+ require "pry"
7
+ Pry.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/gpgmeh.gemspec ADDED
@@ -0,0 +1,24 @@
1
+ # coding: utf-8
2
+ # frozen_string_literal: true
3
+
4
+ lib = File.expand_path("../lib", __FILE__)
5
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
6
+ require "gpgmeh/version"
7
+
8
+ Gem::Specification.new do |spec|
9
+ spec.name = "gpgmeh"
10
+ spec.version = GPGMeh::VERSION
11
+ spec.authors = ["Andrew Lazarus"]
12
+ spec.email = ["lazarus@squareup.com"]
13
+
14
+ spec.summary = "GPG Made Even (Happier|Hipper|Harder?)"
15
+ spec.homepage = "https://github.com/square/gpgmeh"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
18
+ spec.bindir = "exe"
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ["lib"]
21
+
22
+ spec.add_dependency "activesupport", ">= 2.3"
23
+ spec.add_dependency "nio4r", "~> 2"
24
+ end
data/lib/gpgmeh/key.rb ADDED
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require "set"
5
+
6
+ class GPGMeh
7
+ class Key
8
+ class ParseError < ::GPGMeh::Error; end
9
+
10
+ # See README.md for link to gpg documentation on key types
11
+ TYPES = {
12
+ "pub" => "public key",
13
+ "crt" => "X.509 certificate",
14
+ "crs" => "X.509 certificate and private key available",
15
+ "sub" => "subkey",
16
+ "sec" => "secret key",
17
+ "ssb" => "secret subkey",
18
+ "uid" => "user id",
19
+ "uat" => "user attribute",
20
+ "sig" => "signature",
21
+ "rev" => "revocation signature",
22
+ "fpr" => "fingerprint",
23
+ "pkd" => "public key data",
24
+ "grp" => "reserved for gpgsm",
25
+ "rvk" => "revocation key",
26
+ "tru" => "trust database information",
27
+ "spk" => "signature subpacket"
28
+ }.freeze
29
+
30
+ TYPES_THAT_MATTER = TYPES.values_at('pub', 'sub', 'sec', 'ssb', 'rvk').to_set.freeze
31
+
32
+ TRUSTS = {
33
+ "o" => "other",
34
+ "i" => "invalid",
35
+ "d" => "disabled",
36
+ "r" => "revoked",
37
+ "e" => "expired",
38
+ "n" => "none",
39
+ "m" => "marginal",
40
+ "f" => "fully",
41
+ "u" => "ultimately",
42
+ "-" => "unknown",
43
+ "q" => "unknown"
44
+ }.freeze
45
+
46
+ CAPABILITIES = {
47
+ "e" => "encrypt",
48
+ "s" => "sign",
49
+ "c" => "certify",
50
+ "a" => "authentication",
51
+ "d" => "disabled"
52
+ }.freeze
53
+
54
+ def self.parse(raw_keys)
55
+ raw_keys.split("\n").map do |raw_key|
56
+ fields = raw_key.split(":", 13)
57
+ key = new
58
+ key.type = fields[0]
59
+ next unless TYPES_THAT_MATTER.include?(key.type)
60
+ key.trust = fields[1]
61
+ key.key_length = fields[2].to_i
62
+ key.key_id = fields[4]
63
+ key.creation_date = fields[5]
64
+ key.name = fields[9]
65
+ key.capabilities = fields[11]
66
+ key
67
+ end.compact
68
+ end
69
+
70
+ attr_accessor :key_length, :key_id, :name
71
+ attr_reader :type, :trust, :capabilities, :creation_date
72
+
73
+ def creation_date=(s)
74
+ @creation_date = Date.parse(s)
75
+ rescue ArgumentError => e
76
+ msg = "#{e.message}=#{s.inspect}"
77
+ msg += ", gpg2 uses a different date format, are you using gpg2 instead of gpg1?" if s.to_i.to_s == s
78
+ raise ParseError, msg
79
+ end
80
+
81
+ def type=(s)
82
+ @type = TYPES[s] || raise(ParseError, "unkown key type=#{s.inspect}")
83
+ end
84
+
85
+ def trust=(s)
86
+ @trust = TRUSTS[s] || raise(ParseError, "unkown trust=#{s.inspect}") unless s.empty?
87
+ end
88
+
89
+ def capabilities=(s)
90
+ @capabilities = s.split("").map do |letter|
91
+ CAPABILITIES[letter.downcase] ||
92
+ raise(ParseError, "unkown capability=#{letter.inspect} capabilities=#{s.inspect}")
93
+ end.to_set
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ class GPGMeh
4
+ VERSION = "0.1.5"
5
+ end
data/lib/gpgmeh.rb ADDED
@@ -0,0 +1,366 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/core_ext/object/blank"
4
+ require "active_support/core_ext/object/try"
5
+ require "nio"
6
+ require "open3"
7
+
8
+ class GPGMeh
9
+ class Error < StandardError; end
10
+ class TimeoutError < Error; end
11
+ class NoPassphraseError < Error; end
12
+ end
13
+
14
+ require "gpgmeh/key"
15
+ require "gpgmeh/version"
16
+
17
+ class GPGMeh
18
+ # Encrypt message using public key encryption for the `recipients`
19
+ #
20
+ # @param plaintext [String] bytes to be encrypted with the recipient(s)'
21
+ # public key; each recipient's secret key must be used to decrypt the message
22
+ # @param recipients [String] or [Array<String>] list of public key id's
23
+ # @param gpg_options [Hash<Symbol, String>] gpg options, valid keys: cmd, args, homedir, timeout_sec
24
+ # cmd: gpg command to execute, default=gpg
25
+ # args: command line arguments for gpg, default=%w(--armor --trust-model always)
26
+ # (note: --no-tty and --quiet are always added)
27
+ # homedir: custom homedir for gpg (passes --homedir argument to gpg)
28
+ # timeout_sec: timeout for gpg command, default=0.2
29
+ # @param sign [bool] should the encrypted message be signed? Requires `passphrase_callback`. [default=true]
30
+ # @param passphrase_callback [callable] or [block] callable that returns the secret keyring passphrase,
31
+ # only required when signing; the callable takes an 8 character string argument (short format key id)
32
+ #
33
+ # @return [String] encrypted message
34
+ #
35
+ # Example:
36
+ #
37
+ # GPGMeh.encrypt("boom", "ABC123DE") do |secret_key_id|
38
+ # if secret_key_id == "123ABC45"
39
+ # "secret_keyring1_passphrase"
40
+ # else
41
+ # "secret_keyring2_passphrase"
42
+ # end
43
+ # end
44
+ #
45
+ def self.encrypt(plaintext, recipients, gpg_options: {}, sign: true, passphrase_callback: nil, &block)
46
+ raise ArgumentError, "passphrase callback required to sign" if sign && (passphrase_callback || block).nil?
47
+ raise ArgumentError, "recipient(s) required" if recipients.empty?
48
+ unless recipients.all? { |key_id| /^[A-Za-z0-9]+$/ =~ key_id }
49
+ raise ArgumentError, "recipient key ids must all be alphanumeric strings"
50
+ end
51
+ t = Time.now
52
+ new(gpg_options).encrypt(plaintext, recipients, sign: sign, passphrase_callback: passphrase_callback || block)
53
+ ensure
54
+ logger.debug(format("GPGMeh: encryption time=%.3fs", Time.now - t)) if t
55
+ end
56
+
57
+ # Decrypt public key encrypted message using secret keyring
58
+ #
59
+ # @param encrypted_blob [String] encrypted blob to decrypt
60
+ # @param gpg_options (@see #GPGMeh.encrypt)
61
+ # @param passphrase_callback (@see #GPGMeh.encrypt)
62
+ #
63
+ # @return [String] encrypted message
64
+ def self.decrypt(encrypted_blob, gpg_options: {}, passphrase_callback: nil, &block)
65
+ raise ArgumentError, "passphrase callback required" if (passphrase_callback || block).nil?
66
+ t = Time.now
67
+ new(gpg_options).decrypt(encrypted_blob, passphrase_callback || block)
68
+ ensure
69
+ logger.debug(format("GPGMeh: decryption time=%.3fs", Time.now - t)) if t
70
+ end
71
+
72
+ # Encrypt message using a symmetric passphrase
73
+ #
74
+ # @param plaintext (@see #GPGMeh.encrypt)
75
+ # @param gpg_options (@see #GPGMeh.encrypt)
76
+ # @param sign (@see #GPGMeh.encrypt)
77
+ # @param passphrase_callback [callable] or [block] callable that returns passphrases:
78
+ # `callable.call(:symmetric)` # => the symmetric passphrase (required)
79
+ # `callable.call(<short format secret key id>)` # => the secret keyring passphrase
80
+ # (optional, only used when signing)
81
+ #
82
+ # Example:
83
+ #
84
+ # GPGMeh.encrypt_symmetric("boom") do |secret_key_id|
85
+ # if secret_key_id == :symmetric
86
+ # "my-symmetric-secret"
87
+ # elsif secret_key_id == "123ABC45"
88
+ # "secret_keyring1_passphrase"
89
+ # else
90
+ # "secret_keyring2_passphrase"
91
+ # end
92
+ # end
93
+ #
94
+ # @return [String] encrypted message
95
+ def self.encrypt_symmetric(
96
+ plaintext,
97
+ gpg_options: {},
98
+ sign: true,
99
+ passphrase_callback: nil,
100
+ &block
101
+ )
102
+ t = Time.now
103
+ new(gpg_options).encrypt_symmetric(
104
+ plaintext,
105
+ sign: sign,
106
+ passphrase_callback: passphrase_callback || block
107
+ )
108
+ ensure
109
+ logger.debug(format("GPGMeh: symmetric encryption time=%.3fs", Time.now - t)) if t
110
+ end
111
+
112
+ def self.public_keys(gpg_options: {})
113
+ new(gpg_options).public_keys
114
+ end
115
+
116
+ def self.secret_keys(gpg_options: {})
117
+ new(gpg_options).secret_keys
118
+ end
119
+
120
+ def self.version(gpg_options: {})
121
+ new(gpg_options).version
122
+ end
123
+
124
+ class << self
125
+ attr_accessor :default_cmd, :default_args, :default_homedir, :timeout_sec
126
+ attr_writer :logger
127
+ end
128
+ self.default_cmd = "gpg"
129
+ self.default_args = %w[--armor --trust-model always].freeze
130
+ self.timeout_sec = 0.2
131
+
132
+ def self.logger
133
+ return @logger if defined?(@logger)
134
+ require "logger"
135
+ @logger = Logger.new(STDERR)
136
+ end
137
+
138
+ def initialize(
139
+ cmd: self.class.default_cmd,
140
+ args: self.class.default_args,
141
+ homedir: self.class.default_homedir,
142
+ timeout_sec: self.class.timeout_sec
143
+ )
144
+ @gpg_cmd = cmd
145
+ @gpg_args = args
146
+ @gpg_args += ["--homedir", homedir] if homedir
147
+ @deadline = Time.now + timeout_sec
148
+ @stdout_buffer = +""
149
+ @stderr_buffer = +""
150
+ @status_r_buffer = +""
151
+ end
152
+ private_class_method :new
153
+
154
+ private
155
+
156
+ attr_reader :gpg_cmd,
157
+ :gpg_args,
158
+ :status_r,
159
+ :command_w,
160
+ :stdin,
161
+ :stdout,
162
+ :stderr,
163
+ :stdout_buffer,
164
+ :stderr_buffer,
165
+ :status_r_buffer,
166
+ :stdin_monitor,
167
+ :stdout_monitor,
168
+ :stderr_monitor,
169
+ :status_r_monitor,
170
+ :input,
171
+ :callback,
172
+ :wait_thread
173
+
174
+ def start(extra_args, input = nil, callback = nil)
175
+ setup_gpg_process(extra_args, input, callback)
176
+
177
+ runloop
178
+
179
+ unless stderr_buffer.empty?
180
+ self.class.logger.warn { "GPGMeh: gpg stderr=#{stderr_buffer.inspect}" }
181
+ end
182
+
183
+ # wait on thread completion until the deadline
184
+ wait = @deadline - Time.now
185
+ raise TimeoutError if wait <= 0 || wait_thread.join(wait).nil?
186
+
187
+ raise Error, "gpg non-zero exit status=#{wait_thread.value}" unless wait_thread.value.try(:success?)
188
+
189
+ stdout_buffer
190
+ rescue => e
191
+ self.class.logger.error do
192
+ "GPGMeh: error=#{e.inspect} backtrace=#{e.backtrace[0..20].inspect} stderr=#{stderr_buffer.inspect}"
193
+ end
194
+ raise
195
+ ensure
196
+ begin
197
+ Process.kill(:SIGINT, wait_thread.pid) if wait_thread.alive?
198
+ rescue Errno::ESRCH # rubocop:disable Lint/HandleExceptions
199
+ end
200
+ end
201
+
202
+ def setup_gpg_process(extra_args, input, callback)
203
+ @input = input
204
+ @callback = callback
205
+ if callback
206
+ @status_r, status_w = IO.pipe
207
+ status_w.close_on_exec = false
208
+ command_r, @command_w = IO.pipe
209
+ command_r.close_on_exec = false
210
+ command_w.sync = true
211
+ extra_args.concat(["--status-fd", status_w.to_i.to_s, "--command-fd", command_r.to_i.to_s])
212
+ end
213
+
214
+ @stdin, @stdout, @stderr, @wait_thread =
215
+ Open3.popen3(gpg_cmd, "--no-tty", "--quiet", *gpg_args, *extra_args, close_others: !callback)
216
+ stdout.set_encoding(Encoding::BINARY)
217
+
218
+ return unless callback
219
+
220
+ command_r.close
221
+ status_w.close
222
+ end
223
+
224
+ def runloop
225
+ selector = NIO::Selector.new
226
+
227
+ if input
228
+ @stdin_monitor = selector.register(stdin, :w)
229
+ @stdin_monitor.value = method(:write_stdin)
230
+ end
231
+ @stdout_monitor = selector.register(stdout, :r)
232
+ @stdout_monitor.value = method(:read_stdout)
233
+ @stderr_monitor = selector.register(stderr, :r)
234
+ @stderr_monitor.value = method(:read_stderr)
235
+ if callback
236
+ @status_r_monitor = selector.register(status_r, :r)
237
+ @status_r_monitor.value = method(:read_status_r)
238
+ end
239
+
240
+ loop do
241
+ break if selector.empty?
242
+
243
+ wait = @deadline - Time.now
244
+ raise TimeoutError if wait <= 0
245
+
246
+ ready = selector.select(wait)
247
+ next unless ready # ready is nil for timeouts
248
+ ready.each do |monitor|
249
+ monitor.value.call
250
+ end
251
+ end
252
+ ensure
253
+ # rubocop:disable Style/RescueModifier
254
+ stdin.close rescue nil
255
+ stdout.close rescue nil
256
+ stderr.close rescue nil
257
+ status_r.close rescue nil
258
+ command_w.close rescue nil
259
+ selector.close
260
+ # rubocop:enable Style/RescueModifier
261
+ end
262
+
263
+ def write_stdin
264
+ loop do
265
+ bytes_written = stdin.write_nonblock(input, exception: false)
266
+ break if bytes_written == :wait_writable
267
+
268
+ @input = input.byteslice(bytes_written..-1)
269
+
270
+ if input.empty? # rubocop:disable Style/Next
271
+ stdin_monitor.close
272
+ stdin.close_write
273
+ break
274
+ end
275
+ end
276
+ end
277
+
278
+ def read_stdout
279
+ read(stdout, stdout_buffer, stdout_monitor)
280
+ end
281
+
282
+ def read_stderr
283
+ read(stderr, stderr_buffer, stderr_monitor)
284
+ end
285
+
286
+ def read_status_r
287
+ read(status_r, status_r_buffer, status_r_monitor)
288
+
289
+ last = status_r_buffer.rindex("\n")
290
+ return unless last
291
+
292
+ status_r_buffer[0..last].split("\n").each do |line|
293
+ # See README.md for link to gpg documentation on status-fd output
294
+ self.class.logger.debug { "GPGMeh: gpg status-fd output=#{line.inspect}" }
295
+
296
+ if /NEED_PASSPHRASE (?<sub_key_id>\S+) (?<key_id>\S+)/ =~ line
297
+ self.class.logger.debug do
298
+ "GPGMeh: NEED_PASSPHRASE sub_key_id=#{sub_key_id.inspect} key_id=#{key_id.inspect}"
299
+ end
300
+ passphrase = callback.call(sub_key_id[-8..-1])
301
+ raise NoPassphraseError, "secret keyring passphrase required from callback" unless passphrase
302
+ command_w.puts(passphrase)
303
+ elsif /NEED_PASSPHRASE_SYM/.match?(line)
304
+ self.class.logger.debug("GPGMeh: NEED_PASSPHRASE_SYM")
305
+ passphrase = callback.call(:symmetric)
306
+ raise NoPassphraseError, "symmetric passphrase required from callback" unless passphrase
307
+ command_w.puts(passphrase)
308
+ end
309
+ end
310
+ @status_r_buffer = status_r_buffer[(last + 1)..-1]
311
+ end
312
+
313
+ def read(io, buffer, monitor)
314
+ loop do
315
+ output_chunk = io.read_nonblock(8192, exception: false)
316
+ # output_chunk == nil means readable EOF
317
+ return if output_chunk == :wait_readable
318
+
319
+ if output_chunk.nil?
320
+ monitor.close
321
+ io.close
322
+ return
323
+ end
324
+
325
+ buffer << output_chunk
326
+ end
327
+ end
328
+
329
+ # These methods are "public", but since `new` is private, they should be inaccessible
330
+ public
331
+
332
+ # @private
333
+ def encrypt(plaintext, recipients, sign:, passphrase_callback:)
334
+ extra_args = %w[--encrypt] + recipients.flat_map { |recipient| ["--recipient", recipient] }
335
+ extra_args << "--sign" if sign
336
+ start(extra_args, plaintext, passphrase_callback)
337
+ end
338
+
339
+ # @private
340
+ def decrypt(encrypted_blob, passphrase_callback)
341
+ start(["--decrypt"], encrypted_blob, passphrase_callback)
342
+ end
343
+
344
+ # @private
345
+ def encrypt_symmetric(plaintext, sign:, passphrase_callback:)
346
+ extra_args = ["--symmetric"]
347
+ extra_args << "--sign" if sign
348
+
349
+ start(extra_args, plaintext, passphrase_callback)
350
+ end
351
+
352
+ # @private
353
+ def public_keys
354
+ Key.parse(start(%w[--with-colons --list-public-keys]))
355
+ end
356
+
357
+ # @private
358
+ def secret_keys
359
+ Key.parse(start(%w[--with-colons --list-secret-keys]))
360
+ end
361
+
362
+ # @private
363
+ def version
364
+ start(%w[--version])
365
+ end
366
+ end
metadata ADDED
@@ -0,0 +1,87 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: gpgmeh
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.5
5
+ platform: ruby
6
+ authors:
7
+ - Andrew Lazarus
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-11-21 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '2.3'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '2.3'
27
+ - !ruby/object:Gem::Dependency
28
+ name: nio4r
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '2'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '2'
41
+ description:
42
+ email:
43
+ - lazarus@squareup.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".gitignore"
49
+ - ".rspec"
50
+ - ".rubocop.yml"
51
+ - ".travis.yml"
52
+ - BUG-BOUNTY.md
53
+ - CHANGELOG.md
54
+ - Gemfile
55
+ - LICENSE.txt
56
+ - README.md
57
+ - Rakefile
58
+ - bin/console
59
+ - bin/setup
60
+ - gpgmeh.gemspec
61
+ - lib/gpgmeh.rb
62
+ - lib/gpgmeh/key.rb
63
+ - lib/gpgmeh/version.rb
64
+ homepage: https://github.com/square/gpgmeh
65
+ licenses: []
66
+ metadata: {}
67
+ post_install_message:
68
+ rdoc_options: []
69
+ require_paths:
70
+ - lib
71
+ required_ruby_version: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ required_rubygems_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: '0'
81
+ requirements: []
82
+ rubyforge_project:
83
+ rubygems_version: 2.6.13
84
+ signing_key:
85
+ specification_version: 4
86
+ summary: GPG Made Even (Happier|Hipper|Harder?)
87
+ test_files: []