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/README.md DELETED
@@ -1,620 +0,0 @@
1
- # Sym — Light-weight Symmetric Encryption for Humans
2
-
3
- [![Gem Version](https://badge.fury.io/rb/sym.svg)](https://badge.fury.io/rb/sym)
4
- [![Sym Downloads](http://ruby-gem-downloads-badge.herokuapp.com/sym?extension=svg)](https://rubygems.org/gems/sym)
5
- [![Build Status](https://travis-ci.org/kigster/sym.svg?branch=master)](https://travis-ci.org/kigster/sym)
6
- [![CircleCI](https://circleci.com/gh/kigster/sym.svg?style=svg)](https://circleci.com/gh/kigster/sym)
7
-
8
- [![Maintainability](https://api.codeclimate.com/v1/badges/4f1d1614ccaa61c974dd/maintainability)](https://codeclimate.com/github/kigster/sym/maintainability)
9
- [![Test Coverage](https://api.codeclimate.com/v1/badges/4f1d1614ccaa61c974dd/test_coverage)](https://codeclimate.com/github/kigster/sym/test_coverage)
10
- [![Issue Count](https://codeclimate.com/github/kigster/sym/badges/issue_count.svg)](https://codeclimate.com/github/kigster/sym)
11
- [![Gitter](https://img.shields.io/gitter/room/gitterHQ/gitter.svg)](https://gitter.im/kigster/sym)
12
-
13
-
14
- ---
15
-
16
- Please checkout the post "**[Dead Simple Encryption with Sym](http://kig.re/2017/03/10/dead-simple-encryption-with-sym.html)**" that announces this library, and provides further in-depth discussion. Your donation of absolutely any amount is very much appreciated.
17
-
18
- [![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=FSFYYNEQ8RKWU)
19
-
20
- ## Sym — Symmetric Encryption that's easy on Humans
21
-
22
- <div style="padding 40px; margin: 40px; font-size: 13pt;">
23
-
24
- <p><strong>sym</strong> is an open source command line utility and Ruby API which makes it very <em>easy to add reliable encryption and decryption</em> of sensitive data to an application or a project written in any language.</p>
25
-
26
- <p>Unlike many existing encryption tools, <strong>sym</strong> 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. </p>
27
-
28
- <p><strong>sym</strong> uses the <em><a href="https://en.wikipedia.org/wiki/Symmetric-key_algorithm">Symmetric Encryption</a></em> 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.</p>
29
-
30
- <p>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.</p>
31
-
32
- </div>
33
-
34
- ### Quick Demo of the CLI in Action
35
-
36
- [![asciicast](design/ascii-cinema.png)](https://asciinema.org/a/106737)
37
-
38
-
39
- #### Help Screens, Examples and Symit Bash Wrapper
40
-
41
- 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.
42
-
43
- Additionally, Sym comes with a helpful BASH wrapper `symit`.
44
-
45
- **Help screens for `sym` and `symit` are shown in full on another page — [Sym Help Screens and Symit](SYM-CLI.md). Please refer to it for complete help screens and the examples.**
46
-
47
-
48
- ## Supported Ruby Versions
49
-
50
- [![Build Status](https://travis-ci.org/kigster/sym.svg?branch=master)](https://travis-ci.org/kigster/sym)
51
-
52
- Sym currently builds and runs on the following ruby versions:
53
-
54
- * 2.2.9
55
- * 2.3.6
56
- * 2.4.3
57
- * 2.5.1
58
- * jruby-9.1.7.0
59
-
60
- ### Motivation
61
-
62
- 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.
63
-
64
- Most common use-cases include:
65
-
66
- * __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
67
- * __Secure message transfer between any number of receipients__
68
- * __General purpose encryption/decryption with a 256-bit encryption key__, optionally itself re-encrypted with a password.
69
- * __General purpose encryption/decryption with an arbitrary password__.
70
-
71
- __Sym__ is a layer built on top of the [`OpenSSL`](https://www.openssl.org/) library, and, hopefully, makes encryption more accessible to every-day developers, QA, and dev-ops folks, engaged in deploying applications.
72
-
73
- ### What's Included
74
-
75
- This gem includes two primary components:
76
-
77
- 1. **[Rich command line interface CLI](#cli)** with many features to streamline encryption/decryption, and to be integrated into the deployment flow.<br /><br />
78
- 2. Ruby APIs:
79
- * **[Key Generation, Encryption & Decryption API](#rubyapi)**
80
- - is activated by including `Sym` module in a class, it adds easy to use `encr`/`decr` methods.
81
- * **[Application API to shadow the CLI usage](#rubyapi-app)**
82
- - You can instantiate `Sym::Application` class with a hash representing CLI arguments, and then call it's `#execute` method to mimic CLI execution.
83
- * **[Sym::MagicFile API](#magic-file)**
84
- - This is a convenience class allowing you to encrypt/decrypt files in your ruby code with just couple of lines of code.
85
- * **[Sym::Configuration](#rubyapi-config)**
86
- - Use this class to override the default cipher, and configure other parameters such as compression, password caching, and more.
87
-
88
- ### Massive Time Savers
89
-
90
- **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:
91
-
92
- * 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.
93
- * By using a **password cache** (`-c`) via an in-memory provider such as `memcached` or `drb`, `sym` invocations take advantage of password cache, and only ask for a password once per a configurable time period.
94
- * By using **`SYM_ARGS` environment variable** you can save common flags and they will be applied whenever `-A` flag is activated.
95
- * By reading a key from the default key source file `~/.sym.key` which requires no flags at all.
96
- * By utilizing the **`--negate` option to quickly encrypt a regular file**, or decrypt an encrypted file with extension `.enc`.
97
- * By using the **`-t file` (edit) mode**, that opens an encrypted file in your `$EDITOR`, and replaces the encrypted version upon save & exit.
98
-
99
- 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.
100
-
101
- > Encrypting application secrets had never been easier! –– Socrates [LOL, -ed.]
102
-
103
- ## Using Sym
104
-
105
- #### Installation
106
-
107
- If you plan on using the library in your Ruby project with Bundler managing its dependencies, just include the following line in your `Gemfile`:
108
-
109
- gem 'sym'
110
-
111
- And then run `bundle`.
112
-
113
- Or install it into the global namespace with `gem install` command:
114
-
115
- $ gem install sym
116
- $ sym -h
117
- $ sym -E # see examples
118
-
119
- __BASH Completion__
120
-
121
- 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):
122
-
123
- sym -B ~/.bashrc
124
-
125
- 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.
126
-
127
- #### Typical Use-Case Scenario
128
-
129
- 1. 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:
130
- * optionally password protect the key with `sym -gp`
131
- * save the key into a file with `sym -gpo key-file`
132
- * save it into the OS-X Keychain, with `sym -gpx keychain-name`
133
- * cache the password, with `sym -gpcx keychain-name`
134
- * Normally, `sym` will print the resulting key to STDOUT
135
- * You can prevent the key from being printed to STDOUT with `-q/--quiet`.
136
- 2. Next, let's assume you have a file or a string that you want to encrypt. We call this *data*.
137
- 3. 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:
138
- * a file with a pathname specified by the argument (eg, `-k ~/.key`)
139
- * or environment variable (eg `-k ENC_KEY`)
140
- * or OS-X Keychain entry
141
- * verbatum string argument (not recommended)
142
- * alternatively, you can paste the key interactively with `-i` or save the default key in `~/.sym.key` file.
143
- 4. 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.
144
- 4. Instead of printing to STDOUT, the output can be saved to a file with `-o <file>` or a simple redirect or a pipe.
145
- 5. Encrypted file can later be decrypted with `sym -d ...` assuming the same key it was encrypted with.
146
- 6. 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.
147
- 7. 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 editing](#inline)
148
-
149
- A sample session that uses Mac OS-X Keychain to store the password-protected key.
150
-
151
- ```bash
152
- # Gen a new key, password-encrypt it, cache the password, save
153
- # result in the key chain entry 'my-new-key' (but don't print it '-q')
154
- ❯ sym -gpqcx my-new-key
155
- New Password : •••••••••
156
- Confirm Password : •••••••••
157
-
158
- ❯ sym -eck my-new-key -s 'My secret data' -o secret.enc
159
- Password: •••••••••
160
-
161
- ❯ cat secret.enc
162
- BAhTOh1TeW06OkRhdGE6OldyYXBFefDFFD.....
163
-
164
- ❯ sym -dck my-new-key -f secret.enc
165
- My secret data
166
-
167
- # Now, let's save our keychain key in the default key file:
168
- ❯ sym -ck my-new-key -o ~/.sym.key
169
- # Now we can decrypt/encrypt with this key at will
170
- ❯ sym -n secret.enc
171
- # created a decrypted file `secret`
172
-
173
- # Lets now save common flags in the SYM_ARGS bash variable:
174
- ❯ export SYM_ARGS="-ck my-new-key"
175
- ❯ sym -df secret.enc
176
- My secret data
177
- ```
178
-
179
- 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.
180
-
181
- <a name="inline"></a>
182
-
183
- #### Inline Editing of Encrypted Files
184
-
185
- 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.
186
-
187
- 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`.
188
-
189
- sym -t config/application/secrets.yml.enc -k ~/.key
190
-
191
- > This is one of those time-saving features that can make a difference in making encryption feel easy and transparent.
192
-
193
- > 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.
194
-
195
- In this mode several flags are of importance:
196
-
197
- -b (--backup) – will create a backup of the original file
198
- -v (--verbose) - will show additional info about file sizes
199
-
200
- 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`)".
201
-
202
- 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:
203
-
204
- sym -ibt data.enc
205
- # => Private Key: ••••••••••••••••••••••••••••••••••••••••••••
206
- #
207
- # => Diff:
208
- # 3c3
209
- # # (c) 2015 Konstantin Gredeskoul. All rights reserved.
210
- # ---
211
- # # (c) 2016 Konstantin Gredeskoul. All rights reserved.
212
-
213
- Note the `diff` shown after save.
214
-
215
- <a name="rubyapi"></a>
216
-
217
- ## Ruby API
218
-
219
- ### Including `Sym` module
220
-
221
- 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`.
222
-
223
- #### Class Method `#create_private_key()`
224
-
225
- This method will generate a new key each time it's called.
226
-
227
- #### Class Method `#private_key(value = nil)`
228
-
229
- 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).
230
-
231
- The following example illustrates this point:
232
-
233
- ```ruby
234
- require 'sym'
235
-
236
- class TestClass
237
- include Sym
238
- end
239
-
240
- @key = TestClass.create_private_key
241
- @key.eql?(TestClass.private_key) # => false
242
- # A new key was created and saved in #private_key accessor.
243
-
244
- class SomeClass
245
- include Sym
246
- private_key TestClass.private_key
247
- end
248
-
249
- @key.eql?(SomeClass.private_key) # => true (it was assigned)
250
- ```
251
-
252
- #### Encrypting and Decrypting
253
-
254
- So how would we use this library from another Ruby project to encrypt and decrypt values?
255
-
256
- After including the `Sym` module, two instance methods are added:
257
-
258
- * `#encr(value, private_key)` and
259
- * `#decr(value, private_key)`.
260
-
261
- Therefore you could write something like this below, protecting a sensitive string using a class-level secret.
262
-
263
- ```ruby
264
- require 'sym'
265
- class TestClass
266
- include Sym
267
- private_key ENV['SECRET']
268
-
269
- def sensitive_value=(value)
270
- @sensitive_value = encr(value, self.class.private_key)
271
- end
272
- def sensitive_value
273
- decr(@sensitive_value, self.class.private_key)
274
- end
275
- end
276
- ```
277
-
278
- #### Encrypting the Key Itself
279
-
280
- 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.
281
-
282
- For this purpose, two more instance methods exist:
283
-
284
- * `#encr_password(data, password, iv = nil)`
285
- * `#decr_password(encrypted_data, password, iv = nil)`
286
-
287
- They can be used independently of `encr` and `decr` to encrypt/decrypt any data with a password.
288
-
289
- <a name="magic-file"></a>
290
-
291
- ### Using `Sym::MagicFile` API for Reading/Writing Encrypted/Decrypted data
292
-
293
- 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).
294
-
295
- You instantiate `Sym::MagicFile` with just two parameters: a `pathname` to a file (encrypted
296
- or not), and the `key` identifier. The identifier can either be a filename, or
297
- OS-X Keychain entry, or environment variable name, etc — basically it is resolve
298
- like any other `-k <value>` CLI flag.
299
-
300
- The following methods are available:
301
-
302
- * `#encrypt` — returns an encrypted string representing the encrypted contents ofa file specified by the pathname.
303
- * `#decrypt` — returns a decrypted string representing the decrypted contents of a file specified by the pathname.
304
- * `#encrypt_to(filename)` — encrypts the contents of a file specified by the pathname, and writes the result to a `filename`.
305
- * `#decrypt_to(filename)` — decrypts the contents of a file specified by the pathname, and writes the result to a `filename`.
306
-
307
- #### Example: Using `Sym::MagicFile` with the `RailsConfig` (or `Settings`) gem
308
-
309
- In this example, we assume that the environment variable `$PRIVATE_KEY` contain
310
- the key to be used in decryption.
311
-
312
- ```ruby
313
- require 'sym/magic_file'
314
- require 'yaml'
315
- secrets = Sym::MagicFile.new('/usr/local/etc/secrets.yml.enc', 'PRIVATE_KEY')
316
- hash = YAML.load(secrets.decrypt)
317
- ```
318
-
319
- Let's say that you are using [RailsConfig](https://github.com/railsconfig/config) 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:
320
-
321
- ```ruby
322
- require 'config'
323
- require 'sym/magic_file'
324
- require 'yaml'
325
- Settings.add_source!(
326
- YAML.load(
327
- Sym::MagicFile.new(
328
- '/usr/local/etc/secrets.yml.enc',
329
- 'PRIVATE_KEY'
330
- ).decrypt)
331
- )
332
- Settings.reload!
333
- ```
334
-
335
- <a name="rubyapi-app"></a>
336
-
337
- ### Using `Sym::Application` API
338
-
339
- 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.
340
-
341
- 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.
342
-
343
- Here is an example:
344
-
345
- ```ruby
346
- require 'sym/application'
347
-
348
- key = Sym::Application.new(generate: true).execute
349
- # => '75ngenJpB6zL47/8Wo7Ne6JN1pnOsqNEcIqblItpfg4='
350
- ```
351
-
352
- ### Ruby API Conclusion
353
-
354
- 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.
355
-
356
- <a name="cli"></a>
357
- ## Using `sym` with the Command Line
358
-
359
- ### Encryption Keys
360
-
361
- The private key is the cornerstone of the symmetric encryption. Using `sym`, the key can be:
362
-
363
- * generated and printed to STDOUT, or saved to Mac OS-X KeyChain or a file
364
- * fetched from the Keychain in subsequent operations
365
- * password-protected during generation (or import) with the `-p` flag.
366
- * password can be cached using either `memcached` or `dRB` server, if the `-c` flag is provided.
367
- * must be kept very well protected and secure from attackers.
368
-
369
- The __unencrypted private__ key will be in the form of a base64-encoded string, 45 characters long.
370
-
371
- __Encrypted (with password) private key__ will be considerably longer, perhaps 200-300 characters long.
372
-
373
- #### Generating the Key — Examples
374
-
375
- ```bash
376
- # Let's generate a new key, and copy it to the clipboard (using `pbcopy` command on Mac OS-X):
377
- $ sym -g | pbcopy
378
-
379
- # Or save a new key into a bash variable
380
- $ KEY=$(sym -g)
381
-
382
- # Or save it to a file:
383
- $ sym -go ~/.key
384
-
385
- # Or create a password-protected key (`-p`), and save it to a file (`-o`),
386
- # cache the password (`-c`), and don't print the new key to STDOUT (`-q` for quiet)
387
- $ sym -gpcqo ~/.secret
388
- New Password: ••••••••••
389
- Confirm Password: ••••••••••
390
- $
391
- ```
392
-
393
- #### Resolving the `-k` Argument
394
-
395
- You can use the generated private key by passing an argument to the `-k` flag.
396
-
397
- **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:
398
-
399
- 1. the `-k value` flag, where the *value* is one of:
400
- * a file path, eg (`-k ~/.key`)
401
- * an environment variable name (`-k MY_KEY`)
402
- * an actual base64-encoded key (not recommended for security reasons)
403
- * a keychain name (`-k keychain-entry-name`)
404
- 2. pasting or typing the key with the `-i` (interactive) flag
405
- 3. 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.
406
-
407
- #### Encryption and Decryption
408
-
409
- <a name="inline"></a>
410
-
411
- #### Inline Editing
412
-
413
- 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.
414
-
415
- 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.
416
-
417
- > 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.
418
- In this mode several flags are of importance:
419
-
420
- -b (--backup) – will create a backup of the original file
421
- -v (--verbose) - will show additional info about file sizes
422
-
423
- 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`)".
424
-
425
- To edit an encrypted file in `$EDITOR`, while asking to paste the key (`-i | --interactive`), while creating a backup file (`-b | --backup`):
426
-
427
- sym -tibf data.enc
428
- # => Private Key: ••••••••••••••••••••••••••••••••••••••••••••
429
- #
430
- # => Diff:
431
- # 3c3
432
- # # (c) 2015 Konstantin Gredeskoul. All rights reserved.
433
- # ---
434
- # # (c) 2016 Konstantin Gredeskoul. All rights reserved.
435
-
436
-
437
- #### Using KeyChain Access on Mac OS-X
438
-
439
- 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.
440
-
441
- 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:
442
-
443
- * 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.
444
- * If you sync your keychain with the iCloud you will have access to it on other machines
445
-
446
- 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.
447
-
448
- The following command generates the private key and immediately stores it in the KeyChain access under the name provided:
449
-
450
- sym -gx staging # the key is passwordless
451
- sym -gpcx staging # this key is password protected, with the password cached
452
-
453
- Next, whenever you need to *use* this key, you can specify the key with `-k staging`.
454
-
455
- Finally, you can delete a key from KeyChain access by running:
456
-
457
- keychain <name> delete
458
-
459
- Below we describe the purpose of the executable `keychain` shipped with sym.
460
-
461
- #### KeyChain Key Management
462
-
463
- `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`.
464
-
465
- It's help message is self-explanatory:
466
-
467
- Usage: keychain <name> [ add <contents> | find | delete ]
468
-
469
- #### Moving a Key to the Keychain
470
-
471
- 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.
472
-
473
- sym -k $keysource -x mykey
474
-
475
- #### Adding Password to Existing Key
476
-
477
- 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.
478
-
479
- sym -k $mykey -pqcx moo
480
-
481
- 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."
482
-
483
- #### Password Caching
484
-
485
- Nobody likes to re-type passwords over and over again, and for this reason *Sym* supports password caching via either a locally running `memcached` instance (the default, if available), or a locally started `dRB` (distributed Ruby) server based on the `Coin` gem.
486
-
487
- Specifics of configuring both Cache Providers is left to the `Configuration` class, an example of which is shown below in the Ruby API section.
488
-
489
- In order to control password caching, the following flags are available:
490
-
491
- * `-c` turns on caching
492
- * `-u seconds` sets the expiration for cached passwords
493
- * `-r memcached | drb` controls which of the providers is used. Without this flag, *sym* auto-detects caching provider by first checking for `memcached`, and then starting the `dRB` server.
494
-
495
- #### Saving Common Flags in an Environment Variable
496
-
497
- 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`:
498
-
499
- ```
500
- export SYM_ARGS="-cx production"
501
- ```
502
-
503
- 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:
504
-
505
- ```bash
506
- # -cx production are added from SYM_ARGS
507
- sym -Aef file -o file.enc
508
-
509
- # And to decrypt:
510
- sym -Adf file.enc -o file.original
511
-
512
- # Or edit the encrypted file:
513
- sym -Atf file.enc
514
- ```
515
-
516
- ## Fine Tuning
517
-
518
- <a name="rubyapi-config"></a>
519
-
520
- ### Configuration
521
-
522
- 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.
523
-
524
- ```ruby
525
- require 'zlib'
526
- require 'sym'
527
- Sym::Configuration.configure do |config|
528
- config.password_cipher = 'AES-128-CBC'
529
- config.data_cipher = 'AES-256-CBC'
530
- config.private_key_cipher = config.data_cipher
531
- config.compression_enabled = true
532
- config.compression_level = Zlib::BEST_COMPRESSION
533
- config.encrypted_file_extension = 'enc'
534
- config.default_key_file = "#{ENV['HOME']}/.sym.key"
535
-
536
- config.password_cache_timeout = 300
537
-
538
- # When nil is selected, providers are auto-detected.
539
- config.password_cache_default_provider = nil
540
- config.password_cache_arguments = {
541
- # Ruby dRB-based in-memory cache.
542
- drb: {
543
- opts: {
544
- uri: 'druby://127.0.0.1:24924'
545
- }
546
- },
547
- # Memcached Provider – local is the default, but can be changed.
548
- memcached: {
549
- args: %w(127.0.0.1:11211),
550
- opts: { namespace: 'sym',
551
- compress: true,
552
- expires_in: config.password_cache_timeout
553
- }
554
- }
555
- }
556
- end
557
-
558
- ```
559
-
560
- 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.
561
-
562
-
563
- #### Encryption Features & Cipher
564
-
565
- The `sym` executable as well as the Ruby API provide:
566
-
567
- * Symmetric data encryption with:
568
- * the Cipher `AES-256-cBC` used by the US Government
569
- * 256-bit private key, that
570
- * can be generated and is a *base64-encoded* string about 45 characters long. The *decoded* key is always 32 characters (or 256 bytes) long.
571
- * can be optionally password-encrypted using the 128-bit key, and then be automatically detected (and password requested) when the key is used
572
- * can optionally have its password cached for 15 minutes locally on the machine using `memcached` or using a `dRB` server
573
- * Rich command line interface with some innovative features, such as inline editing of an encrypted file, using your favorite `$EDITOR`.
574
- * Data handling:
575
- * Automatic compression of the data upon encryption
576
- * Automatic base64 encryption to make all encrypted strings fit onto a single line.
577
- * This makes the format suitable for YAML or JSON configuration files, where only the values are encrypted.
578
- * Rich Ruby API
579
- * (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.
580
-
581
- ## Development
582
-
583
- 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.
584
-
585
- To install this gem onto your local machine, run `bundle exec rake install`.
586
-
587
- 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 [rubygems.org](https://rubygems.org).
588
-
589
- #### Contributing
590
-
591
- Bug reports and pull requests are welcome on GitHub at [https://github.com/kigster/sym](https://github.com/kigster/sym)
592
-
593
- ### License
594
-
595
- **Sym** library is &copy; 2016-2018 Konstantin Gredeskoul.
596
-
597
- The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). The library is designed to be a layer on top of [`OpenSSL`](https://www.openssl.org/), distributed under the [Apache Style license](https://www.openssl.org/source/license.txt).
598
-
599
- ### Acknowledgements
600
-
601
- * The blog post [(Symmetric) Encryption With Ruby (and Rails)](http://stuff-things.net/2015/02/12/symmetric-encryption-with-ruby-and-rails/) provided the inspiration for this gem.
602
- * We'd like to thank [Spike Ilacqua](http://stuff-things.net/spike/), the author of the [strongbox](https://github.com/spikex/strongbox) gem, for providing very easy-to-read code examples of symmetric encryption.
603
- * We'd like to thank [Wissam Jarjoui](https://github.com/bosswissam) for support and inspiration, as well as testing of the early versions of this gem.
604
-
605
-
606
- #### Contributors:
607
-
608
- Contributions of any kind are very much welcome from anyone.
609
-
610
- Any pull requests will be reviewed promptly.
611
-
612
- Please submit feature requests, bugs, or donations :)
613
-
614
- * [Konstantin Gredeskoul](http:/kig.re) (primary developer)
615
- * [Wissam Jarjoui](https://github.com/bosswissam) (testing, inspiration)
616
- * [Megan Mathews](https://github.com/meganmmathews) (UX, CLI suggestions)
617
- * [Barry Anderson](https://twitter.com/z3ndrag0n) (sanity checking, review)
618
- * [Justin Nazari](https://github.com/JustinNazari) (bug fixes)
619
-
620
-