malmal 0.4.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 +7 -0
- data/LICENSE-APACHE +201 -0
- data/LICENSE-MIT +21 -0
- data/README.md +131 -0
- data/lib/malmal/client.rb +111 -0
- data/lib/malmal/errors.rb +30 -0
- data/lib/malmal/libmalmal_ffi.so +0 -0
- data/lib/malmal/native.rb +91 -0
- data/lib/malmal/report.rb +125 -0
- data/lib/malmal/scanner.rb +222 -0
- data/lib/malmal/version.rb +6 -0
- data/lib/malmal.rb +14 -0
- data/sig/malmal.rbs +101 -0
- metadata +75 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: e6aec8b57e1bf2f703c9456c6a2cc9043f9b7614f2fb192b94edc4acc36ee5f4
|
|
4
|
+
data.tar.gz: 3fb4e606d51ddf8ff565f2a795ac5e9bcdbee98f365a2f5f0b665ad862549257
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 3fbe1ace5197ffbe4404578d2998cfe69d053e9464fc2fc97e3e81f5dfc455700cf51410288d30961ac2728cc7c0b1946991f8248117c5858270dc12f39c9533
|
|
7
|
+
data.tar.gz: 44278c11ad08d6e3129f2a934bd0034c3fb93e660bb374ce63f4f120e9b4e75d63c75ec67944de675863e5ecd575994863ebd5e2765baaa7f3645d24aefac166
|
data/LICENSE-APACHE
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 Derivative
|
|
95
|
+
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 2026 nguyenthuan155632
|
|
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/LICENSE-MIT
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 nguyenthuan155632
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# malmal for Ruby
|
|
2
|
+
|
|
3
|
+
The [malmal](https://github.com/nguyenthuan155632/malmal) upload scanner for any Ruby
|
|
4
|
+
program. It calls `libmalmal_ffi` through the `ffi` gem, and the platform gems carry
|
|
5
|
+
that library, so installing it needs no Rust. For Rails, see
|
|
6
|
+
[malmal-rails](../malmal-rails/README.md).
|
|
7
|
+
|
|
8
|
+
```ruby
|
|
9
|
+
require "malmal"
|
|
10
|
+
|
|
11
|
+
SCANNER = Malmal::Scanner.new # build once, share between threads
|
|
12
|
+
report = SCANNER.scan(upload, filename: "a.png", content_type: "image/png")
|
|
13
|
+
reject(report.codes) unless report.clean?
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Anything but `clean?`, including a `Malmal::ScanError`, means the file is not accepted.
|
|
17
|
+
A scan releases the GVL, so the other threads of a Puma worker carry on while it runs.
|
|
18
|
+
|
|
19
|
+
## Installing
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
bundle add malmal
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
RubyGems picks the gem for the machine:
|
|
26
|
+
|
|
27
|
+
| Platform | For |
|
|
28
|
+
|---|---|
|
|
29
|
+
| `x86_64-linux-gnu`, `aarch64-linux-gnu` | Linux with glibc 2.17 or newer (Debian, Ubuntu, RHEL) |
|
|
30
|
+
| `x86_64-linux-musl`, `aarch64-linux-musl` | Alpine |
|
|
31
|
+
| `arm64-darwin`, `x86_64-darwin` | macOS |
|
|
32
|
+
| `ruby` | anything else, with a library of your own at `MALMAL_LIBRARY` |
|
|
33
|
+
|
|
34
|
+
The gem loads the library at `MALMAL_LIBRARY` if that is set, else the one it carries,
|
|
35
|
+
else `libmalmal_ffi` from the system's library path. It has to be of the gem's version,
|
|
36
|
+
except at `MALMAL_LIBRARY`; otherwise `Malmal::LoadError` says what was found. A library
|
|
37
|
+
for the `ruby` gem is built from a checkout of malmal with:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
cargo build --release -p malmal-ffi
|
|
41
|
+
export MALMAL_LIBRARY=$PWD/target/release/libmalmal_ffi.so
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Ruby 3.2 or newer.
|
|
45
|
+
|
|
46
|
+
## Scanning
|
|
47
|
+
|
|
48
|
+
```ruby
|
|
49
|
+
scanner = Malmal::Scanner.new(
|
|
50
|
+
policy: :documents, # or :default, :strict
|
|
51
|
+
allow: %w[pdf.xfa], # codes that do not count against a file
|
|
52
|
+
types: %i[jpeg png pdf], # accepted file types; every supported one if nil
|
|
53
|
+
hashlist: File.read("blocklist.txt"),
|
|
54
|
+
pdf_passwords: ["statement-password"],
|
|
55
|
+
max_size: 20 << 20, scan_timeout: 5, # also max_decompressed, max_pixels, max_depth
|
|
56
|
+
max_memory: 256 << 20, # what one scan may hold; 512 MiB if not given
|
|
57
|
+
wait: 30 # answer within 30 s whatever the file does
|
|
58
|
+
)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
An unknown option, policy, type or code raises `ArgumentError`. With `wait`, a scan that
|
|
62
|
+
has not ended in time is reported with `limit.time`, never clean, and left running on
|
|
63
|
+
its thread; `scanner.overdue` counts those, and above 0 the process is due a restart.
|
|
64
|
+
|
|
65
|
+
`scan` takes a String or an IO. An IO is read up to `max_size` and one byte past it, so
|
|
66
|
+
that a file too large is reported as such. The `Malmal::Report` it returns has `verdict`
|
|
67
|
+
(`:clean`, `:suspicious` or `:malicious`), `clean?`, `suspicious?`, `malicious?`,
|
|
68
|
+
`detected_type`, `declared_types`, `size`, `sha256`, `findings`, `codes` and `to_h`.
|
|
69
|
+
Each `Malmal::Finding` has `code`, `severity` (`:info` to `:critical`), `message` and
|
|
70
|
+
`offset`.
|
|
71
|
+
|
|
72
|
+
## Rebuilding files
|
|
73
|
+
|
|
74
|
+
`sanitize` scans and then writes a clean file anew from what it draws, so that nothing
|
|
75
|
+
else is kept:
|
|
76
|
+
|
|
77
|
+
```ruby
|
|
78
|
+
begin
|
|
79
|
+
image = scanner.sanitize(upload, filename: "a.png", jpeg_quality: 85)
|
|
80
|
+
rescue Malmal::Rejected => e # the scan did not come back clean
|
|
81
|
+
reject(e.report.codes)
|
|
82
|
+
rescue Malmal::NotRebuilt # clean, but not a file that can be rebuilt
|
|
83
|
+
reject
|
|
84
|
+
else
|
|
85
|
+
store(image.data, image.content_type, "a#{image.extension}")
|
|
86
|
+
end
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The type can change: a BMP, TIFF or ICO comes out as a PNG. `Malmal::Sanitized` has
|
|
90
|
+
`data`, `file_type`, `content_type`, `extension`, `width`, `height`, `frames` and
|
|
91
|
+
`report`. `sanitize` also takes `types`, `pdf_dpi`, `pdf_jpeg`, `pdf_text` and
|
|
92
|
+
`pdf_vector_text`; PDFs are rebuilt only by a library built with `cdr-pdf`. Both
|
|
93
|
+
exceptions are a `Malmal::SanitizeError`.
|
|
94
|
+
|
|
95
|
+
## Speed
|
|
96
|
+
|
|
97
|
+
A scan from Ruby costs 10 to 16 µs more than the same scan from Rust: the copy of the
|
|
98
|
+
data, the report as JSON, and releasing the GVL. From some 20 KB up, the difference is
|
|
99
|
+
within 5%. `ruby -Ilib bench/throughput.rb FILE...` measures it on your files.
|
|
100
|
+
|
|
101
|
+
## With malmald
|
|
102
|
+
|
|
103
|
+
`Malmal::Client` answers as `Scanner` does, from a running `malmald`. It is for
|
|
104
|
+
deployments that want what only the daemon gives: the sandbox, and `--hard-timeout`
|
|
105
|
+
ending a scan that does not end.
|
|
106
|
+
|
|
107
|
+
```ruby
|
|
108
|
+
client = Malmal::Client.new("http://127.0.0.1:8080", token: ENV["MALMAL_TOKEN"])
|
|
109
|
+
client.scan(upload, filename: "a.png").clean?
|
|
110
|
+
client.healthy?
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
The scanning options are then the daemon's flags. `sanitize` takes `types` only, checked
|
|
114
|
+
against the type of the rebuilt file. A daemon that cannot be reached, or does not answer
|
|
115
|
+
with a report, raises `Malmal::ScanError`.
|
|
116
|
+
|
|
117
|
+
## Development
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
cargo build --release -p malmal-ffi
|
|
121
|
+
cd bindings/ruby/malmal
|
|
122
|
+
bundle install
|
|
123
|
+
MALMAL_LIBRARY=../../../target/release/libmalmal_ffi.so bundle exec rake test
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
With `MALMALD` set to a `malmald` binary, the client tests run against it too.
|
|
127
|
+
`bindings/ruby/build_gem.sh <rust-target>` builds a platform gem into `bindings/ruby/pkg`.
|
|
128
|
+
|
|
129
|
+
## License
|
|
130
|
+
|
|
131
|
+
MIT or Apache-2.0, at your option.
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "net/http"
|
|
5
|
+
require "openssl"
|
|
6
|
+
require "uri"
|
|
7
|
+
|
|
8
|
+
module Malmal
|
|
9
|
+
# The scanner of a running malmald, over its HTTP endpoint. It answers as
|
|
10
|
+
# Scanner does, and is for deployments that want what only the daemon
|
|
11
|
+
# gives: the sandbox, and --hard-timeout ending a scan that does not.
|
|
12
|
+
#
|
|
13
|
+
# client = Malmal::Client.new("http://127.0.0.1:8080", token: ENV["MALMAL_TOKEN"])
|
|
14
|
+
# client.scan(upload, filename: "a.png").clean?
|
|
15
|
+
class Client
|
|
16
|
+
attr_reader :url
|
|
17
|
+
|
|
18
|
+
# +url+ is the daemon's base URL; +token+ the one it was started with
|
|
19
|
+
# (--token-file), if any. +open_timeout+ and +read_timeout+ are seconds;
|
|
20
|
+
# the read timeout has to cover the longest scan.
|
|
21
|
+
def initialize(url, token: nil, open_timeout: 5, read_timeout: 120)
|
|
22
|
+
@url = URI(url.to_s.chomp("/"))
|
|
23
|
+
@token = token
|
|
24
|
+
@open_timeout = open_timeout
|
|
25
|
+
@read_timeout = read_timeout
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# As Scanner#scan. Anything but an answer with a report raises ScanError.
|
|
29
|
+
def scan(data, filename: nil, content_type: nil)
|
|
30
|
+
response = post("/scan", data, filename, content_type)
|
|
31
|
+
body = parse(response)
|
|
32
|
+
unless response.code == "200" && body["ok"] && body["report"]
|
|
33
|
+
raise ScanError, "malmald did not scan the file: #{response.code} #{body["error"]}".strip
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
Report.from_h(body["report"])
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# As Scanner#sanitize, with the daemon's own options of the rebuild
|
|
40
|
+
# (the --jpeg-quality and --pdf-* flags it was started with). +types+ is
|
|
41
|
+
# checked here, against the type of the rebuilt file: one of another type
|
|
42
|
+
# raises NotRebuilt. Any other option raises ArgumentError.
|
|
43
|
+
def sanitize(data, filename: nil, content_type: nil, types: nil, **options)
|
|
44
|
+
unless options.empty?
|
|
45
|
+
raise ArgumentError, "#{options.keys.join(", ")} cannot be sent to malmald; start the daemon with them instead"
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
response = post("/sanitize", data, filename, content_type)
|
|
49
|
+
case response.code
|
|
50
|
+
when "200"
|
|
51
|
+
file_type = Sanitized::CONTENT_TYPES.key(response["Content-Type"].to_s.split(";").first) || :unknown
|
|
52
|
+
if types && !Array(types).map(&:to_sym).include?(file_type)
|
|
53
|
+
raise NotRebuilt, "a #{file_type} file is not among the types to rebuild"
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# The daemon does not send the report of a file it rebuilt; the
|
|
57
|
+
# rebuilt file was clean, or it would not have been sent.
|
|
58
|
+
report = Report.new(verdict: :clean, detected_type: file_type)
|
|
59
|
+
Sanitized.new(data: response.body.b, file_type: file_type, report: report)
|
|
60
|
+
when "422"
|
|
61
|
+
body = parse(response)
|
|
62
|
+
raise Rejected, Report.from_h(body["report"]) if body["report"]
|
|
63
|
+
|
|
64
|
+
raise NotRebuilt, body["error"].to_s
|
|
65
|
+
when "415", "501"
|
|
66
|
+
raise NotRebuilt, parse(response)["error"].to_s
|
|
67
|
+
else
|
|
68
|
+
raise ScanError, "malmald did not rebuild the file: #{response.code} #{parse(response)["error"]}".strip
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# Whether the daemon answers GET /healthz.
|
|
73
|
+
def healthy?
|
|
74
|
+
request(Net::HTTP::Get.new(path("/healthz"))).code == "200"
|
|
75
|
+
rescue StandardError
|
|
76
|
+
false
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
private
|
|
80
|
+
|
|
81
|
+
def path(name)
|
|
82
|
+
"#{@url.path}#{name}"
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def post(name, data, filename, content_type)
|
|
86
|
+
bytes = data.respond_to?(:read) ? data.read.to_s : data.to_s
|
|
87
|
+
data.rewind if data.respond_to?(:rewind)
|
|
88
|
+
request = Net::HTTP::Post.new(path(name))
|
|
89
|
+
request["Content-Type"] = content_type.to_s.empty? ? "application/octet-stream" : content_type.to_s
|
|
90
|
+
request["X-Filename"] = URI.encode_www_form_component(filename.to_s).gsub("+", "%20") if filename
|
|
91
|
+
request.body = bytes.b
|
|
92
|
+
request(request)
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
def request(request)
|
|
96
|
+
request["Authorization"] = "Bearer #{@token}" if @token
|
|
97
|
+
Net::HTTP.start(@url.host, @url.port, use_ssl: @url.scheme == "https",
|
|
98
|
+
open_timeout: @open_timeout, read_timeout: @read_timeout) do |http|
|
|
99
|
+
http.request(request)
|
|
100
|
+
end
|
|
101
|
+
rescue SystemCallError, IOError, Timeout::Error, OpenSSL::SSL::SSLError => e
|
|
102
|
+
raise ScanError, "malmald could not be reached: #{e.message}"
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
def parse(response)
|
|
106
|
+
JSON.parse(response.body.to_s)
|
|
107
|
+
rescue JSON::ParserError
|
|
108
|
+
{}
|
|
109
|
+
end
|
|
110
|
+
end
|
|
111
|
+
end
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Malmal
|
|
4
|
+
# The base of every error the gem raises.
|
|
5
|
+
class Error < StandardError; end
|
|
6
|
+
|
|
7
|
+
# The file was not scanned. Treat it as not accepted.
|
|
8
|
+
class ScanError < Error; end
|
|
9
|
+
|
|
10
|
+
# There is no rebuilt file, and the original is not to be kept in its place.
|
|
11
|
+
class SanitizeError < Error; end
|
|
12
|
+
|
|
13
|
+
# The scan of the upload, or of the file made from it, did not come back
|
|
14
|
+
# clean; +report+ is the one that was not.
|
|
15
|
+
class Rejected < SanitizeError
|
|
16
|
+
attr_reader :report
|
|
17
|
+
|
|
18
|
+
def initialize(report)
|
|
19
|
+
@report = report
|
|
20
|
+
super("file is not clean: #{report.codes.join(", ")}")
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# The file is clean but is not of a type that can be rebuilt, is too large,
|
|
25
|
+
# or does not decode.
|
|
26
|
+
class NotRebuilt < SanitizeError; end
|
|
27
|
+
|
|
28
|
+
# libmalmal_ffi could not be found or is not the version this gem needs.
|
|
29
|
+
class LoadError < Error; end
|
|
30
|
+
end
|
|
Binary file
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "ffi"
|
|
4
|
+
|
|
5
|
+
module Malmal
|
|
6
|
+
# The functions of libmalmal_ffi, as declared in malmal.h. Each that scans
|
|
7
|
+
# releases the GVL, so other Ruby threads run while a file is scanned.
|
|
8
|
+
module Native
|
|
9
|
+
extend FFI::Library
|
|
10
|
+
|
|
11
|
+
CLEAN = 0
|
|
12
|
+
SUSPICIOUS = 1
|
|
13
|
+
MALICIOUS = 2
|
|
14
|
+
ERROR = 3
|
|
15
|
+
NOT_REBUILT = 4
|
|
16
|
+
|
|
17
|
+
NAMES = %w[libmalmal_ffi.so libmalmal_ffi.dylib malmal_ffi.dll].freeze
|
|
18
|
+
LOCK = Mutex.new
|
|
19
|
+
private_constant :LOCK
|
|
20
|
+
|
|
21
|
+
class << self
|
|
22
|
+
# Where the library was loaded from.
|
|
23
|
+
attr_reader :path
|
|
24
|
+
|
|
25
|
+
# The library this gem carries, else the one at MALMAL_LIBRARY, else
|
|
26
|
+
# whatever the system loader finds.
|
|
27
|
+
def candidates
|
|
28
|
+
bundled = NAMES.map { |name| File.join(__dir__, name) }.select { |file| File.file?(file) }
|
|
29
|
+
[ENV.fetch("MALMAL_LIBRARY", nil), *bundled, "malmal_ffi"].compact.reject(&:empty?)
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# The version of the loaded library.
|
|
33
|
+
def version
|
|
34
|
+
malmal_version.dup.force_encoding(Encoding::UTF_8)
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# Load the library once, whichever thread asks first.
|
|
38
|
+
def load!
|
|
39
|
+
return if @loaded
|
|
40
|
+
|
|
41
|
+
LOCK.synchronize { load_once! unless @loaded }
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
private
|
|
45
|
+
|
|
46
|
+
def load_once!
|
|
47
|
+
errors = []
|
|
48
|
+
candidates.each do |candidate|
|
|
49
|
+
ffi_lib(candidate)
|
|
50
|
+
@path = candidate
|
|
51
|
+
break
|
|
52
|
+
rescue ::LoadError => e
|
|
53
|
+
errors << e.message
|
|
54
|
+
end
|
|
55
|
+
unless @path
|
|
56
|
+
raise Malmal::LoadError,
|
|
57
|
+
"libmalmal_ffi was not found (#{errors.join("; ")}). This gem has no library for " \
|
|
58
|
+
"#{RUBY_PLATFORM}; build one with `cargo build --release -p malmal-ffi` and set " \
|
|
59
|
+
"MALMAL_LIBRARY to its path."
|
|
60
|
+
end
|
|
61
|
+
attach!
|
|
62
|
+
check_version!
|
|
63
|
+
@loaded = true
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def attach!
|
|
67
|
+
attach_function :malmal_version, [], :string
|
|
68
|
+
attach_function :malmal_scanner_new_json, %i[string pointer], :pointer
|
|
69
|
+
attach_function :malmal_scanner_overdue, [:pointer], :uint64
|
|
70
|
+
attach_function :malmal_scanner_free, [:pointer], :void
|
|
71
|
+
attach_function :malmal_scan, %i[pointer pointer size_t string string pointer], :int, blocking: true
|
|
72
|
+
attach_function :malmal_sanitize_json,
|
|
73
|
+
%i[pointer pointer size_t string string string pointer pointer pointer], :int,
|
|
74
|
+
blocking: true
|
|
75
|
+
attach_function :malmal_string_free, [:pointer], :void
|
|
76
|
+
attach_function :malmal_bytes_free, %i[pointer size_t], :void
|
|
77
|
+
rescue FFI::NotFoundError => e
|
|
78
|
+
raise Malmal::LoadError, "#{@path} is older than this gem (#{e.message}); it needs #{Malmal::VERSION}"
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# The library this gem carries has to be its own version; one given
|
|
82
|
+
# with MALMAL_LIBRARY only has to have the functions.
|
|
83
|
+
def check_version!
|
|
84
|
+
return if version == Malmal::VERSION
|
|
85
|
+
return if ENV["MALMAL_LIBRARY"].to_s == @path
|
|
86
|
+
|
|
87
|
+
raise Malmal::LoadError, "#{@path} is version #{version}, and this gem is #{Malmal::VERSION}"
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
end
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Malmal
|
|
4
|
+
# Severities from least to most serious.
|
|
5
|
+
SEVERITIES = %i[info low medium high critical].freeze
|
|
6
|
+
|
|
7
|
+
# One thing the scanner noticed about a file. +code+ is stable (the codes
|
|
8
|
+
# are listed in docs/findings.md); the wording of +message+ is not.
|
|
9
|
+
Finding = Struct.new(:code, :severity, :message, :offset, keyword_init: true) do
|
|
10
|
+
def self.from_h(fields)
|
|
11
|
+
new(
|
|
12
|
+
code: fields.fetch("code"),
|
|
13
|
+
severity: fields.fetch("severity").to_sym,
|
|
14
|
+
message: fields.fetch("message", ""),
|
|
15
|
+
offset: fields["offset"]
|
|
16
|
+
)
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def to_h
|
|
20
|
+
{ code: code, severity: severity, message: message, offset: offset }
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# What a scan found. Anything but a clean verdict means the file is not to
|
|
25
|
+
# be accepted.
|
|
26
|
+
class Report
|
|
27
|
+
attr_reader :verdict, :detected_type, :declared_types, :size, :sha256, :findings
|
|
28
|
+
|
|
29
|
+
def self.from_h(fields)
|
|
30
|
+
new(
|
|
31
|
+
verdict: fields.fetch("verdict").to_sym,
|
|
32
|
+
detected_type: fields.fetch("detected_type").to_sym,
|
|
33
|
+
declared_types: fields.fetch("declared_types", []).map(&:to_sym),
|
|
34
|
+
size: fields.fetch("size", 0),
|
|
35
|
+
sha256: fields.fetch("sha256", ""),
|
|
36
|
+
findings: fields.fetch("findings", []).map { |finding| Finding.from_h(finding) }
|
|
37
|
+
)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def initialize(verdict:, detected_type:, declared_types: [], size: 0, sha256: "", findings: [])
|
|
41
|
+
@verdict = verdict
|
|
42
|
+
@detected_type = detected_type
|
|
43
|
+
@declared_types = declared_types.freeze
|
|
44
|
+
@size = size
|
|
45
|
+
@sha256 = sha256
|
|
46
|
+
@findings = findings.freeze
|
|
47
|
+
freeze
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def clean?
|
|
51
|
+
verdict == :clean
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def suspicious?
|
|
55
|
+
verdict == :suspicious
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def malicious?
|
|
59
|
+
verdict == :malicious
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# The codes of the findings that count against the file: those above
|
|
63
|
+
# +info+, in the order they were found.
|
|
64
|
+
def codes
|
|
65
|
+
findings.reject { |finding| finding.severity == :info }.map(&:code).uniq
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
def to_h
|
|
69
|
+
{
|
|
70
|
+
verdict: verdict,
|
|
71
|
+
detected_type: detected_type,
|
|
72
|
+
declared_types: declared_types,
|
|
73
|
+
size: size,
|
|
74
|
+
sha256: sha256,
|
|
75
|
+
findings: findings.map(&:to_h)
|
|
76
|
+
}
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def inspect
|
|
80
|
+
"#<Malmal::Report #{verdict} #{detected_type} codes=#{codes.inspect}>"
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# A file written anew from a clean upload: an image from its pixels, an SVG
|
|
85
|
+
# from what draws in it, a PDF as pictures of its pages.
|
|
86
|
+
class Sanitized
|
|
87
|
+
CONTENT_TYPES = {
|
|
88
|
+
jpeg: "image/jpeg",
|
|
89
|
+
png: "image/png",
|
|
90
|
+
gif: "image/gif",
|
|
91
|
+
webp: "image/webp",
|
|
92
|
+
svg: "image/svg+xml",
|
|
93
|
+
pdf: "application/pdf"
|
|
94
|
+
}.freeze
|
|
95
|
+
|
|
96
|
+
EXTENSIONS = { jpeg: ".jpg", png: ".png", gif: ".gif", webp: ".webp", svg: ".svg", pdf: ".pdf" }.freeze
|
|
97
|
+
|
|
98
|
+
# +data+ is the file to keep; +file_type+ its type, which is not always
|
|
99
|
+
# the type of the upload. +width+ and +height+ are 0 for an SVG or a PDF;
|
|
100
|
+
# +frames+ counts the frames of an animation or the pages of a PDF.
|
|
101
|
+
attr_reader :data, :file_type, :width, :height, :frames, :report
|
|
102
|
+
|
|
103
|
+
def initialize(data:, file_type:, report:, width: 0, height: 0, frames: 1)
|
|
104
|
+
@data = data
|
|
105
|
+
@file_type = file_type.to_sym
|
|
106
|
+
@width = width
|
|
107
|
+
@height = height
|
|
108
|
+
@frames = frames
|
|
109
|
+
@report = report
|
|
110
|
+
freeze
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def content_type
|
|
114
|
+
CONTENT_TYPES.fetch(file_type, "application/octet-stream")
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def extension
|
|
118
|
+
EXTENSIONS.fetch(file_type, "")
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
def inspect
|
|
122
|
+
"#<Malmal::Sanitized #{file_type} #{data.bytesize} bytes>"
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
end
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
5
|
+
module Malmal
|
|
6
|
+
# A configured scanner. One instance may be shared by every thread of the
|
|
7
|
+
# process: it holds no per-scan state.
|
|
8
|
+
#
|
|
9
|
+
# scanner = Malmal::Scanner.new(policy: :documents, types: %i[jpeg png pdf])
|
|
10
|
+
# report = scanner.scan(upload, filename: "a.pdf", content_type: "application/pdf")
|
|
11
|
+
# raise "rejected: #{report.codes.join(", ")}" unless report.clean?
|
|
12
|
+
class Scanner
|
|
13
|
+
POLICIES = %i[default strict documents].freeze
|
|
14
|
+
LIMITS = %i[max_size max_decompressed max_pixels max_depth scan_timeout].freeze
|
|
15
|
+
SANITIZE_OPTIONS = %i[types pdf_dpi pdf_jpeg pdf_text pdf_vector_text].freeze
|
|
16
|
+
DEFAULT_MAX_MEMORY = 512 << 20
|
|
17
|
+
|
|
18
|
+
# The handle is freed when the scanner is collected, unless #close
|
|
19
|
+
# freed it first.
|
|
20
|
+
class Handle < FFI::AutoPointer
|
|
21
|
+
def self.release(pointer)
|
|
22
|
+
Native.malmal_scanner_free(pointer)
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
private_constant :Handle
|
|
26
|
+
|
|
27
|
+
attr_reader :options
|
|
28
|
+
|
|
29
|
+
# +policy+:: +:default+, +:strict+ or +:documents+ (XFA forms and
|
|
30
|
+
# attachments in PDFs do not count; what they hold does).
|
|
31
|
+
# +allow+:: finding codes reported at +:info+, such as
|
|
32
|
+
# <tt>%w[pdf.xfa]</tt>; an unknown code, or a +limit.*+ one,
|
|
33
|
+
# raises ArgumentError.
|
|
34
|
+
# +types+:: the accepted file types, such as <tt>%i[jpeg png pdf]</tt>;
|
|
35
|
+
# every supported type when nil.
|
|
36
|
+
# +hashlist+:: a SHA-256 blocklist as text, one hex digest per line.
|
|
37
|
+
# +pdf_passwords+:: passwords to try on encrypted PDFs.
|
|
38
|
+
# +max_size+, +max_decompressed+, +max_pixels+, +max_depth+,
|
|
39
|
+
# +scan_timeout+ (seconds):: the limits of one scan.
|
|
40
|
+
# +max_memory+:: bytes one scan may hold; nil or 0 for no limit.
|
|
41
|
+
# +without_hash+:: leave the SHA-256 out of reports.
|
|
42
|
+
# +wait+:: seconds after which #scan stops waiting and reports
|
|
43
|
+
# +limit.time+ even if a step of the scan never ends; the scan
|
|
44
|
+
# is left running on its thread (see #overdue).
|
|
45
|
+
def initialize(policy: :default, allow: [], types: nil, hashlist: nil, pdf_passwords: [],
|
|
46
|
+
max_memory: DEFAULT_MAX_MEMORY, without_hash: false, wait: nil, **limits)
|
|
47
|
+
unknown = limits.keys - LIMITS
|
|
48
|
+
raise ArgumentError, "unknown option #{unknown.first.inspect}" unless unknown.empty?
|
|
49
|
+
raise ArgumentError, "max_memory cannot be negative" if max_memory&.negative?
|
|
50
|
+
|
|
51
|
+
Native.load!
|
|
52
|
+
@options = {
|
|
53
|
+
policy: policy.to_s,
|
|
54
|
+
allow: Array(allow).flat_map { |code| code.to_s.split(/[,|]/) }.map(&:strip).reject(&:empty?),
|
|
55
|
+
pdf_passwords: Array(pdf_passwords).map { |password| password_json(password) },
|
|
56
|
+
max_memory: max_memory || 0,
|
|
57
|
+
without_hash: without_hash ? true : false
|
|
58
|
+
}
|
|
59
|
+
@options[:types] = Array(types).map(&:to_s) if types
|
|
60
|
+
@options[:hashlist] = hashlist.to_s if hashlist
|
|
61
|
+
@options[:wait] = wait if wait
|
|
62
|
+
@options.merge!(limits)
|
|
63
|
+
@handle = build(JSON.generate(@options))
|
|
64
|
+
@mutex = Mutex.new
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Scan +data+: a String of bytes, or an IO read up to the size limit and
|
|
68
|
+
# one byte past it. +filename+ and +content_type+ are what the uploader
|
|
69
|
+
# claimed. Returns a Report; raises ScanError if the file was not scanned.
|
|
70
|
+
def scan(data, filename: nil, content_type: nil)
|
|
71
|
+
bytes = read(data)
|
|
72
|
+
with_input(bytes) do |pointer|
|
|
73
|
+
report = FFI::MemoryPointer.new(:pointer)
|
|
74
|
+
verdict = Native.malmal_scan(handle, pointer, bytes.bytesize, claim(filename), claim(content_type), report)
|
|
75
|
+
json = take_string(report.read_pointer)
|
|
76
|
+
raise ScanError, "the scanner failed; the file was not scanned" if verdict == Native::ERROR || json.nil?
|
|
77
|
+
|
|
78
|
+
Report.from_h(JSON.parse(json))
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# Scan +data+ and, if it is clean and of a type that can be, write it
|
|
83
|
+
# anew. Returns a Sanitized whose +data+ is the file to keep in place of
|
|
84
|
+
# the upload. Raises Rejected, NotRebuilt or ScanError otherwise; in
|
|
85
|
+
# every case the upload is not to be kept.
|
|
86
|
+
#
|
|
87
|
+
# +jpeg_quality+ (1 to 100), +types+, +pdf_dpi+, +pdf_jpeg+, +pdf_text+
|
|
88
|
+
# and +pdf_vector_text+ are the options of the rebuild.
|
|
89
|
+
def sanitize(data, filename: nil, content_type: nil, jpeg_quality: nil, **options)
|
|
90
|
+
unknown = options.keys - SANITIZE_OPTIONS
|
|
91
|
+
raise ArgumentError, "unknown option #{unknown.first.inspect}" unless unknown.empty?
|
|
92
|
+
|
|
93
|
+
options[:types] = Array(options[:types]).map(&:to_s) if options.key?(:types)
|
|
94
|
+
options[:jpeg_quality] = jpeg_quality if jpeg_quality
|
|
95
|
+
bytes = read(data)
|
|
96
|
+
with_input(bytes) do |pointer|
|
|
97
|
+
image = FFI::MemoryPointer.new(:pointer)
|
|
98
|
+
length = FFI::MemoryPointer.new(:size_t)
|
|
99
|
+
info = FFI::MemoryPointer.new(:pointer)
|
|
100
|
+
status = Native.malmal_sanitize_json(handle, pointer, bytes.bytesize, claim(filename), claim(content_type),
|
|
101
|
+
JSON.generate(options), image, length, info)
|
|
102
|
+
rebuilt = take_bytes(image.read_pointer, length.read(:size_t))
|
|
103
|
+
json = take_string(info.read_pointer)
|
|
104
|
+
sanitized(status, rebuilt, json ? JSON.parse(json) : {})
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# Scans that +wait+ stopped waiting for and that are still running.
|
|
109
|
+
# Above 0, restart the process when it can be.
|
|
110
|
+
def overdue
|
|
111
|
+
Native.malmal_scanner_overdue(handle)
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# The version of the loaded libmalmal_ffi.
|
|
115
|
+
def library_version
|
|
116
|
+
Native.version
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
# Free the scanner now rather than when it is collected.
|
|
120
|
+
def close
|
|
121
|
+
@mutex.synchronize do
|
|
122
|
+
@handle&.free
|
|
123
|
+
@handle = nil
|
|
124
|
+
end
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
def closed?
|
|
128
|
+
@handle.nil?
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
def inspect
|
|
132
|
+
"#<Malmal::Scanner policy=#{@options[:policy]}#{" closed" if closed?}>"
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
private
|
|
136
|
+
|
|
137
|
+
def build(json)
|
|
138
|
+
error = FFI::MemoryPointer.new(:pointer)
|
|
139
|
+
pointer = Native.malmal_scanner_new_json(json, error)
|
|
140
|
+
if pointer.null?
|
|
141
|
+
message = take_string(error.read_pointer) || "the scanner could not be created"
|
|
142
|
+
raise ArgumentError, message
|
|
143
|
+
end
|
|
144
|
+
Handle.new(pointer)
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def handle
|
|
148
|
+
@handle or raise ScanError, "the scanner is closed"
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def password_json(password)
|
|
152
|
+
text = password.to_s
|
|
153
|
+
return text if text.encoding != Encoding::BINARY && text.valid_encoding?
|
|
154
|
+
|
|
155
|
+
utf8 = text.dup.force_encoding(Encoding::UTF_8)
|
|
156
|
+
utf8.valid_encoding? ? utf8 : text.bytes
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
def read(data)
|
|
160
|
+
return data.b if data.is_a?(String)
|
|
161
|
+
|
|
162
|
+
if data.respond_to?(:read)
|
|
163
|
+
data.rewind if data.respond_to?(:rewind)
|
|
164
|
+
limit = (@options[:max_size] || (64 << 20)) + 1
|
|
165
|
+
bytes = data.read(limit) || +""
|
|
166
|
+
data.rewind if data.respond_to?(:rewind)
|
|
167
|
+
return bytes.b
|
|
168
|
+
end
|
|
169
|
+
raise TypeError, "scan takes a String or an IO, not #{data.class}"
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
# A NUL would end the C string early; it is dropped, as the C library
|
|
173
|
+
# would drop what follows it.
|
|
174
|
+
def claim(text)
|
|
175
|
+
text&.to_s&.delete("\0")
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
def with_input(bytes)
|
|
179
|
+
pointer = FFI::MemoryPointer.new(:uint8, [bytes.bytesize, 1].max)
|
|
180
|
+
pointer.put_bytes(0, bytes)
|
|
181
|
+
yield pointer
|
|
182
|
+
ensure
|
|
183
|
+
pointer&.free
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
def take_string(pointer)
|
|
187
|
+
return nil if pointer.null?
|
|
188
|
+
|
|
189
|
+
pointer.read_string.force_encoding(Encoding::UTF_8)
|
|
190
|
+
ensure
|
|
191
|
+
Native.malmal_string_free(pointer) unless pointer.null?
|
|
192
|
+
end
|
|
193
|
+
|
|
194
|
+
def take_bytes(pointer, length)
|
|
195
|
+
return nil if pointer.null?
|
|
196
|
+
|
|
197
|
+
pointer.read_bytes(length)
|
|
198
|
+
ensure
|
|
199
|
+
Native.malmal_bytes_free(pointer, length) unless pointer.null?
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
def sanitized(status, rebuilt, fields)
|
|
203
|
+
case status
|
|
204
|
+
when Native::CLEAN
|
|
205
|
+
raise ScanError, "the scanner failed; there is no rebuilt file" unless rebuilt
|
|
206
|
+
|
|
207
|
+
image = fields.fetch("image")
|
|
208
|
+
Sanitized.new(data: rebuilt, file_type: image.fetch("file_type"), width: image.fetch("width", 0),
|
|
209
|
+
height: image.fetch("height", 0), frames: image.fetch("frames", 1),
|
|
210
|
+
report: Report.from_h(fields.fetch("report")))
|
|
211
|
+
when Native::NOT_REBUILT
|
|
212
|
+
raise NotRebuilt, fields.fetch("error", "the file was not rebuilt")
|
|
213
|
+
when Native::SUSPICIOUS, Native::MALICIOUS
|
|
214
|
+
raise Rejected, Report.from_h(fields.fetch("report"))
|
|
215
|
+
else
|
|
216
|
+
raise ArgumentError, fields["error"] if fields["error"]
|
|
217
|
+
|
|
218
|
+
raise ScanError, "the scanner failed; the file was not scanned"
|
|
219
|
+
end
|
|
220
|
+
end
|
|
221
|
+
end
|
|
222
|
+
end
|
data/lib/malmal.rb
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "malmal/version"
|
|
4
|
+
require_relative "malmal/errors"
|
|
5
|
+
require_relative "malmal/report"
|
|
6
|
+
require_relative "malmal/native"
|
|
7
|
+
require_relative "malmal/scanner"
|
|
8
|
+
require_relative "malmal/client"
|
|
9
|
+
|
|
10
|
+
# Checks uploaded images, SVG, PDF and PostScript files before an
|
|
11
|
+
# application processes them. Anything but a clean report, including an
|
|
12
|
+
# exception, means the file is not accepted.
|
|
13
|
+
module Malmal
|
|
14
|
+
end
|
data/sig/malmal.rbs
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
module Malmal
|
|
2
|
+
VERSION: String
|
|
3
|
+
SEVERITIES: Array[Symbol]
|
|
4
|
+
|
|
5
|
+
type input = String | IO | StringIO
|
|
6
|
+
type verdict = :clean | :suspicious | :malicious
|
|
7
|
+
|
|
8
|
+
class Error < StandardError
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
class ScanError < Error
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
class SanitizeError < Error
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
class Rejected < SanitizeError
|
|
18
|
+
attr_reader report: Report
|
|
19
|
+
def initialize: (Report report) -> void
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
class NotRebuilt < SanitizeError
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
class LoadError < Error
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
class Finding
|
|
29
|
+
attr_accessor code: String
|
|
30
|
+
attr_accessor severity: Symbol
|
|
31
|
+
attr_accessor message: String
|
|
32
|
+
attr_accessor offset: Integer?
|
|
33
|
+
def self.from_h: (Hash[String, untyped] fields) -> Finding
|
|
34
|
+
def initialize: (?code: String, ?severity: Symbol, ?message: String, ?offset: Integer?) -> void
|
|
35
|
+
def to_h: () -> Hash[Symbol, untyped]
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
class Report
|
|
39
|
+
attr_reader verdict: verdict
|
|
40
|
+
attr_reader detected_type: Symbol
|
|
41
|
+
attr_reader declared_types: Array[Symbol]
|
|
42
|
+
attr_reader size: Integer
|
|
43
|
+
attr_reader sha256: String
|
|
44
|
+
attr_reader findings: Array[Finding]
|
|
45
|
+
def self.from_h: (Hash[String, untyped] fields) -> Report
|
|
46
|
+
def initialize: (verdict: verdict, detected_type: Symbol, ?declared_types: Array[Symbol],
|
|
47
|
+
?size: Integer, ?sha256: String, ?findings: Array[Finding]) -> void
|
|
48
|
+
def clean?: () -> bool
|
|
49
|
+
def suspicious?: () -> bool
|
|
50
|
+
def malicious?: () -> bool
|
|
51
|
+
def codes: () -> Array[String]
|
|
52
|
+
def to_h: () -> Hash[Symbol, untyped]
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
class Sanitized
|
|
56
|
+
CONTENT_TYPES: Hash[Symbol, String]
|
|
57
|
+
EXTENSIONS: Hash[Symbol, String]
|
|
58
|
+
attr_reader data: String
|
|
59
|
+
attr_reader file_type: Symbol
|
|
60
|
+
attr_reader width: Integer
|
|
61
|
+
attr_reader height: Integer
|
|
62
|
+
attr_reader frames: Integer
|
|
63
|
+
attr_reader report: Report
|
|
64
|
+
def initialize: (data: String, file_type: Symbol | String, report: Report, ?width: Integer, ?height: Integer,
|
|
65
|
+
?frames: Integer) -> void
|
|
66
|
+
def content_type: () -> String
|
|
67
|
+
def extension: () -> String
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
class Scanner
|
|
71
|
+
POLICIES: Array[Symbol]
|
|
72
|
+
LIMITS: Array[Symbol]
|
|
73
|
+
SANITIZE_OPTIONS: Array[Symbol]
|
|
74
|
+
DEFAULT_MAX_MEMORY: Integer
|
|
75
|
+
|
|
76
|
+
attr_reader options: Hash[Symbol, untyped]
|
|
77
|
+
|
|
78
|
+
def initialize: (?policy: Symbol | String, ?allow: Array[String] | String, ?types: Array[Symbol | String]?,
|
|
79
|
+
?hashlist: String?, ?pdf_passwords: Array[String], ?max_memory: Integer?,
|
|
80
|
+
?without_hash: bool, ?wait: Numeric?, ?max_size: Integer, ?max_decompressed: Integer,
|
|
81
|
+
?max_pixels: Integer, ?max_depth: Integer, ?scan_timeout: Numeric) -> void
|
|
82
|
+
def scan: (input data, ?filename: String?, ?content_type: String?) -> Report
|
|
83
|
+
def sanitize: (input data, ?filename: String?, ?content_type: String?, ?jpeg_quality: Integer?,
|
|
84
|
+
?types: Array[Symbol | String], ?pdf_dpi: Integer, ?pdf_jpeg: bool, ?pdf_text: bool,
|
|
85
|
+
?pdf_vector_text: bool) -> Sanitized
|
|
86
|
+
def overdue: () -> Integer
|
|
87
|
+
def library_version: () -> String
|
|
88
|
+
def close: () -> void
|
|
89
|
+
def closed?: () -> bool
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
class Client
|
|
93
|
+
attr_reader url: URI::Generic
|
|
94
|
+
|
|
95
|
+
def initialize: (String | URI::Generic url, ?token: String?, ?open_timeout: Numeric,
|
|
96
|
+
?read_timeout: Numeric) -> void
|
|
97
|
+
def scan: (input data, ?filename: String?, ?content_type: String?) -> Report
|
|
98
|
+
def sanitize: (input data, ?filename: String?, ?content_type: String?, ?types: Array[Symbol | String]?) -> Sanitized
|
|
99
|
+
def healthy?: () -> bool
|
|
100
|
+
end
|
|
101
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: malmal
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.4.0
|
|
5
|
+
platform: x86_64-linux-gnu
|
|
6
|
+
authors:
|
|
7
|
+
- nguyenthuan155632
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 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.16'
|
|
19
|
+
type: :runtime
|
|
20
|
+
prerelease: false
|
|
21
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
22
|
+
requirements:
|
|
23
|
+
- - "~>"
|
|
24
|
+
- !ruby/object:Gem::Version
|
|
25
|
+
version: '1.16'
|
|
26
|
+
description: |
|
|
27
|
+
Checks uploaded files before your application processes them: whether the content is
|
|
28
|
+
what the name and Content-Type claim, whether it carries active content (scripts,
|
|
29
|
+
actions, embedded files, shell commands), and whether it is well formed. It can also
|
|
30
|
+
rebuild an image, SVG or PDF from what it draws. A file that cannot be analyzed
|
|
31
|
+
completely is never reported clean.
|
|
32
|
+
executables: []
|
|
33
|
+
extensions: []
|
|
34
|
+
extra_rdoc_files: []
|
|
35
|
+
files:
|
|
36
|
+
- LICENSE-APACHE
|
|
37
|
+
- LICENSE-MIT
|
|
38
|
+
- README.md
|
|
39
|
+
- lib/malmal.rb
|
|
40
|
+
- lib/malmal/client.rb
|
|
41
|
+
- lib/malmal/errors.rb
|
|
42
|
+
- lib/malmal/libmalmal_ffi.so
|
|
43
|
+
- lib/malmal/native.rb
|
|
44
|
+
- lib/malmal/report.rb
|
|
45
|
+
- lib/malmal/scanner.rb
|
|
46
|
+
- lib/malmal/version.rb
|
|
47
|
+
- sig/malmal.rbs
|
|
48
|
+
homepage: https://github.com/nguyenthuan155632/malmal
|
|
49
|
+
licenses:
|
|
50
|
+
- MIT
|
|
51
|
+
- Apache-2.0
|
|
52
|
+
metadata:
|
|
53
|
+
homepage_uri: https://github.com/nguyenthuan155632/malmal
|
|
54
|
+
source_code_uri: https://github.com/nguyenthuan155632/malmal/tree/main/bindings/ruby/malmal
|
|
55
|
+
changelog_uri: https://github.com/nguyenthuan155632/malmal/blob/main/CHANGELOG.md
|
|
56
|
+
bug_tracker_uri: https://github.com/nguyenthuan155632/malmal/issues
|
|
57
|
+
rubygems_mfa_required: 'true'
|
|
58
|
+
rdoc_options: []
|
|
59
|
+
require_paths:
|
|
60
|
+
- lib
|
|
61
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
62
|
+
requirements:
|
|
63
|
+
- - ">="
|
|
64
|
+
- !ruby/object:Gem::Version
|
|
65
|
+
version: '3.2'
|
|
66
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
67
|
+
requirements:
|
|
68
|
+
- - ">="
|
|
69
|
+
- !ruby/object:Gem::Version
|
|
70
|
+
version: '0'
|
|
71
|
+
requirements: []
|
|
72
|
+
rubygems_version: 3.6.9
|
|
73
|
+
specification_version: 4
|
|
74
|
+
summary: Upload scanner for images, SVG, PDF and PostScript files
|
|
75
|
+
test_files: []
|