prevoty-rails 0.6.2 → 1.0.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/LICENSE +201 -0
- data/README.md +35 -45
- data/lib/generators/prevoty/rails/USAGE +2 -3
- data/lib/generators/prevoty/rails/install_generator.rb +2 -2
- data/lib/generators/prevoty/rails/templates/prevoty_rails.yml +78 -0
- data/lib/prevoty-rails.rb +2 -10
- data/lib/prevoty/content_monitor.rb +10 -7
- data/lib/prevoty/monitor.rb +1 -4
- data/lib/prevoty/query_handler.rb +83 -0
- data/lib/prevoty/query_monitor.rb +8 -14
- data/lib/prevoty/rails/version.rb +1 -1
- data/lib/prevoty/railtie.rb +46 -0
- data/lib/rack/content_middleware.rb +132 -9
- data/prevoty-rails.gemspec +1 -1
- metadata +7 -9
- data/LICENSE.txt +0 -22
- data/lib/action_controller/request_forgery_protection.rb +0 -36
- data/lib/generators/prevoty/rails/templates/prevoty_rails.rb +0 -86
- data/lib/rack/interceptor.rb +0 -61
- data/lib/rack/monitor_interceptor.rb +0 -51
- data/lib/rack/protect_interceptor.rb +0 -94
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA1:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: d2567c24b8e45e33ca9067dd6bd57734d4c62c4e
|
4
|
+
data.tar.gz: fdd4bfb6bf22739df34736dc189c236c93dd1019
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: cd761c868416d507cbee69fc2ed581e3a0c0bb19590911ef5fc74dab1a305bd9385e8820abdd333e417ff1e8c0865a917d62e8915fa686a5d2f3312ad791983a
|
7
|
+
data.tar.gz: 1977b04e8b3ac8cc352ed2365dc16d74c26e06d63f89d9701ecac310e86afaf48d1abc3a7d9acf819e546b81710cc844ae84462f6ccef140931566914996e477
|
data/LICENSE
ADDED
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright 2015 Prevoty, Inc.
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|
data/README.md
CHANGED
@@ -1,16 +1,16 @@
|
|
1
1
|
# prevoty-rails
|
2
2
|
|
3
|
-
prevoty-rails is a plugin to automatically integrate Prevoty's content filtering and SQL anlysis engine into a Rails application. The content filter is distributed as a Rack middleware
|
3
|
+
prevoty-rails is a plugin to automatically integrate Prevoty's content filtering and SQL anlysis engine into a Rails application. The content filter is distributed as a Rack middleware and can be used on any rack based framework including Rails. The SQL analysis is tied specifically to Rails due to the ActiveRecord and ActiveSupport integration that it depends on.
|
4
4
|
|
5
5
|
## Installation
|
6
6
|
|
7
|
-
Add this line to your application's Gemfile:
|
7
|
+
1. Add this line to your application's Gemfile:
|
8
8
|
|
9
9
|
```ruby
|
10
10
|
gem 'prevoty-rails'
|
11
11
|
```
|
12
12
|
|
13
|
-
And then execute:
|
13
|
+
2. And then execute:
|
14
14
|
|
15
15
|
$ bundle
|
16
16
|
|
@@ -18,50 +18,40 @@ Or install it yourself as:
|
|
18
18
|
|
19
19
|
$ gem install prevoty-rails
|
20
20
|
|
21
|
-
|
22
|
-
Add the following line into your config/application.rb file to use the Prevoty content filter in all environments or add it to the specific environment (eg. testing/production) that you would like to use it with.
|
23
|
-
|
24
|
-
```ruby
|
25
|
-
config.middleware.use Rack::Prevoty::ContentMiddleware, {api_key: '', configuration_key: ''}
|
26
|
-
```
|
27
|
-
|
28
|
-
### SQL Analysis
|
29
|
-
First use the generator to install the initializer needed for SQL.
|
21
|
+
3. Run the installer
|
30
22
|
|
31
23
|
```shell
|
32
24
|
rails generate prevoty:rails:install
|
33
25
|
```
|
34
26
|
|
35
|
-
|
36
|
-
|
37
|
-
|
38
|
-
|
39
|
-
|
40
|
-
|
41
|
-
|
42
|
-
|
43
|
-
|
44
|
-
|
45
|
-
-
|
46
|
-
-
|
47
|
-
-
|
48
|
-
|
49
|
-
|
50
|
-
|
51
|
-
|
52
|
-
|
53
|
-
|
54
|
-
|
55
|
-
|
56
|
-
|
57
|
-
|
58
|
-
|
59
|
-
|
60
|
-
|
61
|
-
|
62
|
-
|
63
|
-
|
64
|
-
|
65
|
-
|
66
|
-
- `failure_mode`: ['block' | 'continue'] Determines whether to stop the request or let it continue if there is an error when sql analysis is in 'protect' mode (default: 'continue')
|
67
|
-
- `callback`: Proc object to call when log_destination is set to callback
|
27
|
+
4. Update the configuration file
|
28
|
+
|
29
|
+
Running the installer will generate the Prevoty Rails plugin configuration file located at config/prevoty_rails.yml. This file has all of the possible options with default values. Unless desired to change from the defaults all values may be left commented out. The only required options are a v1 api key located in the Prevoty Manager and policy keys for content and query.
|
30
|
+
|
31
|
+
## ActiveSupport::Notification Events
|
32
|
+
|
33
|
+
The following are a list of all Prevoty supplied notifications that can be subscribed to via the ActiveSupport::Notifications class. You may subscribe to these events with as many callbacks as you like but each one will be called sequentially and block the application until control is returned.
|
34
|
+
|
35
|
+
prevoty:content:protect - Prevoty has processed the querystring or body of a request in protect mode
|
36
|
+
prevoty:content:monitor - Prevoty has processed a batch of querystrings and bodies in monitor mode
|
37
|
+
prevoty:query:protect - Prevoty has processed a SQL query in protect mode
|
38
|
+
prevoty:query:monitor - Prevoty has processed a batch of queries in monitor mode
|
39
|
+
prevoty:query:failure - Prevoty has failed to process a SQL query
|
40
|
+
|
41
|
+
An example for using these events to access information about the various notifications is as follows.. This code should be place in an initializer, such as in 'config/initializers/prevoty_listeners.rb', or somewhere that is expected to run on startup of the Rails application.
|
42
|
+
|
43
|
+
```ruby
|
44
|
+
handler = ->(name, start, finish, id, payload) do
|
45
|
+
puts name
|
46
|
+
puts start
|
47
|
+
puts finish
|
48
|
+
puts id
|
49
|
+
puts payload.inspect
|
50
|
+
end
|
51
|
+
|
52
|
+
ActiveSupport::Notifications.subscribe 'prevoty:content:protect', handler
|
53
|
+
ActiveSupport::Notifications.subscribe 'prevoty:content:monitor', handler
|
54
|
+
ActiveSupport::Notifications.subscribe 'prevoty:query:protect', handler
|
55
|
+
ActiveSupport::Notifications.subscribe 'prevoty:query:monitor', handler
|
56
|
+
ActiveSupport::Notifications.subscribe 'prevoty:query:failure', handler
|
57
|
+
```
|
@@ -1,9 +1,8 @@
|
|
1
1
|
Description:
|
2
|
-
Generates the
|
3
|
-
Prevoty's Ruby plugin.
|
2
|
+
Generates the config file for the prevoty rails plugin
|
4
3
|
|
5
4
|
Examples:
|
6
5
|
rails generate prevoty:rails:install
|
7
6
|
|
8
|
-
This will generate the
|
7
|
+
This will generate the config file for the Prevoty rails plugin for
|
9
8
|
your rails app.
|
@@ -5,8 +5,8 @@ module Prevoty
|
|
5
5
|
class InstallGenerator < ::Rails::Generators::Base
|
6
6
|
source_root File.expand_path('../templates', __FILE__)
|
7
7
|
|
8
|
-
def
|
9
|
-
|
8
|
+
def copy_config_file
|
9
|
+
copy_file "prevoty_rails.yml", "config/prevoty_rails.yml"
|
10
10
|
end
|
11
11
|
end
|
12
12
|
end
|
@@ -0,0 +1,78 @@
|
|
1
|
+
# The hostname for the api server. This points to Prevoty's cloud api by
|
2
|
+
# default and must be adjusted to point to an on premise installation.
|
3
|
+
# Enabling and disabling SSL support can be done by specifing http/https as
|
4
|
+
# the protocol.
|
5
|
+
# :api_base: 'https://api.prevoty.com'
|
6
|
+
|
7
|
+
# The v1 API key to use for authenticating with API. This must be a v1 API
|
8
|
+
# to correctly work. Authentication will fail otherwise. This is the only
|
9
|
+
# required configuration option.
|
10
|
+
:api_key: ''
|
11
|
+
|
12
|
+
content:
|
13
|
+
# The operating mode for the content plugin
|
14
|
+
# values: ['monitor', 'protect']
|
15
|
+
# :mode: 'monitor'
|
16
|
+
|
17
|
+
# The content policy to use for protect mode
|
18
|
+
# :policy_key: ''
|
19
|
+
|
20
|
+
# Whether to log only on attacks or for every payload processed
|
21
|
+
# values: ['incident', 'all']
|
22
|
+
# :log_verbosity: 'incident'
|
23
|
+
|
24
|
+
# Specific URI paths to perform processing on. By default this is set to
|
25
|
+
# '/' so that all paths in the app are processed. If you would prefer to
|
26
|
+
# whitelist more agressively an array of paths can be specified here.
|
27
|
+
# :paths:
|
28
|
+
# - '/'
|
29
|
+
|
30
|
+
# Specific URI paths to ignore for processing. This must be represented as a
|
31
|
+
# YAML array. By default is an empty array.
|
32
|
+
# :blacklist:
|
33
|
+
|
34
|
+
# The percentage of traffice that should be inspected by the Prevoty
|
35
|
+
# plugins. This will follow the full request/response lifecycle so so if
|
36
|
+
# processing is skipped for content it will also be skipped for all queries
|
37
|
+
# originating from the request. The only exception to this is queries that
|
38
|
+
# are created in separate threads. The default value is 100.
|
39
|
+
# values: 0 - 100
|
40
|
+
# :traffic_percentage: 100
|
41
|
+
|
42
|
+
query:
|
43
|
+
# The operating mode for the query plugin
|
44
|
+
# values: ['monitor', 'protect']
|
45
|
+
# :mode: 'monitor'
|
46
|
+
|
47
|
+
# The query policy to use for protect mode
|
48
|
+
# :policy_key: ''
|
49
|
+
|
50
|
+
# Whether to log only on attacks or for every payload processed
|
51
|
+
# values: ['incident', 'all']
|
52
|
+
# :log_verbosity: 'incident'
|
53
|
+
|
54
|
+
# Interval in milliseconds to submit queries for monitoring. This will be
|
55
|
+
# reset if the queries are submitted earlier due to exceeding the reporting
|
56
|
+
# count
|
57
|
+
# :reporting_milliseconds: 10000
|
58
|
+
|
59
|
+
# Maximum queue size for queries before submitting for monitoring. If the
|
60
|
+
# reporting timeout is reched before this is hit the queue will reset back
|
61
|
+
# to zero.
|
62
|
+
# :reporting_count: 50
|
63
|
+
|
64
|
+
# The database vendor for monitor mode
|
65
|
+
# values: ['mysql', 'mssql', 'oracle', 'db2']
|
66
|
+
# :db_vendor: ''
|
67
|
+
|
68
|
+
# The database's version
|
69
|
+
# :db_version: ''
|
70
|
+
|
71
|
+
# The default database name to use
|
72
|
+
# :db_name: ''
|
73
|
+
|
74
|
+
# Block queries with violations in protect mode
|
75
|
+
# :violation_mode: 'continue'
|
76
|
+
|
77
|
+
# Block queries that fail to parse in protect mode
|
78
|
+
# :failure_mode: 'continue'
|
data/lib/prevoty-rails.rb
CHANGED
@@ -2,6 +2,7 @@ require 'prevoty/adapters'
|
|
2
2
|
require 'prevoty/monitor'
|
3
3
|
require 'prevoty/content_monitor'
|
4
4
|
require 'prevoty/query_monitor'
|
5
|
+
require 'prevoty/query_handler'
|
5
6
|
require 'prevoty/query_payload'
|
6
7
|
require 'prevoty/query_violation'
|
7
8
|
require 'prevoty/query_failure'
|
@@ -9,13 +10,4 @@ require 'prevoty/build_query_result'
|
|
9
10
|
require 'prevoty/rails/version'
|
10
11
|
require 'prevoty/logger'
|
11
12
|
require 'rack/content_middleware'
|
12
|
-
|
13
|
-
# Uncommenting this enables Prevoty CSRF protection that overloads the
|
14
|
-
# built-in Rails implementation. There isn't a good way to specify the action
|
15
|
-
# since we don't know where the form will POST to at the point we're hooking
|
16
|
-
# so it makes the token less secure given that they all share a common action.
|
17
|
-
# Rails generates a token and uses it session wide then masks it using a one
|
18
|
-
# time pad and xor so that each time it's on the page it appears different to
|
19
|
-
# mitigate against the BREACH SSL attack. This essentially creates a unique
|
20
|
-
# token for each request which is the approach Prevoty takes.
|
21
|
-
# require 'action_controller/request_forgery_protection'
|
13
|
+
require 'prevoty/railtie' if defined?(Rails)
|
@@ -10,13 +10,16 @@ module Prevoty
|
|
10
10
|
data = cloned.inject([]) {|arr, i| arr.push i[:input]; arr}
|
11
11
|
begin
|
12
12
|
Timeout::timeout(@timeout) do
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
13
|
+
resp = nil
|
14
|
+
if defined? ActiveSupport::Notifications
|
15
|
+
ActiveSupport::Notifications.instrument('prevoty:content:monitor') do |payload|
|
16
|
+
resp = payload[:response] = res = @client.monitor_content(data)
|
17
|
+
end
|
18
|
+
end
|
19
|
+
resp.each_with_index do |r, i|
|
20
|
+
result = ::Rack::Prevoty::ContentMiddleware.build_result(cloned[i][:mode], cloned[i][:request], cloned[i][:input], r)
|
21
|
+
if r.is_significant? || @log_verbosity === 'all'
|
22
|
+
::Prevoty::LOGGER << result.to_json + "\n"
|
20
23
|
end
|
21
24
|
end
|
22
25
|
end
|
data/lib/prevoty/monitor.rb
CHANGED
@@ -5,17 +5,14 @@ module Prevoty
|
|
5
5
|
class Monitor
|
6
6
|
DEFAULT_TIMEOUT = 10000
|
7
7
|
DEFAULT_MAX_SIZE = 50
|
8
|
-
DEFAULT_LOG_DESTINATION = 'log'
|
9
8
|
|
10
9
|
def initialize(client, options = {})
|
11
10
|
options[:reporting_milliseconds] ||= DEFAULT_TIMEOUT
|
12
11
|
|
13
12
|
@client = client
|
14
|
-
@before_callback = options[:before_callback]
|
15
|
-
@after_callback = options[:after_callback]
|
16
13
|
@max_size = options[:max_size] || DEFAULT_MAX_SIZE
|
17
|
-
@log_destination = options[:log_destination] || DEFAULT_LOG_DESTINATION
|
18
14
|
@timeout = options[:reporting_milliseconds] / 1000
|
15
|
+
@log_verbosity = options[:log_verbosity] ||= 'incident'
|
19
16
|
@mutex = Mutex.new
|
20
17
|
@queue = []
|
21
18
|
@rd, @wr = IO.pipe
|
@@ -0,0 +1,83 @@
|
|
1
|
+
require 'prevoty/query_violation'
|
2
|
+
require 'prevoty/query_failure'
|
3
|
+
require 'prevoty/query_payload'
|
4
|
+
require 'prevoty/build_query_result'
|
5
|
+
require 'prevoty/logger'
|
6
|
+
|
7
|
+
class QueryHandler
|
8
|
+
include Prevoty::BuildQueryResult
|
9
|
+
|
10
|
+
def initialize(opts)
|
11
|
+
@base = opts[:api_base] ||= 'https://api.prevoty.com'
|
12
|
+
@client = ::Prevoty::Client.new(opts[:api_key], @base)
|
13
|
+
@policy_key = opts[:policy_key] ||= ''
|
14
|
+
@mode = opts[:mode] ||= 'monitor'
|
15
|
+
@log_verbosity = opts[:log_verbosity] ||= 'incident'
|
16
|
+
@reporting_milliseconds = opts[:reporting_milliseconds] ||= 10000
|
17
|
+
@reporting_count = opts[:reporting_count] ||= 50
|
18
|
+
@db_vendor = opts[:db_vendor] ||= ''
|
19
|
+
@db_version = opts[:db_version] ||= ''
|
20
|
+
@db_name = opts[:db_name] ||= ''
|
21
|
+
@violation_mode = opts[:violation_mode] ||= 'block'
|
22
|
+
@failure_mode = opts[:failure_mode] ||= 'continue'
|
23
|
+
|
24
|
+
if @mode === 'monitor'
|
25
|
+
@monitor = ::Prevoty::QueryMonitor.new(@client, opts)
|
26
|
+
end
|
27
|
+
end
|
28
|
+
|
29
|
+
def handle(name, start, finish, id, payload)
|
30
|
+
# ActiveRecord does some wonky stuff on startup that causes a query to be
|
31
|
+
# executed that doesn't seem to pass through the rack middleware so the
|
32
|
+
# request_storage key doesn't exist. It's unclear if there are other
|
33
|
+
# situations that also cause this but because of it we need to use try here
|
34
|
+
# to ensure there are no nil pointer exceptions
|
35
|
+
if Thread.current[:request_storage].try(:[], :skip_processing)
|
36
|
+
return
|
37
|
+
end
|
38
|
+
|
39
|
+
unless payload[:name] =~ /SQL|Load/
|
40
|
+
return
|
41
|
+
end
|
42
|
+
|
43
|
+
case @mode
|
44
|
+
when 'monitor'
|
45
|
+
package = {vendor: @db_vendor, database: @db_name, version: @db_version, query: payload[:sql]}
|
46
|
+
@monitor.process(package)
|
47
|
+
when 'protect'
|
48
|
+
begin
|
49
|
+
resp = nil
|
50
|
+
ActiveSupport::Notifications.instrument('prevoty:query:protect') do |resp_payload|
|
51
|
+
resp = resp_payload[:response] = @client.analyze_query(payload[:sql], @policy_key)
|
52
|
+
end
|
53
|
+
|
54
|
+
# always log because we're either set to all or incident
|
55
|
+
if resp.processed and not resp.compliant
|
56
|
+
::Prevoty::LOGGER << build_result(@mode, payload[:sql], resp).to_json + "\n"
|
57
|
+
raise ::Prevoty::QueryViolation.new if @violation_mode === 'block'
|
58
|
+
elsif resp.processed and resp.compliant
|
59
|
+
# all good, only log if log verbosity is all
|
60
|
+
if @log_verbosity === 'all'
|
61
|
+
::Prevoty::LOGGER << build_result(@mode, payload[:sql], resp).to_json + "\n"
|
62
|
+
end
|
63
|
+
elsif not resp.processed and not resp.compliant
|
64
|
+
# query failure
|
65
|
+
if @log_verbosity === 'all'
|
66
|
+
::Prevoty::LOGGER << build_result(@mode, payload[:sql], resp).to_json + "\n"
|
67
|
+
end
|
68
|
+
ActiveSupport::Notifications.instrument('prevoty:query:failure', response: resp)
|
69
|
+
raise ::Prevoty::QueryFailure.new
|
70
|
+
end
|
71
|
+
rescue ::Prevoty::QueryViolation => e
|
72
|
+
# need to catch and rethrow to catch other exceptions
|
73
|
+
raise e
|
74
|
+
rescue ::Prevoty::QueryFailure => e
|
75
|
+
# need to catch and rethrow to catch other exceptions
|
76
|
+
raise e
|
77
|
+
rescue Exception => e
|
78
|
+
Rails.logger.error e.message
|
79
|
+
raise e if @failure_mode === 'block'
|
80
|
+
end
|
81
|
+
end
|
82
|
+
end
|
83
|
+
end
|
@@ -11,25 +11,19 @@ module Prevoty
|
|
11
11
|
@queue = []
|
12
12
|
Thread.new do
|
13
13
|
begin
|
14
|
-
@before_callback.call(cloned) if @log_destination === 'callback' and @before_callback.respond_to? :call
|
15
14
|
Timeout::timeout(@timeout) do
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
|
22
|
-
|
15
|
+
resp = nil
|
16
|
+
ActiveSupport::Notifications.instrument('prevoty:query:monitor') do |payload|
|
17
|
+
resp = payload[:response] = @client.monitor_query(cloned)
|
18
|
+
end
|
19
|
+
resp.each_with_index do |r, i|
|
20
|
+
if r.processed || @log_verbosity === 'all'
|
21
|
+
Prevoty::LOGGER << build_result('monitor', cloned[i][:query], r).to_json + "\n"
|
23
22
|
end
|
24
23
|
end
|
25
24
|
end
|
26
25
|
rescue Exception => e
|
27
|
-
|
28
|
-
when 'log'
|
29
|
-
::Rails.logger.error e.message
|
30
|
-
when 'callback'
|
31
|
-
@error_callback.call(e.message) if @error_callback.respond_to? :call
|
32
|
-
end
|
26
|
+
::Rails.logger.error e.message
|
33
27
|
end
|
34
28
|
end
|
35
29
|
end
|
@@ -0,0 +1,46 @@
|
|
1
|
+
module Prevoty
|
2
|
+
class Railtie < ::Rails::Railtie
|
3
|
+
initializer "load config file" do |app|
|
4
|
+
begin
|
5
|
+
@config = YAML.load(File.read(File.join(::Rails.root, 'config', 'prevoty_rails.yml')))
|
6
|
+
rescue Errno::ENOENT
|
7
|
+
# Config file doesn't exist. This may be because the installer hasn't
|
8
|
+
# been run yet or it's missing. If it's simply missing let something
|
9
|
+
# down the line file and provide a more useful error message since we
|
10
|
+
# wont know where what the condition should be
|
11
|
+
end
|
12
|
+
end
|
13
|
+
|
14
|
+
initializer "insert content rack middleware" do |app|
|
15
|
+
# If we didn't load the config file we might be getting installed or
|
16
|
+
# there is just an error, don't attempt to load otherwise we'll hit a
|
17
|
+
# nil pointer
|
18
|
+
next if @config.nil?
|
19
|
+
|
20
|
+
content_config = {}
|
21
|
+
content_config[:api_base] = @config[:api_base] unless @config[:api_base].nil?
|
22
|
+
content_config[:api_key] = @config[:api_key] unless @config[:api_key].nil?
|
23
|
+
# if no keys are set in the content block it will return nil so we need
|
24
|
+
# to make sure we have an empty hash to merge
|
25
|
+
content_config = (@config["content"] || {}).merge(content_config)
|
26
|
+
app.middleware.use ::Rack::Prevoty::ContentMiddleware, content_config
|
27
|
+
end
|
28
|
+
|
29
|
+
initializer "setup ActiveRecord notification listener" do |app|
|
30
|
+
# If we didn't load the config file we might be getting installed or
|
31
|
+
# there is just an error, don't attempt to load otherwise we'll hit a
|
32
|
+
# nil pointer
|
33
|
+
next if @config.nil?
|
34
|
+
|
35
|
+
query_config = {}
|
36
|
+
query_config[:api_base] = @config[:api_base] unless @config[:api_base].nil?
|
37
|
+
query_config[:api_key] = @config[:api_key] unless @config[:api_key].nil?
|
38
|
+
# if no keys are set in the query block it will return nil so we need
|
39
|
+
# to make sure we have an empty hash to merge
|
40
|
+
query_config = (@config["query"] || {}).merge(query_config)
|
41
|
+
@query_handler = QueryHandler.new(query_config)
|
42
|
+
|
43
|
+
ActiveSupport::Notifications.subscribe 'sql.active_record', &@query_handler.method(:handle)
|
44
|
+
end
|
45
|
+
end
|
46
|
+
end
|
@@ -1,21 +1,144 @@
|
|
1
|
-
require '
|
2
|
-
require '
|
1
|
+
require 'timeout'
|
2
|
+
require 'cgi'
|
3
|
+
require 'prevoty'
|
4
|
+
require 'prevoty/content_payload'
|
3
5
|
|
4
6
|
module Rack
|
5
7
|
module Prevoty
|
6
8
|
class ContentMiddleware
|
7
9
|
def initialize(app, opts)
|
8
|
-
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
|
13
|
-
|
10
|
+
@app = app
|
11
|
+
@base = opts[:api_base] ||= 'https://api.prevoty.com'
|
12
|
+
@client = ::Prevoty::Client.new(opts[:api_key], @base)
|
13
|
+
@policy_key = opts[:policy_key] ||= ''
|
14
|
+
@mode = opts[:mode] ||= 'monitor'
|
15
|
+
@log_verbosity = opts[:log_verbosity] ||= 'incident'
|
16
|
+
@paths = opts[:paths] ||= ['/']
|
17
|
+
@blacklist = opts[:blacklist] ||= []
|
18
|
+
@traffic_percentage = opts[:traffic_percentage] ||= 100
|
19
|
+
if @mode === 'monitor'
|
20
|
+
@monitor = ::Prevoty::ContentMonitor.new(@client, opts)
|
14
21
|
end
|
15
22
|
end
|
16
23
|
|
17
24
|
def call(env)
|
18
|
-
|
25
|
+
req = Rack::Request.new(env)
|
26
|
+
|
27
|
+
# Thread local storage for communicating between content and query
|
28
|
+
Thread.current[:request_storage] = {}
|
29
|
+
|
30
|
+
# only wrapping this in a begin so we can use ensure to clean out
|
31
|
+
# thread storage
|
32
|
+
begin
|
33
|
+
if rand(100) > @traffic_percentage
|
34
|
+
Thread.current[:request_storage][:skip_processing] = true
|
35
|
+
return @app.call(env)
|
36
|
+
end
|
37
|
+
|
38
|
+
# passthru if not listed in paths
|
39
|
+
return @app.call(env) if @paths.detect {|p| req.path.start_with?(p)}.nil?
|
40
|
+
|
41
|
+
# passthru if blacklisted
|
42
|
+
return @app.call(env) unless @blacklist.detect {|p| req.path.start_with?(p)}.nil?
|
43
|
+
|
44
|
+
# TODO: implement support for multipart. The Rack multipart
|
45
|
+
# implementation doesn't support parsing and re-creating the
|
46
|
+
# mutlipart data so a custom implementation needs to be written
|
47
|
+
return @app.call(env) if req.media_type === 'multipart/form-data'
|
48
|
+
|
49
|
+
unless env['QUERY_STRING'].empty?
|
50
|
+
if @mode === 'protect'
|
51
|
+
begin
|
52
|
+
Timeout::timeout(@timeout) do
|
53
|
+
resp = nil
|
54
|
+
if defined? ActiveSupport::Notifications
|
55
|
+
ActiveSupport::Notifications.instrument('prevoty:content:protect') do |payload|
|
56
|
+
resp = payload[:response] = @client.bulk_filter(body, @policy_key)
|
57
|
+
end
|
58
|
+
end
|
59
|
+
env['QUERY_STRING'] = resp.output
|
60
|
+
result = self.class.build_result(@mode, req, querystring, resp)
|
61
|
+
if resp.statistics.is_significant? || @log_verbosity === 'all'
|
62
|
+
::Prevoty::LOGGER << result.to_json + "\n"
|
63
|
+
end
|
64
|
+
end
|
65
|
+
rescue Exception => e
|
66
|
+
env['QUERY_STRING'] = escape_query(CGI::parse(env['QUERY_STRING']))
|
67
|
+
Rails.logger.warn e.message
|
68
|
+
end
|
69
|
+
else
|
70
|
+
@monitor.process({mode: @mode, input: env['QUERY_STRING'], request: req})
|
71
|
+
end
|
72
|
+
end
|
73
|
+
|
74
|
+
if ['POST', 'PUT', 'PATCH'].member?(req.request_method)
|
75
|
+
body = URI.unescape(req.body.read.encode('utf-8'))
|
76
|
+
unless body.empty?
|
77
|
+
if @mode === 'protect'
|
78
|
+
begin
|
79
|
+
resp = nil
|
80
|
+
Timeout::timeout(@timeout) do
|
81
|
+
if defined? ActiveSupport::Notifications
|
82
|
+
ActiveSupport::Notifications.instrument('prevoty:content:protect') do |payload|
|
83
|
+
resp = payload[:response] = @client.bulk_filter(body, @policy_key)
|
84
|
+
end
|
85
|
+
end
|
86
|
+
env['rack.input'] = StringIO.new(resp.output)
|
87
|
+
result = self.class.build_result(@mode, req, body, resp)
|
88
|
+
if resp.statistics.is_significant? || @log_verbosity === 'all'
|
89
|
+
::Prevoty::LOGGER << result.to_json + "\n"
|
90
|
+
end
|
91
|
+
end
|
92
|
+
rescue Exception => e
|
93
|
+
env['rack.input'] = StringIO.new(escape_query(CGI::parse(body)))
|
94
|
+
Rails.logger.warn e.message
|
95
|
+
end
|
96
|
+
else
|
97
|
+
@monitor.process({mode: @mode, input: body, request: req})
|
98
|
+
end
|
99
|
+
end
|
100
|
+
end
|
101
|
+
|
102
|
+
@app.call(env)
|
103
|
+
ensure
|
104
|
+
Thread.current[:request_storage] = {}
|
105
|
+
end
|
106
|
+
end
|
107
|
+
|
108
|
+
def self.build_result(mode, request, input, result)
|
109
|
+
data = {
|
110
|
+
product: 'content',
|
111
|
+
mode: mode,
|
112
|
+
version: '1',
|
113
|
+
input: input,
|
114
|
+
timestamp: Time.now.utc.strftime('%b %d %Y %H:%M:%S %Z'),
|
115
|
+
request_url: request.path,
|
116
|
+
session_id: request.session["session_id"],
|
117
|
+
cookies: request.cookies,
|
118
|
+
http_method: request.request_method,
|
119
|
+
src_ip: request.ip,
|
120
|
+
dest_host: request.host,
|
121
|
+
dest_port: request.port
|
122
|
+
}
|
123
|
+
|
124
|
+
# these are hacks due to differences between protect and monitor
|
125
|
+
if mode === 'protect'
|
126
|
+
data[:statistics] = result.statistics
|
127
|
+
data[:output] = CGI::unescape(result.output)
|
128
|
+
else
|
129
|
+
data[:statistics] = result
|
130
|
+
end
|
131
|
+
|
132
|
+
::Prevoty::ContentPayload.new(data)
|
133
|
+
end
|
134
|
+
|
135
|
+
protected
|
136
|
+
def escape_query(params)
|
137
|
+
params.map do |name,values|
|
138
|
+
values.map do |value|
|
139
|
+
"#{CGI.escape name}=#{CGI.escape CGI.escapeHTML value}"
|
140
|
+
end
|
141
|
+
end.flatten.join("&")
|
19
142
|
end
|
20
143
|
end
|
21
144
|
end
|
data/prevoty-rails.gemspec
CHANGED
@@ -11,7 +11,7 @@ Gem::Specification.new do |spec|
|
|
11
11
|
spec.summary = %q{Prevoty rails plugin.}
|
12
12
|
spec.description = %q{Plugin to add dropin support for Prevoty's content filter and SQL analysis.}
|
13
13
|
spec.homepage = "https://www.prevoty.com"
|
14
|
-
spec.license = "
|
14
|
+
spec.license = "Apache-2.0"
|
15
15
|
|
16
16
|
spec.files = `git ls-files -z`.split("\x0")
|
17
17
|
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
|
metadata
CHANGED
@@ -1,14 +1,14 @@
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
2
2
|
name: prevoty-rails
|
3
3
|
version: !ruby/object:Gem::Version
|
4
|
-
version: 0.
|
4
|
+
version: 1.0.0
|
5
5
|
platform: ruby
|
6
6
|
authors:
|
7
7
|
- Joe Rozner
|
8
8
|
autorequire:
|
9
9
|
bindir: bin
|
10
10
|
cert_chain: []
|
11
|
-
date: 2016-
|
11
|
+
date: 2016-10-03 00:00:00.000000000 Z
|
12
12
|
dependencies:
|
13
13
|
- !ruby/object:Gem::Dependency
|
14
14
|
name: prevoty
|
@@ -103,13 +103,12 @@ extra_rdoc_files: []
|
|
103
103
|
files:
|
104
104
|
- Gemfile
|
105
105
|
- Gemfile.lock
|
106
|
-
- LICENSE
|
106
|
+
- LICENSE
|
107
107
|
- README.md
|
108
108
|
- Rakefile
|
109
|
-
- lib/action_controller/request_forgery_protection.rb
|
110
109
|
- lib/generators/prevoty/rails/USAGE
|
111
110
|
- lib/generators/prevoty/rails/install_generator.rb
|
112
|
-
- lib/generators/prevoty/rails/templates/prevoty_rails.
|
111
|
+
- lib/generators/prevoty/rails/templates/prevoty_rails.yml
|
113
112
|
- lib/prevoty-rails.rb
|
114
113
|
- lib/prevoty/adapters.rb
|
115
114
|
- lib/prevoty/build_query_result.rb
|
@@ -118,18 +117,17 @@ files:
|
|
118
117
|
- lib/prevoty/logger.rb
|
119
118
|
- lib/prevoty/monitor.rb
|
120
119
|
- lib/prevoty/query_failure.rb
|
120
|
+
- lib/prevoty/query_handler.rb
|
121
121
|
- lib/prevoty/query_monitor.rb
|
122
122
|
- lib/prevoty/query_payload.rb
|
123
123
|
- lib/prevoty/query_violation.rb
|
124
124
|
- lib/prevoty/rails/version.rb
|
125
|
+
- lib/prevoty/railtie.rb
|
125
126
|
- lib/rack/content_middleware.rb
|
126
|
-
- lib/rack/interceptor.rb
|
127
|
-
- lib/rack/monitor_interceptor.rb
|
128
|
-
- lib/rack/protect_interceptor.rb
|
129
127
|
- prevoty-rails.gemspec
|
130
128
|
homepage: https://www.prevoty.com
|
131
129
|
licenses:
|
132
|
-
-
|
130
|
+
- Apache-2.0
|
133
131
|
metadata: {}
|
134
132
|
post_install_message:
|
135
133
|
rdoc_options: []
|
data/LICENSE.txt
DELETED
@@ -1,22 +0,0 @@
|
|
1
|
-
Copyright (c) 2014 Prevoty
|
2
|
-
|
3
|
-
MIT License
|
4
|
-
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining
|
6
|
-
a copy of this software and associated documentation files (the
|
7
|
-
"Software"), to deal in the Software without restriction, including
|
8
|
-
without limitation the rights to use, copy, modify, merge, publish,
|
9
|
-
distribute, sublicense, and/or sell copies of the Software, and to
|
10
|
-
permit persons to whom the Software is furnished to do so, subject to
|
11
|
-
the following conditions:
|
12
|
-
|
13
|
-
The above copyright notice and this permission notice shall be
|
14
|
-
included in all copies or substantial portions of the Software.
|
15
|
-
|
16
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
17
|
-
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
18
|
-
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
19
|
-
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
20
|
-
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
21
|
-
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
22
|
-
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
@@ -1,36 +0,0 @@
|
|
1
|
-
module ActionController
|
2
|
-
module RequestForgeryProtection
|
3
|
-
# NOTE: This implementation currently doesn't support the BREACH
|
4
|
-
# mitigation that Rails introduces with masking. The Prevoty
|
5
|
-
# implementation possibly makes this unnecessary because it scopes CSRF
|
6
|
-
# tokens by action and not just the session id. This allows for each form
|
7
|
-
# to have a unique token and can be re-generated for each request. However
|
8
|
-
# because of how the plugin works there isn't a clear way to set the action
|
9
|
-
# so all forms will share a token. We should either introduce masking or
|
10
|
-
# find a solution to setting the action correctly.
|
11
|
-
protected
|
12
|
-
def form_authenticity_token
|
13
|
-
begin
|
14
|
-
resp = PREVOTY_CLIENT.generate_timed_token(session[:session_id], "action", 86400)
|
15
|
-
session[:_csrf_token] = resp.token
|
16
|
-
rescue Exception => e
|
17
|
-
Rails.logger.debug e.message
|
18
|
-
end
|
19
|
-
end
|
20
|
-
|
21
|
-
def verified_request?
|
22
|
-
return true if !protect_against_forgery? || request.get? || request.head?
|
23
|
-
begin
|
24
|
-
resp = PREVOTY_CLIENT.validate_timed_token(session[:session_id], "action", session[:_csrf_token])
|
25
|
-
return true if resp.valid
|
26
|
-
resp = PREVOTY_CLIENT.validate_timed_token(session[:session_id], "action", request.headers['X-CSRF-Token'])
|
27
|
-
return true if resp.valid
|
28
|
-
rescue
|
29
|
-
Rails.logger.debug e.message
|
30
|
-
return false
|
31
|
-
end
|
32
|
-
|
33
|
-
false
|
34
|
-
end
|
35
|
-
end
|
36
|
-
end
|
@@ -1,86 +0,0 @@
|
|
1
|
-
require 'prevoty/query_violation'
|
2
|
-
require 'prevoty/query_failure'
|
3
|
-
require 'prevoty/query_payload'
|
4
|
-
require 'prevoty/build_query_result'
|
5
|
-
require 'prevoty/logger'
|
6
|
-
|
7
|
-
options = {
|
8
|
-
api_base: 'https://api.prevoty.com',
|
9
|
-
api_key: '',
|
10
|
-
mode: 'monitor',
|
11
|
-
minimal_logging: false,
|
12
|
-
log_destination: 'log',
|
13
|
-
# configuration_key: '', # uncomment for protect
|
14
|
-
reporting_milliseconds: 10000,
|
15
|
-
reporting_count: 50,
|
16
|
-
db_vendor: '', # unused for protect
|
17
|
-
db_version: '', # unused for protect
|
18
|
-
db_name: '', # unused for protect
|
19
|
-
violation_mode: 'block',
|
20
|
-
failure_mode: 'continue',
|
21
|
-
before_callback: ->() {}, # fired before a query is analyzed
|
22
|
-
after_callback: ->() {}, # fired after a query is analyzed
|
23
|
-
error_callback: ->() {} # fired after an error
|
24
|
-
}
|
25
|
-
|
26
|
-
case options[:mode]
|
27
|
-
when 'monitor'
|
28
|
-
client = ::Prevoty::Client.new(options[:api_key], options[:api_base])
|
29
|
-
QUERY_MONITOR = ::Prevoty::QueryMonitor.new client, options
|
30
|
-
when 'protect'
|
31
|
-
PREVOTY_CLIENT = ::Prevoty::Client.new(options[:api_key], options[:api_base])
|
32
|
-
end
|
33
|
-
|
34
|
-
query_handler = ->(name, start, finish, id, payload) do
|
35
|
-
include Prevoty::BuildQueryResult
|
36
|
-
|
37
|
-
unless payload[:name] =~ /SQL|Load/
|
38
|
-
return
|
39
|
-
end
|
40
|
-
|
41
|
-
case options[:mode]
|
42
|
-
when 'monitor'
|
43
|
-
package = {vendor: options[:db_vendor], database: options[:db_name], version: options[:db_version], query: payload[:sql]}
|
44
|
-
QUERY_MONITOR.process(package)
|
45
|
-
when 'protect'
|
46
|
-
begin
|
47
|
-
options[:before_callback].call(payload[:sql]) if options[:log_destination] === 'callback' and options[:before_callback].respond_to? :call
|
48
|
-
res = PREVOTY_CLIENT.analyze_query(payload[:sql], options[:configuration_key])
|
49
|
-
if res.processed and not res.compliant
|
50
|
-
case options[:log_destination]
|
51
|
-
when 'log'
|
52
|
-
::Prevoty::LOGGER << build_result(options[:mode], payload[:sql], res).to_json + "\n"
|
53
|
-
when 'callback'
|
54
|
-
options[:after_callback].call(build_result(options[:mode], payload[:sql], res).to_json) if options[:after_callback].respond_to? :call
|
55
|
-
end
|
56
|
-
raise ::Prevoty::QueryViolation.new if options[:violation_mode] === 'block'
|
57
|
-
elsif res.processed and res.compliant
|
58
|
-
case options[:log_destination]
|
59
|
-
when 'log'
|
60
|
-
::Prevoty::LOGGER << build_result(options[:mode], payload[:sql], res).to_json + "\n"
|
61
|
-
when 'callback'
|
62
|
-
options[:after_callback].call(build_result(options[:mode], payload[:sql], res).to_json) if options[:after_callback].respond_to? :call
|
63
|
-
end
|
64
|
-
elsif not res.processed and not res.compliant
|
65
|
-
raise ::Prevoty::QueryFailure.new
|
66
|
-
end
|
67
|
-
rescue ::Prevoty::QueryViolation => e
|
68
|
-
# need to catch and rethrow to catch other exceptions
|
69
|
-
raise e
|
70
|
-
rescue ::Prevoty::QueryFailure => e
|
71
|
-
# need to catch and rethrow to catch other exceptions
|
72
|
-
raise e
|
73
|
-
rescue Exception => e
|
74
|
-
case options[:log_destination]
|
75
|
-
when 'log'
|
76
|
-
Rails.logger.error e.message
|
77
|
-
when 'callback'
|
78
|
-
options[:error_callback].call(e) if options[:error_callback].response_to_? :call
|
79
|
-
end
|
80
|
-
|
81
|
-
raise e if options[:failure_mode] === 'block'
|
82
|
-
end
|
83
|
-
end
|
84
|
-
end
|
85
|
-
|
86
|
-
ActiveSupport::Notifications.subscribe 'sql.active_record', query_handler
|
data/lib/rack/interceptor.rb
DELETED
@@ -1,61 +0,0 @@
|
|
1
|
-
require 'prevoty'
|
2
|
-
require 'prevoty/content_payload'
|
3
|
-
|
4
|
-
module Rack
|
5
|
-
module Prevoty
|
6
|
-
class Interceptor
|
7
|
-
def initialize(app, opts)
|
8
|
-
@app = app
|
9
|
-
@base = opts[:api_base] ||= 'https://api.prevoty.com'
|
10
|
-
@client = ::Prevoty::Client.new(opts[:api_key], @base)
|
11
|
-
@configuration_key = opts[:configuration_key]
|
12
|
-
@mode = opts[:mode] ||= 'monitor'
|
13
|
-
@callback = opts[:callback] ||= nil
|
14
|
-
@minimal_logging = opts[:minimal_logging] ||= false
|
15
|
-
@log_destination = opts[:log_destination] ||= 'log'
|
16
|
-
@paths = opts[:paths] ||= ['/']
|
17
|
-
@blacklist = opts[:blacklist] ||= []
|
18
|
-
end
|
19
|
-
|
20
|
-
def call(env)
|
21
|
-
raise 'this is an abstract class...instantiate one of the child rack middlewares'
|
22
|
-
end
|
23
|
-
|
24
|
-
def self.build_result(mode, request, input, result)
|
25
|
-
data = {
|
26
|
-
product: 'content',
|
27
|
-
mode: mode,
|
28
|
-
version: '1',
|
29
|
-
input: input,
|
30
|
-
timestamp: Time.now.utc.strftime('%b %d %Y %H:%M:%S %Z'),
|
31
|
-
request_url: request.path,
|
32
|
-
session_id: request.session["session_id"],
|
33
|
-
cookies: request.cookies,
|
34
|
-
http_method: request.request_method,
|
35
|
-
src_ip: request.ip,
|
36
|
-
dest_host: request.host,
|
37
|
-
dest_port: request.port
|
38
|
-
}
|
39
|
-
|
40
|
-
# these are hacks due to differences between protect and monitor
|
41
|
-
if mode === 'protect'
|
42
|
-
data[:statistics] = result.statistics
|
43
|
-
data[:output] = CGI::unescape(result.output)
|
44
|
-
else
|
45
|
-
data[:statistics] = result
|
46
|
-
end
|
47
|
-
|
48
|
-
::Prevoty::ContentPayload.new(data)
|
49
|
-
end
|
50
|
-
|
51
|
-
protected
|
52
|
-
def escape_query(params)
|
53
|
-
params.map do |name,values|
|
54
|
-
values.map do |value|
|
55
|
-
"#{CGI.escape name}=#{CGI.escape CGI.escapeHTML value}"
|
56
|
-
end
|
57
|
-
end.flatten.join("&")
|
58
|
-
end
|
59
|
-
end
|
60
|
-
end
|
61
|
-
end
|
@@ -1,51 +0,0 @@
|
|
1
|
-
require 'rack/interceptor'
|
2
|
-
|
3
|
-
module Rack
|
4
|
-
module Prevoty
|
5
|
-
class MonitorInterceptor < Interceptor
|
6
|
-
def initialize(app, opts)
|
7
|
-
super(app, opts)
|
8
|
-
|
9
|
-
@monitor = ::Prevoty::ContentMonitor.new(@client, opts)
|
10
|
-
end
|
11
|
-
|
12
|
-
def call(env)
|
13
|
-
req = Rack::Request.new(env)
|
14
|
-
|
15
|
-
# passthru if not listed in paths
|
16
|
-
return @app.call(env) if @paths.detect {|p| req.path.start_with?(p)}.nil?
|
17
|
-
|
18
|
-
# passthru if blacklisted
|
19
|
-
return @app.call(env) unless @blacklist.detect {|p| req.path.start_with?(p)}.nil?
|
20
|
-
|
21
|
-
case req.request_method
|
22
|
-
when "GET", "DELETE"
|
23
|
-
unless env['QUERY_STRING'] === ''
|
24
|
-
querystring = URI.unescape(env['QUERY_STRING'])
|
25
|
-
@monitor.process({mode: @mode, input: querystring, request: req})
|
26
|
-
end
|
27
|
-
when "POST", "PUT"
|
28
|
-
if req.media_type === 'multipart/form-data'
|
29
|
-
# TODO: implement support for multipart. The Rack multipart
|
30
|
-
# implementation doesn't support parsing and re-creating the
|
31
|
-
# mutlipart data so a custom implementation needs to be written
|
32
|
-
else
|
33
|
-
body = URI.unescape(req.body.read.encode('utf-8'))
|
34
|
-
unless body === ''
|
35
|
-
@monitor.process({mode: @mode, input: body, request: req})
|
36
|
-
end
|
37
|
-
end
|
38
|
-
|
39
|
-
# clean any GET data passed
|
40
|
-
unless env['QUERY_STRING'] === ''
|
41
|
-
querystring = URI.unescape(env['QUERY_STRING'])
|
42
|
-
@monitor.process({mode: @mode, input: querystring, request: req})
|
43
|
-
end
|
44
|
-
else Rails.logger.warn "unknown method #{req.request_method}"
|
45
|
-
end
|
46
|
-
|
47
|
-
@app.call(env)
|
48
|
-
end
|
49
|
-
end
|
50
|
-
end
|
51
|
-
end
|
@@ -1,94 +0,0 @@
|
|
1
|
-
require 'timeout'
|
2
|
-
require 'cgi'
|
3
|
-
require 'rack/interceptor'
|
4
|
-
|
5
|
-
module Rack
|
6
|
-
module Prevoty
|
7
|
-
class ProtectInterceptor < Interceptor
|
8
|
-
def initialize(app, opts)
|
9
|
-
super(app, opts)
|
10
|
-
end
|
11
|
-
|
12
|
-
def call(env)
|
13
|
-
req = Rack::Request.new(env)
|
14
|
-
|
15
|
-
# passthru if not listed in paths
|
16
|
-
return @app.call(env) if @paths.detect {|p| req.path.start_with?(p)}.nil?
|
17
|
-
|
18
|
-
# passthru if blacklisted
|
19
|
-
return @app.call(env) unless @blacklist.detect {|p| req.path.start_with?(p)}.nil?
|
20
|
-
|
21
|
-
case req.request_method
|
22
|
-
when "GET", "DELETE"
|
23
|
-
unless env['QUERY_STRING'] === ''
|
24
|
-
querystring = env['QUERY_STRING']
|
25
|
-
begin
|
26
|
-
Timeout::timeout(@timeout) do
|
27
|
-
resp = @client.bulk_filter(querystring, @configuration_key)
|
28
|
-
env['QUERY_STRING'] = resp.output
|
29
|
-
case @log_destination
|
30
|
-
when 'log'
|
31
|
-
::Prevoty::LOGGER << self.class.build_result(@mode, req, querystring, resp).to_json + "\n" if resp.statistics.javascript_attributes > 0 || resp.statistics.javascript_protocols > 0 || resp.statistics.javascript_tags > 0
|
32
|
-
when 'callback'
|
33
|
-
@callback.call(self.class.build_result(@mode, req, querystring, resp).to_json) if !@callback.nil? && (resp.statistics.javascript_attributes > 0 || resp.statistics.javascript_protocols > 0 || resp.statistics.javascript_tags > 0)
|
34
|
-
end
|
35
|
-
end
|
36
|
-
rescue Exception => e
|
37
|
-
env['QUERY_STRING'] = escape_query(CGI::parse(querystring))
|
38
|
-
Rails.logger.warn e.message
|
39
|
-
end
|
40
|
-
end
|
41
|
-
when "POST", "PUT"
|
42
|
-
if req.media_type === 'multipart/form-data'
|
43
|
-
# TODO: implement support for multipart. The Rack multipart
|
44
|
-
# implementation doesn't support parsing and re-creating the
|
45
|
-
# multipart data so a custom implementation needs to be written
|
46
|
-
else
|
47
|
-
# First, clean the request body
|
48
|
-
body = req.body.read.encode('utf-8')
|
49
|
-
unless body === ''
|
50
|
-
begin
|
51
|
-
Timeout::timeout(@timeout) do
|
52
|
-
resp = @client.bulk_filter(body, @configuration_key)
|
53
|
-
env['rack.input'] = StringIO.new(resp.output)
|
54
|
-
case @log_destination
|
55
|
-
when 'log'
|
56
|
-
::Prevoty::LOGGER << self.class.build_result(@mode, req, body, resp).to_json + "\n" if resp.statistics.javascript_attributes > 0 || resp.statistics.javascript_protocols > 0 || resp.statistics.javascript_tags > 0
|
57
|
-
when 'callback'
|
58
|
-
@callback.call(self.class.build_result(@mode, req, body, resp).to_json) if !@callback.nil? && (resp.statistics.javascript_attributes > 0 || resp.statistics.javascript_protocols > 0 || resp.statistics.javascript_tags > 0)
|
59
|
-
end
|
60
|
-
end
|
61
|
-
rescue Exception => e
|
62
|
-
env['rack.input'] = StringIO.new(escape_query(CGI::parse(body)))
|
63
|
-
Rails.logger.warn e.message
|
64
|
-
end
|
65
|
-
end
|
66
|
-
end
|
67
|
-
|
68
|
-
# Second, clean any data passed in the query string
|
69
|
-
unless env['QUERY_STRING'] === ''
|
70
|
-
querystring = env['QUERY_STRING']
|
71
|
-
begin
|
72
|
-
Timeout::timeout(@timeout) do
|
73
|
-
resp = @client.bulk_filter(querystring, @configuration_key)
|
74
|
-
env['QUERY_STRING'] = resp.output
|
75
|
-
case @log_destination
|
76
|
-
when 'log'
|
77
|
-
::Prevoty::LOGGER << self.class.build_result(@mode, req, querystring, resp).to_json + "\n" if resp.statistics.javascript_attributes > 0 || resp.statistics.javascript_protocols > 0 || resp.statistics.javascript_tags > 0
|
78
|
-
when 'callback'
|
79
|
-
@callback.call(self.class.build_result(@mode, req, querystring, resp).to_json) if !@callback.nil? && (resp.statistics.javascript_attributes > 0 || resp.statistics.javascript_protocols > 0 || resp.statistics.javascript_tags > 0)
|
80
|
-
end
|
81
|
-
end
|
82
|
-
rescue Exception => e
|
83
|
-
env['QUERY_STRING'] = escape_query(CGI::parse(querystring))
|
84
|
-
Rails.logger.warn e.message
|
85
|
-
end
|
86
|
-
end
|
87
|
-
else Rails.logger.warn "unknown method #{req.request_method}"
|
88
|
-
end
|
89
|
-
|
90
|
-
@app.call(env)
|
91
|
-
end
|
92
|
-
end
|
93
|
-
end
|
94
|
-
end
|