libddwaf 1.24.1.0.0-x86_64-linux-gnu

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d4bae579c5589821f0f9b3cf6fd3188d3bf3a94ed8b74e8506044f8a8cee036a
4
+ data.tar.gz: 6375adaf609de81c3426317746cb3f2a091efe304184fa6a7d4b0db232f8040c
5
+ SHA512:
6
+ metadata.gz: 6b2e561c0882b1780093aaf82744f3f7a4ca660a2f9fd896e76eee485384abf5fc10e4f52cef1cc464f8f0eb723fcad0b1b1e002a92d263537ec44a454e5de05
7
+ data.tar.gz: 0e7830acd2e9ec619f122f7baa19c7fbd7fa702770b0196b2029bc6bf3603e2d3fae49d7f07510a27d4754c7a7c37eb443a28e33441900c0cb4ef4651717c9b0
data/CHANGELOG.md ADDED
@@ -0,0 +1,153 @@
1
+ # Unreleased v1.23.0.0.0
2
+
3
+ ## Added
4
+
5
+ - Add `HandleBuilder` class for managing libddwaf configuration and building WAF handles
6
+ - Add Error classes:
7
+ - `LibDDWAFError` for libddwaf errors
8
+ - `ConversionError` for conversion errors
9
+ - `InstanceFinalizedError` that is raised when attempting to run methods on finalized instances
10
+
11
+ ## Changed
12
+
13
+ - Change `Handle` instantiation - now it should be done using `HandleBuilder#build_handle` method
14
+ - Change `Context` instantiation - now is should be done using `Handle#build_context` method
15
+ - Change configuration of Limits and obfuscation - it is now done when initializing `HandleBuilder`
16
+ - Change `Context#run` to return a `Result` object instead of an tuple with code and result
17
+
18
+ ## Removed
19
+
20
+ - Remove `WAF::Handle#merge` method - the configuration is now handled by `HandleBuilder`
21
+
22
+ # 2025-02-20 v.1.18.0.0.1
23
+
24
+ - Fixed memory-leak in `Datadog::AppSec::WAF::Context#run` when non-empty ephemeral data passed
25
+
26
+ # 2024-10-29 v.1.15.0.0.0
27
+
28
+ - Update to libddwaf 1.15.0
29
+ - Changed `Datadog::AppSec::WAF::Context#run` interface to accommodate ephemeral data ([Breaking change](https://github.com/DataDog/libddwaf/blob/master/CHANGELOG.md#v1150-unstable))
30
+
31
+ # 2023-09-11 v.1.14.0.0.0
32
+
33
+ - Update to libddwaf 1.14.0
34
+ - Add support for `Float` and `Nil` scalar values when converting from ruby to WAF Object and vice versa.
35
+
36
+ # 2023-08-29 v.1.11.0.0.0
37
+
38
+ - Update to libddwaf 1.11.0
39
+ - Changed `Datadog::AppSec::WAF::Handle#ruleset_info` to `Datadog::AppSec::WAF::Handle#diagnostics`. (Breaking change)
40
+ The schema of the diagnostics variable can be found [here](https://github.com/DataDog/libddwaf/blob/master/schema/diagnostics.json)
41
+ - Changed `Datadog::AppSec::WAF::Result#data` to `Datadog::AppSec::WAF::Result#events`. (Breaking change)
42
+ The schema of the events variable can be found [here](https://github.com/DataDog/libddwaf/blob/master/schema/events.json)
43
+
44
+ # 2023-08-28 v.1.10.0.0.0
45
+
46
+ - Update to libddwaf 1.10.0
47
+
48
+ # 2023-06-13 v.1.9.0.0.1
49
+
50
+ - Handle invalid encoding
51
+ - Ensure strings passed to libddwaf are not clipped inside a code point
52
+ - Ensure strings passed to libddwaf are UTF-8
53
+
54
+ # 2023-05-17 v1.9.0.0.0
55
+
56
+ - Update to libddwaf 1.9.0
57
+ - Support [`custom_rules`](https://github.com/DataDog/libddwaf/pull/154)
58
+
59
+ # 2023-03-03 v1.8.2.0.0
60
+
61
+ - Update to libddwaf 1.8.2
62
+ - Added Waf::Handle#merge method
63
+ - Remove Waf::Handle#update_rule_data and Waf::Handle#toggle_rules methods
64
+ - Remove WAF::LibDDWAF.ddwaf_required_rule_data_ids method
65
+
66
+ # 2023-02-03 v1.7.0.0.0
67
+
68
+ - Update to libddwaf 1.7.0
69
+
70
+ # 2023-02-03 v1.6.2.0.0
71
+
72
+ - Update to libddwaf 1.6.2
73
+ - Add specs for the getter functions
74
+
75
+ # 2023-02-01 v1.5.1.0.1
76
+
77
+ - Fix incorrect size in input string limit
78
+ - Fix object freeing on `update_rule_data` and `toggle_rules`
79
+
80
+ # 2022-10-04 v1.5.1.0.0
81
+
82
+ - Update to libddwaf 1.5.1
83
+ - Add live rule data update API
84
+ - Add live rule toggle API
85
+ - Add libddwaf boolean type support
86
+ - Add Ruby to libddwaf object conversion limits
87
+ - Add Ruby to libddwaf object converter optional coercion of scalars to string
88
+ - Add static type checking via RBS+Steep
89
+ - Change version to return a string
90
+ - Change free function to be passed as config instead of context init argument
91
+ - Change result to include action list
92
+ - Change return code from action to status
93
+ - Change handle and context freeing model from GC-based to explicit
94
+ - Fix double-free upon finalization of retained C objects
95
+ - Fix context crash by retaining necessary C objects
96
+
97
+ # 2022-05-20 v1.3.0.2.0
98
+
99
+ - Fix multibyte string handling
100
+ - Support JRuby
101
+
102
+ # 2022-04-29 v1.3.0.1.0
103
+
104
+ Promotion of v1.3.0.1.0.beta1 to stable
105
+
106
+ # 2022-04-25 v1.3.0.1.0.beta1
107
+
108
+ - Add obfuscator configuration
109
+ - Add nested object limit configuration
110
+ - Add report ruleset information
111
+
112
+ # 2022-04-29 v1.3.0.0.0
113
+
114
+ - Promote v1.3.0.0.0.beta1 to stable
115
+
116
+ # 2022-04-20 v1.3.0.0.0.beta1
117
+
118
+ - Update to libddwaf 1.3.0
119
+
120
+ # 2022-03-18 v1.2.1.0.0.beta1
121
+
122
+ - Update to libddwaf 1.2.1
123
+ - Fix incorrect types for a few binding functions
124
+
125
+ # 2022-03-04 v1.0.14.2.1.beta1
126
+
127
+ - Fix incorrect return code
128
+ - Fix passing nil in libddwaf object containers
129
+
130
+ # 2022-02-07 v1.0.14.2.0.beta1
131
+
132
+ - Change Datadog::Security to Datadog::AppSec
133
+
134
+ # 2022-02-01 v1.0.14.1.0.beta2
135
+
136
+ - Add support for Ruby 3.1
137
+
138
+ # 2021-12-14 v1.0.14.1.0.beta1
139
+
140
+ - Fix sequential runs on a single context by retaining C input data objects
141
+
142
+ # 2021-11-24 v1.0.14.0.0.beta1
143
+
144
+ - Update to libddwaf 1.0.14
145
+
146
+ # 2021-11-24 v1.0.13.0.0.beta1
147
+
148
+ - Add ruby platform fallback for unsupported platforms
149
+ - Update to libddwaf 1.0.13
150
+
151
+ # 2021-10-13 v1.0.12.0.0.beta1
152
+
153
+ - Initial release
data/LICENSE ADDED
@@ -0,0 +1,6 @@
1
+ ## License
2
+
3
+ This work is dual-licensed under Apache 2.0 or BSD3.
4
+ You may select, at your option, one of the above-listed licenses.
5
+
6
+ `SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause`
@@ -0,0 +1,2 @@
1
+ Component,Origin,License,Copyright
2
+ core,https://github.com/ffi/ffi,BSD-3-Clause,"Copyright (c) 2008-2016, Ruby FFI project contributors"
data/LICENSE.Apache ADDED
@@ -0,0 +1,200 @@
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 2021 Datadog, Inc.
190
+ Licensed under the Apache License, Version 2.0 (the "License");
191
+ you may not use this file except in compliance with the License.
192
+ You may obtain a copy of the License at
193
+
194
+ http://www.apache.org/licenses/LICENSE-2.0
195
+
196
+ Unless required by applicable law or agreed to in writing, software
197
+ distributed under the License is distributed on an "AS IS" BASIS,
198
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
199
+ See the License for the specific language governing permissions and
200
+ limitations under the License.
data/LICENSE.BSD3 ADDED
@@ -0,0 +1,24 @@
1
+ Copyright (c) 2021, Datadog <info@datadoghq.com>
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+ * Redistributions of source code must retain the above copyright
7
+ notice, this list of conditions and the following disclaimer.
8
+ * Redistributions in binary form must reproduce the above copyright
9
+ notice, this list of conditions and the following disclaimer in the
10
+ documentation and/or other materials provided with the distribution.
11
+ * Neither the name of Datadog nor the
12
+ names of its contributors may be used to endorse or promote products
13
+ derived from this software without specific prior written permission.
14
+
15
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
16
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18
+ DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
19
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
data/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Datadog libddwaf-rb
2
+ Copyright 2021-Present Datadog, Inc.
3
+
4
+ This product includes software developed at Datadog, Inc. (https://www.datadoghq.com/).
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Datadog
4
+ module AppSec
5
+ module WAF
6
+ # Ruby representation of the ddwaf_context in libddwaf
7
+ # See https://github.com/DataDog/libddwaf/blob/10e3a1dfc7bc9bb8ab11a09a9f8b6b339eaf3271/BINDING_IMPL_NOTES.md?plain=1#L125-L158
8
+ class Context
9
+ RESULT_CODE = {
10
+ ddwaf_ok: :ok,
11
+ ddwaf_match: :match,
12
+ ddwaf_err_internal: :err_internal,
13
+ ddwaf_err_invalid_object: :err_invalid_object,
14
+ ddwaf_err_invalid_argument: :err_invalid_argument
15
+ }.freeze
16
+
17
+ def initialize(context_ptr)
18
+ @context_ptr = context_ptr
19
+ end
20
+
21
+ # Destroys the WAF context and sets the pointer to nil.
22
+ #
23
+ # The instance becomes unusable after this method is called.
24
+ def finalize!
25
+ context_ptr_to_destroy = @context_ptr
26
+ @context_ptr = nil
27
+
28
+ retained.each do |retained_obj|
29
+ next unless retained_obj.is_a?(LibDDWAF::Object)
30
+
31
+ LibDDWAF.ddwaf_object_free(retained_obj)
32
+ end
33
+
34
+ retained.clear
35
+ LibDDWAF.ddwaf_context_destroy(context_ptr_to_destroy)
36
+ end
37
+
38
+ # Runs the WAF context with the given persistent and ephemeral data.
39
+ #
40
+ # @raise [ConversionError] if the conversion of persistent or ephemeral data fails
41
+ # @raise [LibDDWAFError] if libddwaf could not create the result object
42
+ #
43
+ # @return [Result] the result of the WAF run
44
+ def run(persistent_data, ephemeral_data, timeout = LibDDWAF::DDWAF_RUN_TIMEOUT)
45
+ ensure_pointer_presence!
46
+
47
+ persistent_data_obj = Converter.ruby_to_object(
48
+ persistent_data,
49
+ max_container_size: LibDDWAF::DDWAF_MAX_CONTAINER_SIZE,
50
+ max_container_depth: LibDDWAF::DDWAF_MAX_CONTAINER_DEPTH,
51
+ max_string_length: LibDDWAF::DDWAF_MAX_STRING_LENGTH,
52
+ coerce: false
53
+ )
54
+ if persistent_data_obj.null?
55
+ raise ConversionError, "Could not convert persistent data: #{persistent_data.inspect}"
56
+ end
57
+
58
+ # retain C objects in memory for subsequent calls to run
59
+ retain(persistent_data_obj)
60
+
61
+ ephemeral_data_obj = Converter.ruby_to_object(
62
+ ephemeral_data,
63
+ max_container_size: LibDDWAF::DDWAF_MAX_CONTAINER_SIZE,
64
+ max_container_depth: LibDDWAF::DDWAF_MAX_CONTAINER_DEPTH,
65
+ max_string_length: LibDDWAF::DDWAF_MAX_STRING_LENGTH,
66
+ coerce: false
67
+ )
68
+ if ephemeral_data_obj.null?
69
+ raise ConversionError, "Could not convert ephemeral data: #{ephemeral_data.inspect}"
70
+ end
71
+
72
+ result_obj = LibDDWAF::Result.new
73
+ raise LibDDWAFError, "Could not create result object" if result_obj.null?
74
+
75
+ code = LibDDWAF.ddwaf_run(@context_ptr, persistent_data_obj, ephemeral_data_obj, result_obj, timeout)
76
+
77
+ Result.new(
78
+ RESULT_CODE[code],
79
+ Converter.object_to_ruby(result_obj[:events]),
80
+ result_obj[:total_runtime],
81
+ result_obj[:timeout],
82
+ Converter.object_to_ruby(result_obj[:actions]),
83
+ Converter.object_to_ruby(result_obj[:derivatives])
84
+ )
85
+ ensure
86
+ LibDDWAF.ddwaf_result_free(result_obj) if result_obj
87
+ LibDDWAF.ddwaf_object_free(ephemeral_data_obj) if ephemeral_data_obj
88
+ end
89
+
90
+ private
91
+
92
+ def ensure_pointer_presence!
93
+ return if @context_ptr
94
+
95
+ raise InstanceFinalizedError, "Cannot use WAF context after it has been finalized"
96
+ end
97
+
98
+ def retained
99
+ @retained ||= []
100
+ end
101
+
102
+ def retain(object)
103
+ retained << object
104
+ end
105
+
106
+ def release(object)
107
+ retained.delete(object)
108
+ end
109
+ end
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,169 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Datadog
4
+ module AppSec
5
+ module WAF
6
+ # Module responsible for Ruby-to-C and C-to-Ruby conversions
7
+ module Converter
8
+ module_function
9
+
10
+ # standard:disable Metrics/MethodLength,Metrics/CyclomaticComplexity
11
+ def ruby_to_object(val, max_container_size: nil, max_container_depth: nil, max_string_length: nil, coerce: true)
12
+ case val
13
+ when Array
14
+ obj = LibDDWAF::Object.new
15
+ res = LibDDWAF.ddwaf_object_array(obj)
16
+ raise ConversionError, "Could not convert into object: #{val}" if res.null?
17
+
18
+ max_index = max_container_size - 1 if max_container_size
19
+ unless max_container_depth == 0
20
+ val.each.with_index do |e, i|
21
+ member = Converter.ruby_to_object(
22
+ e,
23
+ max_container_size: max_container_size,
24
+ max_container_depth: (max_container_depth - 1 if max_container_depth),
25
+ max_string_length: max_string_length,
26
+ coerce: coerce
27
+ )
28
+ e_res = LibDDWAF.ddwaf_object_array_add(obj, member)
29
+ raise ConversionError, "Could not add to array object: #{e.inspect}" unless e_res
30
+
31
+ break val if max_index && i >= max_index
32
+ end
33
+ end
34
+
35
+ obj
36
+ when Hash
37
+ obj = LibDDWAF::Object.new
38
+ res = LibDDWAF.ddwaf_object_map(obj)
39
+ raise ConversionError, "Could not convert into object: #{val}" if res.null?
40
+
41
+ max_index = max_container_size - 1 if max_container_size
42
+ unless max_container_depth == 0
43
+ val.each.with_index do |e, i|
44
+ # for Steep, which doesn't handle |(k, v), i|
45
+ k = e[0]
46
+ v = e[1]
47
+
48
+ k = k.to_s[0, max_string_length] if max_string_length
49
+ member = Converter.ruby_to_object(
50
+ v,
51
+ max_container_size: max_container_size,
52
+ max_container_depth: (max_container_depth - 1 if max_container_depth),
53
+ max_string_length: max_string_length,
54
+ coerce: coerce
55
+ )
56
+ kv_res = LibDDWAF.ddwaf_object_map_addl(obj, k.to_s, k.to_s.bytesize, member)
57
+ raise ConversionError, "Could not add to map object: #{k.inspect} => #{v.inspect}" unless kv_res
58
+
59
+ break val if max_index && i >= max_index
60
+ end
61
+ end
62
+
63
+ obj
64
+ when String
65
+ obj = LibDDWAF::Object.new
66
+ encoded_val = val.to_s.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
67
+ val = encoded_val[0, max_string_length] if max_string_length
68
+ str = val.to_s
69
+ res = LibDDWAF.ddwaf_object_stringl(obj, str, str.bytesize)
70
+ raise ConversionError, "Could not convert into object: #{val.inspect}" if res.null?
71
+
72
+ obj
73
+ when Symbol
74
+ obj = LibDDWAF::Object.new
75
+ val = val.to_s[0, max_string_length] if max_string_length
76
+ str = val.to_s
77
+ res = LibDDWAF.ddwaf_object_stringl(obj, str, str.bytesize)
78
+ raise ConversionError, "Could not convert into object: #{val.inspect}" if res.null?
79
+
80
+ obj
81
+ when Integer
82
+ obj = LibDDWAF::Object.new
83
+ res = if coerce
84
+ LibDDWAF.ddwaf_object_string(obj, val.to_s)
85
+ elsif val < 0
86
+ LibDDWAF.ddwaf_object_signed(obj, val)
87
+ else
88
+ LibDDWAF.ddwaf_object_unsigned(obj, val)
89
+ end
90
+ raise ConversionError, "Could not convert into object: #{val.inspect}" if res.null?
91
+
92
+ obj
93
+ when Float
94
+ obj = LibDDWAF::Object.new
95
+ res = if coerce
96
+ LibDDWAF.ddwaf_object_string(obj, val.to_s)
97
+ else
98
+ LibDDWAF.ddwaf_object_float(obj, val)
99
+ end
100
+ raise ConversionError, "Could not convert into object: #{val.inspect}" if res.null?
101
+
102
+ obj
103
+ when TrueClass, FalseClass
104
+ obj = LibDDWAF::Object.new
105
+ res = if coerce
106
+ LibDDWAF.ddwaf_object_string(obj, val.to_s)
107
+ else
108
+ LibDDWAF.ddwaf_object_bool(obj, val)
109
+ end
110
+ raise ConversionError, "Could not convert into object: #{val.inspect}" if res.null?
111
+
112
+ obj
113
+ when NilClass
114
+ obj = LibDDWAF::Object.new
115
+ res = if coerce
116
+ LibDDWAF.ddwaf_object_string(obj, "")
117
+ else
118
+ LibDDWAF.ddwaf_object_null(obj)
119
+ end
120
+ raise ConversionError, "Could not convert into object: #{val.inspect}" if res.null?
121
+
122
+ obj
123
+ else
124
+ Converter.ruby_to_object("")
125
+ end
126
+ end
127
+ # standard:enable Metrics/MethodLength,Metrics/CyclomaticComplexity
128
+
129
+ # standard:disable Metrics/MethodLength,Metrics/CyclomaticComplexity
130
+ def object_to_ruby(obj)
131
+ case obj[:type]
132
+ when :ddwaf_obj_invalid, :ddwaf_obj_null
133
+ nil
134
+ when :ddwaf_obj_bool
135
+ obj[:valueUnion][:boolean]
136
+ when :ddwaf_obj_string
137
+ # NOTE: FFI's `AbstractMemoryPointer#read_bytes` returns a binary string,
138
+ # which is not automatically encoded as UTF-8 and will raise an error
139
+ # if it contains non-ASCII characters and is used in a JSON#generate call.
140
+ bytes = obj[:valueUnion][:stringValue].read_bytes(obj[:nbEntries])
141
+ bytes.ascii_only? ? bytes : bytes.force_encoding(Encoding::UTF_8)
142
+ when :ddwaf_obj_signed
143
+ obj[:valueUnion][:intValue]
144
+ when :ddwaf_obj_unsigned
145
+ obj[:valueUnion][:uintValue]
146
+ when :ddwaf_obj_float
147
+ obj[:valueUnion][:f64]
148
+ when :ddwaf_obj_array
149
+ (0...obj[:nbEntries]).each.with_object([]) do |i, a|
150
+ ptr = obj[:valueUnion][:array] + i * LibDDWAF::Object.size
151
+ e = Converter.object_to_ruby(LibDDWAF::Object.new(ptr))
152
+ a << e # steep:ignore
153
+ end
154
+ when :ddwaf_obj_map
155
+ (0...obj[:nbEntries]).each.with_object({}) do |i, h|
156
+ ptr = obj[:valueUnion][:array] + i * Datadog::AppSec::WAF::LibDDWAF::Object.size
157
+ o = Datadog::AppSec::WAF::LibDDWAF::Object.new(ptr)
158
+ l = o[:parameterNameLength]
159
+ k = o[:parameterName].read_bytes(l)
160
+ v = Converter.object_to_ruby(LibDDWAF::Object.new(ptr))
161
+ h[k] = v # steep:ignore
162
+ end
163
+ end
164
+ end
165
+ # standard:enable Metrics/MethodLength,Metrics/CyclomaticComplexity
166
+ end
167
+ end
168
+ end
169
+ end
@@ -0,0 +1,19 @@
1
+ module Datadog
2
+ module AppSec
3
+ module WAF
4
+ Error = Class.new(StandardError)
5
+ InstanceFinalizedError = Class.new(Error)
6
+ ConversionError = Class.new(Error)
7
+
8
+ class LibDDWAFError < Error
9
+ attr_reader :diagnostics
10
+
11
+ def initialize(msg, diagnostics: nil)
12
+ @diagnostics = diagnostics
13
+
14
+ super(msg)
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Datadog
4
+ module AppSec
5
+ module WAF
6
+ # Ruby representation of the ddwaf_handle in libddwaf
7
+ # See https://github.com/DataDog/libddwaf/blob/10e3a1dfc7bc9bb8ab11a09a9f8b6b339eaf3271/BINDING_IMPL_NOTES.md?plain=1#L4-L19
8
+ class Handle
9
+ def initialize(handle_ptr)
10
+ @handle_ptr = handle_ptr
11
+ end
12
+
13
+ # Destroys the WAF handle and sets the pointer to nil.
14
+ #
15
+ # The instance becomes unusable after this method is called.
16
+ def finalize!
17
+ handle_ptr_to_destroy = @handle_ptr
18
+ @handle_ptr = nil
19
+
20
+ LibDDWAF.ddwaf_destroy(handle_ptr_to_destroy)
21
+ end
22
+
23
+ # Builds a WAF context.
24
+ #
25
+ # @raise [LibDDWAFError] if libddwaf could not create the context.
26
+ # @return [Handle] the WAF handle
27
+ def build_context
28
+ ensure_pointer_presence!
29
+
30
+ context_obj = LibDDWAF.ddwaf_context_init(@handle_ptr)
31
+ raise LibDDWAFError, "Could not create context" if context_obj.null?
32
+
33
+ Context.new(context_obj)
34
+ end
35
+
36
+ # Returns the list of known addresses in the WAF handle.
37
+ #
38
+ # @return [Array<String>] the list of known addresses
39
+ def known_addresses
40
+ ensure_pointer_presence!
41
+
42
+ count = LibDDWAF::UInt32Ptr.new
43
+ list = LibDDWAF.ddwaf_known_addresses(@handle_ptr, count)
44
+
45
+ return [] if count == 0 # list is null
46
+
47
+ list.get_array_of_string(0, count[:value])
48
+ end
49
+
50
+ private
51
+
52
+ def ensure_pointer_presence!
53
+ return if @handle_ptr
54
+
55
+ raise InstanceFinalizedError, "Cannot use WAF handle after it has been finalized"
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Datadog
4
+ module AppSec
5
+ module WAF
6
+ # This class represents the libddwaf WAF builder, which is used to generate WAF handles.
7
+ #
8
+ # It handles merging of potentially overlapping configurations.
9
+ class HandleBuilder
10
+ def initialize(limits: {}, obfuscator: {})
11
+ handle_config_obj = LibDDWAF::HandleBuilderConfig.new
12
+ if handle_config_obj.null?
13
+ raise LibDDWAFError, "Could not create config struct"
14
+ end
15
+
16
+ handle_config_obj[:limits][:max_container_size] = limits[:max_container_size] || LibDDWAF::DEFAULT_MAX_CONTAINER_SIZE
17
+ handle_config_obj[:limits][:max_container_depth] = limits[:max_container_depth] || LibDDWAF::DEFAULT_MAX_CONTAINER_DEPTH
18
+ handle_config_obj[:limits][:max_string_length] = limits[:max_string_length] || LibDDWAF::DEFAULT_MAX_STRING_LENGTH
19
+
20
+ handle_config_obj[:obfuscator][:key_regex] = FFI::MemoryPointer.from_string(obfuscator[:key_regex]) if obfuscator[:key_regex]
21
+ handle_config_obj[:obfuscator][:value_regex] = FFI::MemoryPointer.from_string(obfuscator[:value_regex]) if obfuscator[:value_regex]
22
+ handle_config_obj[:free_fn] = LibDDWAF::ObjectNoFree
23
+
24
+ @builder_ptr = LibDDWAF.ddwaf_builder_init(handle_config_obj)
25
+ end
26
+
27
+ # Destroys the WAF builder and sets the pointer to nil.
28
+ #
29
+ # The instance becomes unusable after this method is called.
30
+ def finalize!
31
+ builder_ptr_to_destroy = @builder_ptr
32
+ @builder_ptr = nil
33
+
34
+ LibDDWAF.ddwaf_builder_destroy(builder_ptr_to_destroy)
35
+ end
36
+
37
+ # Builds a WAF handle from the current state of the builder.
38
+ #
39
+ # @raise [LibDDWAFError] if no rules were added to the builder before building the handle
40
+ # @return [Handle] the WAF handle
41
+ def build_handle
42
+ ensure_pointer_presence!
43
+
44
+ handle_obj = LibDDWAF.ddwaf_builder_build_instance(@builder_ptr)
45
+ raise LibDDWAFError, "Could not create handle" if handle_obj.null?
46
+
47
+ Handle.new(handle_obj)
48
+ end
49
+
50
+ # :section: Configuration management methods
51
+ # methods for adding, updating, and removing configurations from the WAF handle builder.
52
+
53
+ # Adds or updates a configuration in the WAF handle builder for the given path.
54
+ #
55
+ # @return [Hash] diagnostics object
56
+ # NOTE: default config that was read from file at application startup
57
+ # has to be removed before adding configurations obtained through Remote Configuration.
58
+ def add_or_update_config(config, path:)
59
+ ensure_pointer_presence!
60
+
61
+ config_obj = Converter.ruby_to_object(config)
62
+ diagnostics_obj = LibDDWAF::Object.new
63
+
64
+ LibDDWAF.ddwaf_builder_add_or_update_config(@builder_ptr, path, path.length, config_obj, diagnostics_obj)
65
+
66
+ Converter.object_to_ruby(diagnostics_obj)
67
+ ensure
68
+ LibDDWAF.ddwaf_object_free(config_obj) if config_obj
69
+ LibDDWAF.ddwaf_object_free(diagnostics_obj) if diagnostics_obj
70
+ end
71
+
72
+ # Removes a configuration from the WAF handle builder for the given path.
73
+ #
74
+ # @return [Boolean] true if the configuration was removed, false otherwise
75
+ def remove_config_at_path(path)
76
+ ensure_pointer_presence!
77
+
78
+ LibDDWAF.ddwaf_builder_remove_config(@builder_ptr, path, path.length)
79
+ end
80
+
81
+ private
82
+
83
+ def ensure_pointer_presence!
84
+ return if @builder_ptr
85
+
86
+ raise InstanceFinalizedError, "Cannot use WAF handle builder after it has been finalized"
87
+ end
88
+ end
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,313 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ffi"
4
+ require "datadog/appsec/waf/version"
5
+
6
+ module Datadog
7
+ module AppSec
8
+ module WAF
9
+ # FFI-binding for C-libddwaf
10
+ # See https://github.com/DataDog/libddwaf
11
+ module LibDDWAF
12
+ DEFAULT_MAX_CONTAINER_SIZE = 256
13
+ DEFAULT_MAX_CONTAINER_DEPTH = 20
14
+ DEFAULT_MAX_STRING_LENGTH = 16_384 # in bytes, UTF-8 worst case being 4x size in terms of code point
15
+
16
+ DDWAF_MAX_CONTAINER_SIZE = 256
17
+ DDWAF_MAX_CONTAINER_DEPTH = 20
18
+ DDWAF_MAX_STRING_LENGTH = 4096
19
+
20
+ DDWAF_RUN_TIMEOUT = 5000
21
+
22
+ extend ::FFI::Library
23
+
24
+ def self.local_os
25
+ if RUBY_ENGINE == "jruby"
26
+ os_name = java.lang.System.get_property("os.name")
27
+
28
+ os = case os_name
29
+ when /linux/i then "linux"
30
+ when /mac/i then "darwin"
31
+ else raise Error, "unsupported JRuby os.name: #{os_name.inspect}"
32
+ end
33
+
34
+ return os
35
+ end
36
+
37
+ Gem::Platform.local.os
38
+ end
39
+
40
+ def self.local_version
41
+ return nil unless local_os == "linux"
42
+
43
+ # Old rubygems don't handle non-gnu linux correctly
44
+ return ::Regexp.last_match(1) if RUBY_PLATFORM =~ /linux-(.+)$/
45
+
46
+ "gnu"
47
+ end
48
+
49
+ def self.local_cpu
50
+ if RUBY_ENGINE == "jruby"
51
+ os_arch = java.lang.System.get_property("os.arch")
52
+
53
+ cpu = case os_arch
54
+ when "amd64" then "x86_64"
55
+ when "aarch64" then (local_os == "darwin") ? "arm64" : "aarch64"
56
+ else raise Error, "unsupported JRuby os.arch: #{os_arch.inspect}"
57
+ end
58
+
59
+ return cpu
60
+ end
61
+
62
+ Gem::Platform.local.cpu
63
+ end
64
+
65
+ def self.source_dir
66
+ __dir__ || raise("__dir__ is nil: eval?")
67
+ end
68
+
69
+ def self.vendor_dir
70
+ File.join(source_dir, "../../../../vendor")
71
+ end
72
+
73
+ def self.libddwaf_vendor_dir
74
+ File.join(vendor_dir, "libddwaf")
75
+ end
76
+
77
+ def self.shared_lib_triplet(version: local_version)
78
+ version ? "#{local_os}-#{version}-#{local_cpu}" : "#{local_os}-#{local_cpu}"
79
+ end
80
+
81
+ def self.libddwaf_dir
82
+ default = File.join(libddwaf_vendor_dir,
83
+ "libddwaf-#{Datadog::AppSec::WAF::VERSION::BASE_STRING}-#{shared_lib_triplet}")
84
+ candidates = [
85
+ default
86
+ ]
87
+
88
+ if local_os == "linux"
89
+ candidates << File.join(libddwaf_vendor_dir,
90
+ "libddwaf-#{Datadog::AppSec::WAF::VERSION::BASE_STRING}-#{shared_lib_triplet(version: nil)}")
91
+ end
92
+
93
+ candidates.find { |d| Dir.exist?(d) } || default
94
+ end
95
+
96
+ def self.shared_lib_extname
97
+ if Gem::Platform.local.os == "darwin"
98
+ ".dylib"
99
+ elsif Gem::Platform.local.os == "java" && java.lang.System.get_property("os.name").match(/mac/i)
100
+ ".dylib"
101
+ else
102
+ ".so"
103
+ end
104
+ end
105
+
106
+ def self.shared_lib_path
107
+ File.join(libddwaf_dir, "lib", "libddwaf#{shared_lib_extname}")
108
+ end
109
+
110
+ ffi_lib [shared_lib_path]
111
+
112
+ # version
113
+
114
+ attach_function :ddwaf_get_version, [], :string
115
+
116
+ # ddwaf::object data structure
117
+
118
+ DDWAF_OBJ_TYPE = enum :ddwaf_obj_invalid, 0,
119
+ :ddwaf_obj_signed, 1 << 0,
120
+ :ddwaf_obj_unsigned, 1 << 1,
121
+ :ddwaf_obj_string, 1 << 2,
122
+ :ddwaf_obj_array, 1 << 3,
123
+ :ddwaf_obj_map, 1 << 4,
124
+ :ddwaf_obj_bool, 1 << 5,
125
+ :ddwaf_obj_float, 1 << 6,
126
+ :ddwaf_obj_null, 1 << 7
127
+
128
+ typedef DDWAF_OBJ_TYPE, :ddwaf_obj_type
129
+
130
+ typedef :pointer, :charptr
131
+ typedef :pointer, :charptrptr
132
+
133
+ # Ruby representation of C uint32_t
134
+ class UInt32Ptr < ::FFI::Struct
135
+ layout :value, :uint32
136
+ end
137
+
138
+ typedef UInt32Ptr.by_ref, :uint32ptr
139
+
140
+ # Ruby representation of C uint64_t
141
+ class UInt64Ptr < ::FFI::Struct
142
+ layout :value, :uint64
143
+ end
144
+
145
+ typedef UInt64Ptr.by_ref, :uint64ptr
146
+
147
+ # Ruby representation of C size_t
148
+ class SizeTPtr < ::FFI::Struct
149
+ layout :value, :size_t
150
+ end
151
+
152
+ typedef SizeTPtr.by_ref, :sizeptr
153
+
154
+ # Ruby representation of C union
155
+ class ObjectValueUnion < ::FFI::Union
156
+ layout :stringValue, :charptr,
157
+ :uintValue, :uint64,
158
+ :intValue, :int64,
159
+ :array, :pointer,
160
+ :boolean, :bool,
161
+ :f64, :double
162
+ end
163
+
164
+ # Ruby representation of ddwaf_object
165
+ # See https://github.com/DataDog/libddwaf/blob/10e3a1dfc7bc9bb8ab11a09a9f8b6b339eaf3271/include/ddwaf.h#L94C1-L115C3
166
+ class Object < ::FFI::Struct
167
+ layout :parameterName, :charptr,
168
+ :parameterNameLength, :uint64,
169
+ :valueUnion, ObjectValueUnion,
170
+ :nbEntries, :uint64,
171
+ :type, :ddwaf_obj_type
172
+ end
173
+
174
+ typedef Object.by_ref, :ddwaf_object
175
+
176
+ ## setters
177
+
178
+ attach_function :ddwaf_object_invalid, [:ddwaf_object], :ddwaf_object
179
+ attach_function :ddwaf_object_string, [:ddwaf_object, :string], :ddwaf_object
180
+ attach_function :ddwaf_object_stringl, [:ddwaf_object, :charptr, :size_t], :ddwaf_object
181
+ attach_function :ddwaf_object_stringl_nc, [:ddwaf_object, :charptr, :size_t], :ddwaf_object
182
+ attach_function :ddwaf_object_string_from_unsigned, [:ddwaf_object, :uint64], :ddwaf_object
183
+ attach_function :ddwaf_object_string_from_signed, [:ddwaf_object, :int64], :ddwaf_object
184
+ attach_function :ddwaf_object_unsigned, [:ddwaf_object, :uint64], :ddwaf_object
185
+ attach_function :ddwaf_object_signed, [:ddwaf_object, :int64], :ddwaf_object
186
+ attach_function :ddwaf_object_bool, [:ddwaf_object, :bool], :ddwaf_object
187
+ attach_function :ddwaf_object_null, [:ddwaf_object], :ddwaf_object
188
+ attach_function :ddwaf_object_float, [:ddwaf_object, :double], :ddwaf_object
189
+
190
+ attach_function :ddwaf_object_array, [:ddwaf_object], :ddwaf_object
191
+ attach_function :ddwaf_object_array_add, [:ddwaf_object, :ddwaf_object], :bool
192
+
193
+ attach_function :ddwaf_object_map, [:ddwaf_object], :ddwaf_object
194
+ attach_function :ddwaf_object_map_add, [:ddwaf_object, :string, :pointer], :bool
195
+ attach_function :ddwaf_object_map_addl, [:ddwaf_object, :charptr, :size_t, :pointer], :bool
196
+ attach_function :ddwaf_object_map_addl_nc, [:ddwaf_object, :charptr, :size_t, :pointer], :bool
197
+
198
+ ## getters
199
+
200
+ attach_function :ddwaf_object_type, [:ddwaf_object], DDWAF_OBJ_TYPE
201
+ attach_function :ddwaf_object_size, [:ddwaf_object], :uint64
202
+ attach_function :ddwaf_object_length, [:ddwaf_object], :size_t
203
+ attach_function :ddwaf_object_get_key, [:ddwaf_object, :sizeptr], :charptr
204
+ attach_function :ddwaf_object_get_string, [:ddwaf_object, :sizeptr], :charptr
205
+ attach_function :ddwaf_object_get_unsigned, [:ddwaf_object], :uint64
206
+ attach_function :ddwaf_object_get_signed, [:ddwaf_object], :int64
207
+ attach_function :ddwaf_object_get_index, [:ddwaf_object, :size_t], :ddwaf_object
208
+ attach_function :ddwaf_object_get_bool, [:ddwaf_object], :bool
209
+ attach_function :ddwaf_object_get_float, [:ddwaf_object], :double
210
+
211
+ ## freeers
212
+
213
+ ObjectFree = attach_function :ddwaf_object_free, [:ddwaf_object], :void
214
+ ObjectNoFree = ::FFI::Pointer::NULL
215
+
216
+ # handle builder
217
+
218
+ typedef :pointer, :ddwaf_builder
219
+ typedef :pointer, :ddwaf_handle
220
+ typedef :pointer, :ddwaf_diagnostics
221
+
222
+ callback :ddwaf_object_free_fn, [:ddwaf_object], :void
223
+
224
+ # Ruby representation of ddwaf_config
225
+ # https://github.com/DataDog/libddwaf/blob/10e3a1dfc7bc9bb8ab11a09a9f8b6b339eaf3271/include/ddwaf.h#L129-L152
226
+ class HandleBuilderConfig < ::FFI::Struct
227
+ # Ruby representation of ddwaf_config_limits
228
+ # https://github.com/DataDog/libddwaf/blob/10e3a1dfc7bc9bb8ab11a09a9f8b6b339eaf3271/include/ddwaf.h#L131-L138
229
+ class Limits < ::FFI::Struct
230
+ layout :max_container_size, :uint32,
231
+ :max_container_depth, :uint32,
232
+ :max_string_length, :uint32
233
+ end
234
+
235
+ # Ruby representation of ddwaf_config_obfuscator
236
+ # https://github.com/DataDog/libddwaf/blob/10e3a1dfc7bc9bb8ab11a09a9f8b6b339eaf3271/include/ddwaf.h#L141-L146
237
+ class Obfuscator < ::FFI::Struct
238
+ layout :key_regex, :pointer, # should be :charptr
239
+ :value_regex, :pointer # should be :charptr
240
+ end
241
+
242
+ layout :limits, Limits,
243
+ :obfuscator, Obfuscator,
244
+ :free_fn, :pointer # :ddwaf_object_free_fn
245
+ end
246
+
247
+ typedef HandleBuilderConfig.by_ref, :ddwaf_config
248
+
249
+ attach_function :ddwaf_builder_init, [:ddwaf_config], :ddwaf_builder
250
+ attach_function :ddwaf_builder_destroy, [:ddwaf_builder], :void
251
+
252
+ attach_function :ddwaf_builder_add_or_update_config, [:ddwaf_builder, :string, :size_t, :ddwaf_object, :ddwaf_diagnostics], :bool
253
+ attach_function :ddwaf_builder_remove_config, [:ddwaf_builder, :string, :size_t], :bool
254
+
255
+ attach_function :ddwaf_builder_build_instance, [:ddwaf_builder], :ddwaf_handle
256
+
257
+ # handle
258
+
259
+ callback :ddwaf_object_free_fn, [:ddwaf_object], :void
260
+
261
+ attach_function :ddwaf_destroy, [:ddwaf_handle], :void
262
+
263
+ attach_function :ddwaf_known_addresses, [:ddwaf_handle, UInt32Ptr], :charptrptr
264
+
265
+ # updating
266
+
267
+ DDWAF_RET_CODE = enum :ddwaf_err_internal, -3,
268
+ :ddwaf_err_invalid_object, -2,
269
+ :ddwaf_err_invalid_argument, -1,
270
+ :ddwaf_ok, 0,
271
+ :ddwaf_match, 1
272
+ typedef DDWAF_RET_CODE, :ddwaf_ret_code
273
+
274
+ # running
275
+
276
+ typedef :pointer, :ddwaf_context
277
+
278
+ attach_function :ddwaf_context_init, [:ddwaf_handle], :ddwaf_context
279
+ attach_function :ddwaf_context_destroy, [:ddwaf_context], :void
280
+
281
+ # Ruby representation of ddwaf_result
282
+ # See https://github.com/DataDog/libddwaf/blob/10e3a1dfc7bc9bb8ab11a09a9f8b6b339eaf3271/include/ddwaf.h#L154-L173
283
+ class Result < ::FFI::Struct
284
+ layout :timeout, :bool,
285
+ :events, Object,
286
+ :actions, Object,
287
+ :derivatives, Object,
288
+ :total_runtime, :uint64
289
+ end
290
+
291
+ typedef Result.by_ref, :ddwaf_result
292
+ typedef :uint64, :timeout_us
293
+
294
+ attach_function :ddwaf_run, [:ddwaf_context, :ddwaf_object, :ddwaf_object, :ddwaf_result, :timeout_us], :ddwaf_ret_code, blocking: true
295
+ attach_function :ddwaf_result_free, [:ddwaf_result], :void
296
+
297
+ # logging
298
+
299
+ DDWAF_LOG_LEVEL = enum :ddwaf_log_trace,
300
+ :ddwaf_log_debug,
301
+ :ddwaf_log_info,
302
+ :ddwaf_log_warn,
303
+ :ddwaf_log_error,
304
+ :ddwaf_log_off
305
+ typedef DDWAF_LOG_LEVEL, :ddwaf_log_level
306
+
307
+ callback :ddwaf_log_cb, [:ddwaf_log_level, :string, :string, :uint, :charptr, :uint64], :void
308
+
309
+ attach_function :ddwaf_set_log_cb, [:ddwaf_log_cb, :ddwaf_log_level], :bool
310
+ end
311
+ end
312
+ end
313
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Datadog
4
+ module AppSec
5
+ module WAF
6
+ # Ruby representation of the ddwaf_result of a libddwaf run.
7
+ # See https://github.com/DataDog/libddwaf/blob/10e3a1dfc7bc9bb8ab11a09a9f8b6b339eaf3271/include/ddwaf.h#L159-L173
8
+ class Result
9
+ attr_reader :status, :events, :total_runtime, :timeout, :actions, :derivatives
10
+
11
+ def initialize(status, events, total_runtime, timeout, actions, derivatives)
12
+ @status = status
13
+ @events = events
14
+ @total_runtime = total_runtime
15
+ @timeout = timeout
16
+ @actions = actions
17
+ @derivatives = derivatives
18
+ end
19
+
20
+ def to_h
21
+ {
22
+ status: @status,
23
+ events: @events,
24
+ total_runtime: @total_runtime,
25
+ timeout: @timeout,
26
+ actions: @actions,
27
+ derivatives: @derivatives
28
+ }
29
+ end
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,13 @@
1
+ module Datadog
2
+ module AppSec
3
+ module WAF
4
+ module VERSION
5
+ BASE_STRING = "1.24.1"
6
+ # NOTE: Every change to the `BASE_STRING` should be accompanied
7
+ # by a reset of the patch version in the `STRING` below.
8
+ STRING = "#{BASE_STRING}.0.0"
9
+ MINIMUM_RUBY_VERSION = "2.5"
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "datadog/appsec/waf/lib_ddwaf"
4
+
5
+ require "datadog/appsec/waf/handle_builder"
6
+ require "datadog/appsec/waf/handle"
7
+ require "datadog/appsec/waf/converter"
8
+ require "datadog/appsec/waf/errors"
9
+ require "datadog/appsec/waf/result"
10
+ require "datadog/appsec/waf/context"
11
+ require "datadog/appsec/waf/version"
12
+
13
+ module Datadog
14
+ module AppSec
15
+ module WAF
16
+ module_function
17
+
18
+ def version
19
+ LibDDWAF.ddwaf_get_version
20
+ end
21
+
22
+ def log_callback(level, func, file, line, message, len)
23
+ return if WAF.logger.nil?
24
+
25
+ WAF.logger.debug do
26
+ {
27
+ level: level,
28
+ func: func,
29
+ file: file,
30
+ line: line,
31
+ message: message.read_bytes(len)
32
+ }.inspect
33
+ end
34
+ end
35
+
36
+ def logger
37
+ @logger
38
+ end
39
+
40
+ def logger=(logger)
41
+ unless @log_callback
42
+ log_callback = WAF.method(:log_callback)
43
+ LibDDWAF.ddwaf_set_log_cb(log_callback, :ddwaf_log_trace)
44
+
45
+ # retain logging proc if set properly
46
+ @log_callback = log_callback
47
+ end
48
+
49
+ @logger = logger
50
+ end
51
+ end
52
+ end
53
+ end
data/lib/libddwaf.rb ADDED
@@ -0,0 +1 @@
1
+ require "datadog/appsec/waf"
metadata ADDED
@@ -0,0 +1,74 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: libddwaf
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.24.1.0.0
5
+ platform: x86_64-linux-gnu
6
+ authors:
7
+ - Datadog, Inc.
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 2025-07-18 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: ffi
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '1.0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '1.0'
26
+ description: 'libddwaf packages a WAF implementation in C++, exposed to Ruby
27
+
28
+ '
29
+ email:
30
+ - dev@datadoghq.com
31
+ executables: []
32
+ extensions: []
33
+ extra_rdoc_files: []
34
+ files:
35
+ - CHANGELOG.md
36
+ - LICENSE
37
+ - LICENSE-3rdparty.csv
38
+ - LICENSE.Apache
39
+ - LICENSE.BSD3
40
+ - NOTICE
41
+ - lib/datadog/appsec/waf.rb
42
+ - lib/datadog/appsec/waf/context.rb
43
+ - lib/datadog/appsec/waf/converter.rb
44
+ - lib/datadog/appsec/waf/errors.rb
45
+ - lib/datadog/appsec/waf/handle.rb
46
+ - lib/datadog/appsec/waf/handle_builder.rb
47
+ - lib/datadog/appsec/waf/lib_ddwaf.rb
48
+ - lib/datadog/appsec/waf/result.rb
49
+ - lib/datadog/appsec/waf/version.rb
50
+ - lib/libddwaf.rb
51
+ - vendor/libddwaf/libddwaf-1.24.1-linux-x86_64/lib/libddwaf.so
52
+ homepage: https://github.com/DataDog/libddwaf-rb
53
+ licenses:
54
+ - BSD-3-Clause
55
+ metadata:
56
+ allowed_push_host: https://rubygems.org
57
+ rdoc_options: []
58
+ require_paths:
59
+ - lib
60
+ required_ruby_version: !ruby/object:Gem::Requirement
61
+ requirements:
62
+ - - ">="
63
+ - !ruby/object:Gem::Version
64
+ version: '2.5'
65
+ required_rubygems_version: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - ">="
68
+ - !ruby/object:Gem::Version
69
+ version: 2.0.0
70
+ requirements: []
71
+ rubygems_version: 3.6.2
72
+ specification_version: 4
73
+ summary: Datadog WAF
74
+ test_files: []