sym 2.8.5 → 2.10.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/.circleci/config.yml +19 -12
  3. data/.envrc +7 -0
  4. data/.gitignore +1 -0
  5. data/.rubocop.yml +150 -928
  6. data/.travis.yml +16 -28
  7. data/CHANGELOG.md +201 -174
  8. data/Gemfile +1 -0
  9. data/README.adoc +650 -0
  10. data/Rakefile +6 -2
  11. data/codecov.yml +29 -0
  12. data/exe/keychain +1 -1
  13. data/exe/sym +5 -2
  14. data/lib/ruby_warnings.rb +7 -0
  15. data/lib/sym.rb +1 -7
  16. data/lib/sym/app.rb +1 -1
  17. data/lib/sym/app/args.rb +3 -2
  18. data/lib/sym/app/cli.rb +1 -2
  19. data/lib/sym/app/cli_slop.rb +1 -1
  20. data/lib/sym/app/commands.rb +1 -1
  21. data/lib/sym/app/commands/base_command.rb +1 -1
  22. data/lib/sym/app/commands/bash_completion.rb +2 -2
  23. data/lib/sym/app/commands/open_editor.rb +1 -1
  24. data/lib/sym/app/commands/password_protect_key.rb +4 -4
  25. data/lib/sym/app/commands/show_examples.rb +1 -1
  26. data/lib/sym/app/keychain.rb +15 -9
  27. data/lib/sym/app/output/noop.rb +2 -1
  28. data/lib/sym/app/password/cache.rb +1 -1
  29. data/lib/sym/app/password/providers.rb +2 -3
  30. data/lib/sym/app/private_key/decryptor.rb +2 -2
  31. data/lib/sym/app/private_key/detector.rb +4 -7
  32. data/lib/sym/application.rb +5 -10
  33. data/lib/sym/constants.rb +4 -4
  34. data/lib/sym/data/wrapper_struct.rb +20 -12
  35. data/lib/sym/errors.rb +11 -2
  36. data/lib/sym/extensions/instance_methods.rb +7 -8
  37. data/lib/sym/extensions/stdlib.rb +0 -1
  38. data/lib/sym/extensions/with_retry.rb +1 -1
  39. data/lib/sym/extensions/with_timeout.rb +1 -1
  40. data/lib/sym/version.rb +30 -5
  41. data/sym.gemspec +35 -35
  42. metadata +86 -68
  43. data/README.md +0 -620
  44. data/lib/sym/app/password/providers/drb_provider.rb +0 -41
data/Gemfile CHANGED
@@ -9,3 +9,4 @@ if RUBY_PLATFORM == 'x86_64-darwin16'
9
9
  gem 'coin', git: 'https://github.com/kigster/coin'
10
10
  end
11
11
 
12
+
@@ -0,0 +1,650 @@
1
+ = *sym* — _Symmetric Encryption for Humans_
2
+ :toc:
3
+ :sectnum:
4
+ :toclevel: 4
5
+
6
+ ====
7
+ image:https://badge.fury.io/rb/sym.svg[Gem Version,link=https://badge.fury.io/rb/sym]
8
+ image:https://travis-ci.org/kigster/sym.svg?branch=master[Build Status,link=https://travis-ci.org/kigster/sym]
9
+ image:https://circleci.com/gh/kigster/sym.svg?style=shield[CircleCI,link=https://circleci.com/gh/kigster/sym?style=shield]
10
+ image:https://api.codeclimate.com/v1/badges/4f1d1614ccaa61c974dd/maintainability[Maintainability,link=https://codeclimate.com/github/kigster/sym/maintainability]
11
+
12
+ image:https://codecov.io/gh/kigster/sym/branch/master/graph/badge.svg?style=shield[Coverage,link="https://codecov.io/gh/kigster/sym"]
13
+ image:https://img.shields.io/gitter/room/gitterHQ/gitter.svg[Gitter,link=https://gitter.im/kigster/sym]
14
+ image:https://ruby-gem-downloads-badge.herokuapp.com/sym?extension=svg[Sym Downloads,link=https://rubygems.org/gems/sym]
15
+
16
+ image:https://codecov.io/gh/kigster/sym/branch/master/graphs/sunburst.svg[Coverage Map,link=https://codecov.io/gh/kigster/sym]
17
+ ====
18
+
19
+ Please checkout the following post — _http://kig.re/2017/03/10/dead-simple-encryption-with-sym.html[Dead Simple Encryption with Sym]_ — that announced the initial release of this library, and provides further in-depth discussion. Your donation of absolutely any amount is very much appreciated but never required.
20
+
21
+ image::https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif[Donate,link=https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=FSFYYNEQ8RKWU]
22
+
23
+ == Introduction
24
+
25
+ ====
26
+ *sym* is an open source command line utility and Ruby API which makes it very _easy to add reliable encryption and decryption_ of sensitive data to an application or a project written in any language.
27
+ ====
28
+
29
+ * Unlike many existing encryption tools, *sym* focuses on narrowing the gap between convenience and security, by offering enhanced usability and a streamlined ruby API and a CLI. The primary goal of the library is to make encryption very easy and transparent. +
30
+
31
+ * *sym* uses the _https://en.wikipedia.org/wiki/Symmetric-key_algorithm[Symmetric Encryption]_ algorithm. This means that the same key is used to encrypt and decrypt data. In addition to the key, the encryption uses a randomized IV vector, which is automatically generated per each encryption and serialized with the data. Result of encryption is zlib-compressed, and base64 encoded, to be suitable for storage as string. The generated keys are also base64-encoded for convenience. +
32
+
33
+ * Finally, the library offers encryption using any regular password, and in particular supports password-protected encryption keys. Automatic key detection algorithm attempts to resolve a provided key as a filename, an environment variable name, an OS-X Keychain password entry name, a key itself, or a default key file. +
34
+
35
+ NOTE: Sym uses Ruby's `Marshall.dump` to serialize it's data, and therefore it is not currently possible or easy to deserialize the data in languages other than Ruby.
36
+
37
+ === Quick Demo of the CLI in Action
38
+
39
+ image::design/ascii-cinema.png[asciicast,link=https://asciinema.org/a/106737]
40
+
41
+ ==== Help Screens, Examples and Symit Bash Wrapper
42
+
43
+ This may be a good time to take a look at the full help message for the `sym` tool, shown naturally with a `-h` or `--help` option. Examples can be shown with `-E/--examples` flag.
44
+
45
+ Additionally, Sym comes with a helpful BASH wrapper `symit`.
46
+
47
+ *Help screens for `sym` and `symit` are shown in full on another page -- xref:SYM-CLI.adoc[Sym Help Screens and Symit]. Please refer to it for complete help screens and the examples.*
48
+
49
+ == Supported Ruby Versions
50
+
51
+ Sym currently builds and runs on the following ruby versions on Travis CI:
52
+
53
+ .Ruby Version Compatibility
54
+ [cols="<,<", width="80%"]
55
+ |===
56
+ | MRI Ruby |JRuby
57
+
58
+ | 2.3.8 | jruby-9.1.17.0
59
+ | 2.4.10| jruby-9.2.13.0
60
+ | 2.5.8 |
61
+ | 2.6.6 |
62
+ | 2.7.1 |
63
+
64
+ |===
65
+
66
+
67
+ === Motivation
68
+
69
+ The main goal when writing this tool was to streamline and simplify handling of sensitive data in a trasparent and easy to use way without sacrificing security.
70
+
71
+ Most common use-cases include:
72
+
73
+ * *Encrypting/decrypting of application secrets files*, so that the encrypted secrets can be safely checked into the git repository and distributed, and yet without much of the added headache that this often requires
74
+
75
+ * *Secure message transfer between any number of receipients*
76
+
77
+ * *General purpose encryption/decryption with a 256-bit encryption key*, optionally itself re-encrypted with a password.
78
+
79
+ * *General purpose encryption/decryption with an arbitrary password*.
80
+
81
+ *Sym* is a layer built on top of the https://www.openssl.org/[`OpenSSL`] library, and, hopefully, makes encryption more accessible to every-day developers, QA, and dev-ops folks, engaged in deploying applications.
82
+
83
+ === What's Included
84
+
85
+ This gem includes two primary components:
86
+
87
+ . *<<cli,Rich command line interface CLI>>* with many features to streamline encryption/decryption, and to be integrated into the deployment flow. +
88
+ +
89
+ . Ruby APIs:
90
+ ** *<<rubyapi,Key Generation, Encryption & Decryption API>>*
91
+ *** is activated by including `Sym` module in a class, it adds easy to use `encr`/`decr` methods.
92
+ ** *<<rubyapi-app,Application API to shadow the CLI usage>>*
93
+ *** You can instantiate `Sym::Application` class with a hash representing CLI arguments, and then call it's `#execute` method to mimic CLI execution.
94
+ ** *<<magic-file,Sym::MagicFile API>>*
95
+ *** This is a convenience class allowing you to encrypt/decrypt files in your ruby code with just couple of lines of code.
96
+ ** *<<rubyapi-config,Sym::Configuration>>*
97
+ *** Use this class to override the default cipher, and configure other parameters such as compression, password caching, and more.
98
+
99
+ === Massive Time Savers
100
+
101
+ *Sym* tries very hard to get out of your way, to make it _feel_ as if your encrypted files are as easy to work with as the unencrypted files. It accomplishes this transparency with the following features:
102
+
103
+ * By using *Mac OS-X Keychain*, `sym` offers a simple yet secure way of storing the key on a local machine, much more secure then storing it on a file system.
104
+ * By using a *password cache* (`-c`) via an in-memory provider such as `memcached`, `sym` invocations take advantage of password cache, and only ask for a password once per a configurable time period.
105
+ * By using *`SYM_ARGS` environment variable* you can save common flags and they will be applied whenever `-A` flag is activated.
106
+ * By reading a key from the default key source file `~/.sym.key` which requires no flags at all.
107
+ * By utilizing the *`--negate` option to quickly encrypt a regular file*, or decrypt an encrypted file with extension `.enc`.
108
+ * By using the *`-t file` (edit) mode*, that opens an encrypted file in your `$EDITOR`, and replaces the encrypted version upon save & exit.
109
+
110
+ As you can see, we really tried to build a tool that provides good security for application secrets, including password-based encryption, but does not annoyingly ask for password every time. With `--edit` option, and `--negate` options you can treat encrypted files like regular files.
111
+
112
+ [quote, Socrates (LOL)]
113
+ Encrypting application secrets had never been easier!
114
+ ---
115
+
116
+ == Using Sym
117
+
118
+ [discrete]
119
+ ==== Installation
120
+
121
+ If you plan on using the library in your Ruby project with Bundler managing its dependencies, just include the following line in your `Gemfile`:
122
+
123
+ gem 'sym'
124
+
125
+ And then run `bundle`.
126
+
127
+ Or install it into the global namespace with `gem install` command:
128
+
129
+ [source,bash]
130
+ ----
131
+ $ gem install sym
132
+ $ sym -h
133
+ $ sym -E # see examples
134
+ ----
135
+
136
+ *BASH Completion*
137
+
138
+ Optionally, after gem installation, you can also install bash-completion of gem's command line options, but running the following command (and feel free to use any of the "dot" files you prefer):
139
+
140
+ sym -B ~/.bashrc
141
+
142
+ Should you choose to install it (this part is optional), you will be able to use "tab-tab" after typing `sym`, and you'll be able to choose from all of the supported flags.
143
+
144
+ [discrete]
145
+ ==== Typical Use-Case Scenario
146
+
147
+ . You generate a new encryption key, that will be used to both encrypt and decrypt the data. The key is 256 bits, or 32 bytes, or 45 bytes when base64-encoded, and can be generated with `sym -g`. The key must be saved somewhere for later retrieval. The key should not be easily accessible to an attacker. Note, that while generating the key, you can:
148
+ ** optionally password protect the key with `sym -gp`
149
+ ** save the key into a file with `sym -gpo key-file`
150
+ ** save it into the OS-X Keychain, with `sym -gpx keychain-name`
151
+ ** cache the password, with `sym -gpcx keychain-name`
152
+ ** Normally, `sym` will print the resulting key to STDOUT
153
+ ** You can prevent the key from being printed to STDOUT with `-q/--quiet`.
154
+ . Next, let's assume you have a file or a string that you want to encrypt. We call this _data_.
155
+ . In order to encrypt the *data*, we must supply an encryption key. Flag `-k` automatically retrieves the key, by trying to read it in several distinct ways, such as:
156
+ ** a file with a pathname specified by the argument (eg, `-k ~/.key`)
157
+ ** or environment variable (eg `-k ENC_KEY`)
158
+ ** or OS-X Keychain entry
159
+ ** verbatum string argument (not recommended)
160
+ ** alternatively, you can paste the key interactively with `-i` or save the default key in `~/.sym.key` file.
161
+ . Finally, we are ready to encrypt. The data to be encrypted can be read from a file with `-f filename`, or it can be read from STDIN, or a passed on the command line with `-s string`. For example, `sym -e -k ~/.key -f /etc/passwd` will encrypt the file and print the encrypted contents to STDOUT.
162
+ . Instead of printing to STDOUT, the output can be saved to a file with `-o <file>` or a simple redirect or a pipe.
163
+ . Encrypted file can later be decrypted with `+sym -d ...+` assuming the same key it was encrypted with.
164
+ . Encrypted file with extension `.enc` can be automatically decrypted with `-n/--negate file` option; if the file does not end with `.enc`, it is encrypted and `.enc` extension added to the resulting file.
165
+ . With `-t/--edit file` flag you can edit an encrypted file in VIM (or `$EDITOR`) any encrypted file and edit it. Once you save it, the file gets re-encrypted and replaces the previous version. A backup can be created with `-b` option. See the section on <<inline,inline editing>>
166
+
167
+ A sample session that uses Mac OS-X Keychain to store the password-protected key.
168
+
169
+ [source,bash]
170
+ ----
171
+ # Gen a new key, password-encrypt it, cache the password, save
172
+ # result in the key chain entry 'my-new-key' (but don't print it '-q')
173
+ ❯ sym -gpqcx my-new-key
174
+ New Password : •••••••••
175
+ Confirm Password : •••••••••
176
+
177
+ ❯ sym -eck my-new-key -s 'My secret data' -o secret.enc
178
+ Password: •••••••••
179
+
180
+ ❯ cat secret.enc
181
+ BAhTOh1TeW06OkRhdGE6OldyYXBFefDFFD.....
182
+
183
+ ❯ sym -dck my-new-key -f secret.enc
184
+ My secret data
185
+
186
+ # Now, let's save our keychain key in the default key file:
187
+ ❯ sym -ck my-new-key -o ~/.sym.key
188
+
189
+ # Now we can decrypt/encrypt with this key at will
190
+ ❯ sym -n secret.enc
191
+ # created a decrypted file `secret`
192
+
193
+ # Lets now save common flags in the SYM_ARGS bash variable:
194
+ ❯ export SYM_ARGS="-ck my-new-key"
195
+ ❯ sym -df secret.enc
196
+ My secret data
197
+ ----
198
+
199
+ Note that password caching is off by default, but is enabled with `-c` flag. In the example above, the decryption step fetched the password from the cache, and so the user was not required to re-enter the password.
200
+
201
+ +++<a name="inline">++++++</a>+++
202
+
203
+ [discrete]
204
+ ==== Inline Editing of Encrypted Files
205
+
206
+ The `sym` CLI tool supports one particularly interesting mode, that streamlines handling of encrypted files. The mode is called *edit mode*, and is activated with the `-t` flag.
207
+
208
+ Instead of decrypting data anytime you need to change it into a new file and then manually re-encrypting the result, you can use the shortcut flag `-t` (for "edi**t**"), which decrypts your data into a temporary file, automatically opening it with an `$EDITOR`.
209
+
210
+ sym -t config/application/secrets.yml.enc -k ~/.key
211
+
212
+ ____
213
+ This is one of those time-saving features that can make a difference in making encryption feel easy and transparent.
214
+ ____
215
+
216
+ NOTE: this mode does not seem to work with GUI editors such as Atom or TextMate. Since `sym` waits for the editor process to complete, GUI editors "complete" immediately upon starting a windowed application.
217
+
218
+ In this mode several flags are of importance:
219
+
220
+ -b (--backup) – will create a backup of the original file
221
+ -v (--verbose) - will show additional info about file sizes
222
+
223
+ Here is a full command that opens a file specified by `-f | --file`, using the key specified in `-k | --keyfile`, in the editor defined by the `$EDITOR` environment variable (or if not set -- defaults to `/bin/vi`)".
224
+
225
+ Example: here we edit an encrypted file in `vim`, while using interactive mode to paste the key (`-i | --interactive`), and then creating a backup file (`-b | --backup`) upon save:
226
+
227
+ sym -ibt data.enc
228
+ # => Private Key: ••••••••••••••••••••••••••••••••••••••••••••
229
+ #
230
+ # => Diff:
231
+ # 3c3
232
+ # # (c) 2015 Konstantin Gredeskoul. All rights reserved.
233
+ # ---
234
+ # # (c) 2016 Konstantin Gredeskoul. All rights reserved.
235
+
236
+ Note the `diff` shown after save.
237
+
238
+ +++<a name="rubyapi">++++++</a>+++
239
+
240
+ == Ruby API
241
+
242
+ === Including `Sym` module
243
+
244
+ Low-level encryption routines can be imported by including `Sym` module into your class or a module. Such class will be decorated with new class methods `#private_key` and `#create_private_key`, as well as instance methods `#encr`, and `#decr`.
245
+
246
+ ==== Class Method `#create_private_key()`
247
+
248
+ This method will generate a new key each time it's called.
249
+
250
+ ==== Class Method `#private_key(value = nil)`
251
+
252
+ This method will either assign an existing key (if a value is passed) or generate and save a new key in the class instance variable. Therefore each class including `Sym` will (by default) use a unique key (unless the key is passed in as an argument).
253
+
254
+ The following example illustrates this point:
255
+
256
+ [source,ruby]
257
+ ----
258
+ require 'sym'
259
+
260
+ class TestClass
261
+ include Sym
262
+ end
263
+
264
+ @key = TestClass.create_private_key
265
+ @key.eql?(TestClass.private_key) # => false
266
+ # A new key was created and saved in #private_key accessor.
267
+
268
+ class SomeClass
269
+ include Sym
270
+ private_key TestClass.private_key
271
+ end
272
+
273
+ @key.eql?(SomeClass.private_key) # => true (it was assigned)
274
+ ----
275
+
276
+ ==== Encrypting and Decrypting
277
+
278
+ So how would we use this library from another Ruby project to encrypt and decrypt values?
279
+
280
+ After including the `Sym` module, two instance methods are added:
281
+
282
+ * `#encr(value, private_key)` and
283
+ * `#decr(value, private_key)`.
284
+
285
+ Therefore you could write something like this below, protecting a sensitive string using a class-level secret.
286
+
287
+ [source,ruby]
288
+ ----
289
+ require 'sym'
290
+ class TestClass
291
+ include Sym
292
+ private_key ENV['SECRET']
293
+
294
+ def sensitive_value=(value)
295
+ @sensitive_value = encr(value, self.class.private_key)
296
+ end
297
+ def sensitive_value
298
+ decr(@sensitive_value, self.class.private_key)
299
+ end
300
+ end
301
+ ----
302
+
303
+ ==== Encrypting the Key Itself
304
+
305
+ You can encrypt the private key using a custom password. This is highly recommended, because without the password the key is the only piece that stands between an attacker and decrypting your sensitive data.
306
+
307
+ For this purpose, two more instance methods exist:
308
+
309
+ * `#encr_password(data, password, iv = nil)`
310
+ * `#decr_password(encrypted_data, password, iv = nil)`
311
+
312
+ They can be used independently of `encr` and `decr` to encrypt/decrypt any data with a password.
313
+
314
+ +++<a name="magic-file">++++++</a>+++
315
+
316
+ === Using `Sym::MagicFile` API for Reading/Writing Encrypted/Decrypted data
317
+
318
+ This is probably the easiest way to leverage Sym-encrypted files in your application -- by loading them into memory with `Sym::MagicFile`. This class provides a very simple API while supporting all of the convenience features of the rich application API (see below).
319
+
320
+ You instantiate `Sym::MagicFile` with just two parameters: a `pathname` to a file (encrypted
321
+ or not), and the `key` identifier. The identifier can either be a filename, or
322
+ OS-X Keychain entry, or environment variable name, etc -- basically it is resolve
323
+ like any other `-k <value>` CLI flag.
324
+
325
+ The following methods are available:
326
+
327
+ * `#encrypt` -- returns an encrypted string representing the encrypted contents ofa file specified by the pathname.
328
+ * `#decrypt` -- returns a decrypted string representing the decrypted contents of a file specified by the pathname.
329
+ * `#encrypt_to(filename)` -- encrypts the contents of a file specified by the pathname, and writes the result to a `filename`.
330
+ * `#decrypt_to(filename)` -- decrypts the contents of a file specified by the pathname, and writes the result to a `filename`.
331
+
332
+ ==== Example: Using `Sym::MagicFile` with the `RailsConfig` (or `Settings`) gem
333
+
334
+ In this example, we assume that the environment variable `$PRIVATE_KEY` contain
335
+ the key to be used in decryption.
336
+
337
+ [source,ruby]
338
+ ----
339
+ require 'sym/magic_file'
340
+ require 'yaml'
341
+ secrets = Sym::MagicFile.new('/usr/local/etc/secrets.yml.enc', 'PRIVATE_KEY')
342
+ hash = YAML.load(secrets.decrypt)
343
+ ----
344
+
345
+ Let's say that you are using https://github.com/railsconfig/config[RailsConfig] gem for managing your Rails application setings. Since the gem allows appending settings from a hash, you can simply do the following in your `settings_initializer.rb`, and after all of the unencrypted settings are loaded:
346
+
347
+ [source,ruby]
348
+ ----
349
+ require 'config'
350
+ require 'sym/magic_file'
351
+ require 'yaml'
352
+ Settings.add_source!(
353
+ YAML.load(
354
+ Sym::MagicFile.new(
355
+ '/usr/local/etc/secrets.yml.enc',
356
+ 'PRIVATE_KEY'
357
+ ).decrypt)
358
+ )
359
+ Settings.reload!
360
+ ----
361
+
362
+ +++<a name="rubyapi-app">++++++</a>+++
363
+
364
+ === Using `Sym::Application` API
365
+
366
+ Since the command line interface offers much more than just encryption/decryption of data with a key, majority of these features are available through `Sym::Application` instance.
367
+
368
+ The class is instantiated with a hash that would be otherwise generated by parsing CLI arguments, typical `options`. For example, to generate the key, pass `generate: true` -- essentially any flag in it's long form can be converted into a hash member.
369
+
370
+ Here is an example:
371
+
372
+ [source,ruby]
373
+ ----
374
+ require 'sym/application'
375
+
376
+ key = Sym::Application.new(generate: true).execute
377
+ # => '75ngenJpB6zL47/8Wo7Ne6JN1pnOsqNEcIqblItpfg4='
378
+ ----
379
+
380
+ === Ruby API Conclusion
381
+
382
+ Using ``Sym``'s rich ruby API you can perform both low-level encryption/decryption, as well as high-level management of encrypted files. By using `Sym::MagicFile` and/or `Sym::Application` classes you can access the entire set of functionality expressed vi the CLI, described in details below.
383
+
384
+ +++<a name="cli">++++++</a>+++
385
+
386
+ == Using `sym` with the Command Line
387
+
388
+ === Encryption Keys
389
+
390
+ The private key is the cornerstone of the symmetric encryption. Using `sym`, the key can be:
391
+
392
+ * generated and printed to STDOUT, or saved to Mac OS-X KeyChain or a file
393
+ * fetched from the Keychain in subsequent operations
394
+ * password-protected during generation (or import) with the `-p` flag.
395
+ * password can be cached using a locally running `memcached`, assuming the `-c` flag is provided.
396
+ * must be kept very well protected and secure from attackers.
397
+
398
+ The *unencrypted private* key will be in the form of a base64-encoded string, 45 characters long.
399
+
400
+ *Encrypted (with password) private key* will be considerably longer, perhaps 200-300 characters long.
401
+
402
+ ==== Generating the Key -- Examples
403
+
404
+ [source,bash]
405
+ ----
406
+ # Let's generate a new key, and copy it to the clipboard (using `pbcopy` command on Mac OS-X):
407
+ $ sym -g | pbcopy
408
+
409
+ # Or save a new key into a bash variable
410
+ $ KEY=$(sym -g)
411
+
412
+ # Or save it to a file:
413
+ $ sym -go ~/.key
414
+
415
+ # Or create a password-protected key (`-p`), and save it to a file (`-o`),
416
+ # cache the password (`-c`), and don't print the new key to STDOUT (`-q` for quiet)
417
+ $ sym -gpcqo ~/.secret
418
+ New Password: ••••••••••
419
+ Confirm Password: ••••••••••
420
+ $
421
+ ----
422
+
423
+ ==== Resolving the `-k` Argument
424
+
425
+ You can use the generated private key by passing an argument to the `-k` flag.
426
+
427
+ *Sym* attempts to automatically resolve the key source by trying each of the following options, and then moving on to the next until the key is found, or error is shown:
428
+
429
+ . the `-k value` flag, where the _value_ is one of:
430
+ ** a file path, eg (`-k ~/.key`)
431
+ ** an environment variable name (`-k MY_KEY`)
432
+ ** an actual base64-encoded key (not recommended for security reasons)
433
+ ** a keychain name (`-k keychain-entry-name`)
434
+ . pasting or typing the key with the `-i` (interactive) flag
435
+ . if exists, a default key file, located in your home folder: `~/.sym.key` is used only when no other key-specifying flags were passed in.
436
+
437
+ ==== Encryption and Decryption
438
+
439
+ +++<a name="inline">++++++</a>+++
440
+
441
+ ==== Inline Editing
442
+
443
+ The `sym` CLI tool supports one particularly interesting mode, that streamlines handling of encrypted files. The mode is called *edit mode*, and is activated with the `-t file` flag.
444
+
445
+ In this mode `sym` will automaticaly decrypt the encrypted file into a temporary file, and then open it in `$EDITOR`. Once you quit the editor, `sym` will automatically diff the new and old content, and if it is different, `sym` will re-encrypt the new contents and overwrite the original file. You can create an optional backup by adding `-b` flag.
446
+
447
+ NOTE: this mode does not seem to work with GUI editors such as Atom or TextMate. Since `sym` waits for the editor process to complete, GUI editors "complete" immediately upon starting a windowed application.
448
+ In this mode several flags are of importance:
449
+
450
+ -b (--backup) – will create a backup of the original file
451
+ -v (--verbose) - will show additional info about file sizes
452
+
453
+ Here is a full command that opens a file specified by `-t | --edit file`, using the key specified in `-k | --keyfile`, in the editor defined by the `$EDITOR` environment variable (or if not set -- defaults to `/bin/vi`)".
454
+
455
+ To edit an encrypted file in `$EDITOR`, while asking to paste the key (`-i | --interactive`), while creating a backup file (`-b | --backup`):
456
+
457
+
458
+ [source,bash]
459
+ ----
460
+ sym -tibf data.enc
461
+ # => Private Key: ••••••••••••••••••••••••••••••••••••••••••••
462
+ #
463
+ # => Diff:
464
+ # 3c3
465
+ # # (c) 2015 Konstantin Gredeskoul. All rights reserved.
466
+ # ---
467
+ # # (c) 2016 Konstantin Gredeskoul. All rights reserved.
468
+ ----
469
+
470
+ ==== Using KeyChain Access on Mac OS-X
471
+
472
+ KeyChain storage is a huge time saver. It allows you to securely store the key the keychain, meaning the key can not be easily extracted by an attacker without a login to your account. Just having access to the disk is not enough.
473
+
474
+ Apple had released a `security` command line tool, which this library uses to securely store a key/value pair of the key name and the actual private key in your OS-X KeyChain. The advantages of this method are numerous:
475
+
476
+ * The private key won't be lying around your file system unencrypted, so if your Mac is ever stolen, you don't need to worry about the keys running wild.
477
+ * If you sync your keychain with the iCloud you will have access to it on other machines
478
+
479
+ As mentioned previously, to add the key to the KeyChain on the Mac, use `-x <key-name>` flag with `-g` flag when generating a key. The `key name` is what you call this particular key, based on how you plan to use it. For example, you may call it `staging`, etc.
480
+
481
+ The following command generates the private key and immediately stores it in the KeyChain access under the name provided:
482
+
483
+ sym -gx staging # the key is passwordless
484
+ sym -gpcx staging # this key is password protected, with the password cached
485
+
486
+ Next, whenever you need to _use_ this key, you can specify the key with `-k staging`.
487
+
488
+ Finally, you can delete a key from KeyChain access by running:
489
+
490
+ keychain <name> delete
491
+
492
+ Below we describe the purpose of the executable `keychain` shipped with sym.
493
+
494
+ ==== KeyChain Key Management
495
+
496
+ `keychain` is an additional executable installed with the gem, which can be used to read (find), update (add), and delete keychain entries used by `sym`.
497
+
498
+ It's help message is self-explanatory:
499
+
500
+ Usage: keychain <name> [ add <contents> | find | delete ]
501
+
502
+ ==== Moving a Key to the Keychain
503
+
504
+ You can easily move an existing key from a file or a string to a keychain by combining -k or -k to read the key, with -x to write it.
505
+
506
+ sym -k $keysource -x mykey
507
+
508
+ ==== Adding Password to Existing Key
509
+
510
+ You can add a password to a key by combining one of the key description flags (-k, -i) and then also -p. Use `-q` to hide new key from the STDOUT, and `c` to cache the password.
511
+
512
+ sym -k $mykey -pqcx moo
513
+
514
+ The above example will take an unencrypted key passed in `$mykey`, ask for a password and save password protected key into the keychain with name "moo."
515
+
516
+ ==== Password Caching
517
+
518
+ Nobody likes to re-type passwords over and over again, and for this reason _Sym_ supports password caching via a locally running `memcached` instance (using the default port 11211, if available).
519
+
520
+ _Multiple Providers_
521
+
522
+ Cache is written using the Provider design pattern (a.k.a. plugin architecture), and so it's easy to add a new Cache Provider that uses a custom backend. The supplied production-ready provider only works with a `memcached` daemon running (ideally) locally.
523
+
524
+ For customization of memcached location, we refer you to the `Configuration` class for an example of how to configure MemCached provider -- shown below in the Ruby API section.
525
+
526
+ In order to control password caching, the following flags are available:
527
+
528
+ * `-c` turns on caching
529
+ * `-u seconds` sets the expiration for cached passwords
530
+ * `-r memcached` controls which of the providers is used. Without this flag, _sym_ auto-detects caching provider by first checking for `memcached`
531
+
532
+ ==== Saving Common Flags in an Environment Variable
533
+
534
+ You can optionally store frequently used flags for `sym` in the `SYM_ARGS` environment variable. For example, to always cache passwords, and to always use the same encryption key from the keychain named "production", set the following in your `~/.bashrc`:
535
+
536
+ ----
537
+ export SYM_ARGS="-cx production"
538
+ ----
539
+
540
+ This will be automatically appended to the command line if the `-A/--sym-args` flag is provided, and so to encrypt/decrypt anything with password caching enabled and using that particular key, you would simply type:
541
+
542
+ [source,bash]
543
+ ----
544
+ # -cx production are added from SYM_ARGS
545
+ sym -Aef file -o file.enc
546
+
547
+ # And to decrypt:
548
+ sym -Adf file.enc -o file.original
549
+
550
+ # Or edit the encrypted file:
551
+ sym -Atf file.enc
552
+ ----
553
+
554
+ == Fine Tuning
555
+
556
+ +++<a name="rubyapi-config">++++++</a>+++
557
+
558
+ === Configuration
559
+
560
+ The library contains a `Sym::Configuration` singleton class, which can be used to tweak some of the internals of the gem. Its meant for advanced users who know what they are doing. The code snippet shown below is an actual default configuration. You can override the defaults by including a similar snipped in your application initialization, right after the `require 'sym'`. The `Configuration` class is a Singleton, so changes to it will propagate to any subsequent calls to the gem.
561
+
562
+ [source,ruby]
563
+ ----
564
+ require 'zlib'
565
+ require 'sym'
566
+ Sym::Configuration.configure do |config|
567
+ config.password_cipher = 'AES-128-CBC'
568
+ config.data_cipher = 'AES-256-CBC'
569
+ config.private_key_cipher = config.data_cipher
570
+ config.compression_enabled = true
571
+ config.compression_level = Zlib::BEST_COMPRESSION
572
+ config.encrypted_file_extension = 'enc'
573
+ config.default_key_file = "#{ENV['HOME']}/.sym.key"
574
+
575
+ config.password_cache_timeout = 300
576
+
577
+ # When nil is selected, providers are auto-detected.
578
+ config.password_cache_default_provider = nil
579
+ config.password_cache_arguments = {
580
+ # In-memory password cache configuration:
581
+ # Memcached Provider – local is the default, but can be changed.
582
+ memcached: {
583
+ args: %w(127.0.0.1:11211),
584
+ opts: { namespace: 'sym',
585
+ compress: true,
586
+ expires_in: config.password_cache_timeout
587
+ }
588
+ }
589
+ }
590
+ end
591
+ ----
592
+
593
+ As you can see, it's possible to change the default cipher type, although not all ciphers will be code-compatible with the current algorithm, and may require additional code changes.
594
+
595
+ ==== Encryption Features & Cipher
596
+
597
+ The `sym` executable as well as the Ruby API provide:
598
+
599
+ * Symmetric data encryption with:
600
+ ** the Cipher `AES-256-cBC` used by the US Government
601
+ ** 256-bit private key, that
602
+ *** can be generated and is a _base64-encoded_ string about 45 characters long. The _decoded_ key is always 32 characters (or 256 bytes) long.
603
+ *** can be optionally password-encrypted using the 128-bit key, and then be automatically detected (and password requested) when the key is used
604
+ *** can optionally have its password cached for 15 minutes locally on the machine using `memcached`
605
+ * Rich command line interface with some innovative features, such as inline editing of an encrypted file, using your favorite `$EDITOR`.
606
+ * Data handling:
607
+ ** Automatic compression of the data upon encryption
608
+ ** Automatic base64 encryption to make all encrypted strings fit onto a single line.
609
+ ** This makes the format suitable for YAML or JSON configuration files, where only the values are encrypted.
610
+ * Rich Ruby API
611
+ * (OS-X Only): Ability to create, add and delete generic password entries from the Mac OS-X KeyChain, and to leverage the KeyChain to store sensitive private keys.
612
+
613
+ == Development
614
+
615
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
616
+
617
+ To install this gem onto your local machine, run `bundle exec rake install`.
618
+
619
+ To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to https://rubygems.org[rubygems.org].
620
+
621
+ [discrete]
622
+ ==== Contributing
623
+
624
+ Bug reports and pull requests are welcome on GitHub at https://github.com/kigster/sym
625
+
626
+ === License
627
+
628
+ *Sym* library is &copy; 2016-2020 Konstantin Gredeskoul and Contributors.
629
+
630
+ The gem is available as open source under the terms of the http://opensource.org/licenses/MIT[MIT License]. The library is designed to be a layer on top of https://www.openssl.org/[`OpenSSL`], distributed under the https://www.openssl.org/source/license.txt[Apache Style license].
631
+
632
+ === Acknowledgements
633
+
634
+ * The blog post http://stuff-things.net/2015/02/12/symmetric-encryption-with-ruby-and-rails/[(Symmetric) Encryption With Ruby (and Rails)] provided the inspiration for this gem.
635
+ * We'd like to thank http://stuff-things.net/spike/[Spike Ilacqua], the author of the https://github.com/spikex/strongbox[strongbox] gem, for providing very easy-to-read code examples of symmetric encryption.
636
+ * We'd like to thank https://github.com/bosswissam[Wissam Jarjoui] for support and inspiration, as well as testing of the early versions of this gem.
637
+
638
+ ==== Contributors:
639
+
640
+ Contributions of any kind are very much welcome from anyone.
641
+
642
+ Any pull requests will be reviewed promptly.
643
+
644
+ Please submit feature requests, bugs, or donations :)
645
+
646
+ * link:http:/kig.re[Konstantin Gredeskoul] (primary developer)
647
+ * https://github.com/bosswissam[Wissam Jarjoui] (testing, inspiration)
648
+ * https://github.com/meganmmathews[Megan Mathews] (UX, CLI suggestions)
649
+ * https://twitter.com/z3ndrag0n[Barry Anderson] (sanity checking, review)
650
+ * https://github.com/JustinNazari[Justin Nazari] (bug fixes)