fluent-plugin-sdns-api 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ed83d441568fce83f35bcadfa0fea53fdafccc7a274588344eb4ace99b094d14
4
+ data.tar.gz: 0ce35035202fc91bed7cc957fbacc596aedb120046ad1059f164f3216ed6582b
5
+ SHA512:
6
+ metadata.gz: 1c998e2331bf12c4d78deab97db0a86fbaa303924c80c485ba70d6711b4ec1a924913d5f20b2a7d1bffed54f3c586b18b00d9788c5c8a00f0fb39d60dcb0029b
7
+ data.tar.gz: 9d09a0533a41fea12df19815c3361858486419a18711e4c6995c2efec2d66af614ef8ee007ac5ea9bdf65f5c8cbeadf7f300ff8ff26c4d145ccef565292de5b5
data/.gitignore ADDED
@@ -0,0 +1,3 @@
1
+ *.lock
2
+ vendor
3
+ pkg
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,51 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ fluent-plugin-sdns-api (0.1.0)
5
+ fluentd (>= 0.14.10, < 2)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ concurrent-ruby (1.2.2)
11
+ cool.io (1.8.0)
12
+ fluentd (1.16.3)
13
+ bundler
14
+ cool.io (>= 1.4.5, < 2.0.0)
15
+ http_parser.rb (>= 0.5.1, < 0.9.0)
16
+ msgpack (>= 1.3.1, < 2.0.0)
17
+ serverengine (>= 2.3.2, < 3.0.0)
18
+ sigdump (~> 0.2.5)
19
+ strptime (>= 0.2.4, < 1.0.0)
20
+ tzinfo (>= 1.0, < 3.0)
21
+ tzinfo-data (~> 1.0)
22
+ webrick (~> 1.4)
23
+ yajl-ruby (~> 1.0)
24
+ http_parser.rb (0.8.0)
25
+ msgpack (1.7.2)
26
+ power_assert (2.0.3)
27
+ rake (13.1.0)
28
+ serverengine (2.3.2)
29
+ sigdump (~> 0.2.2)
30
+ sigdump (0.2.5)
31
+ strptime (0.2.5)
32
+ test-unit (3.6.1)
33
+ power_assert
34
+ tzinfo (2.0.6)
35
+ concurrent-ruby (~> 1.0)
36
+ tzinfo-data (1.2023.3)
37
+ tzinfo (>= 1.0.0)
38
+ webrick (1.8.1)
39
+ yajl-ruby (1.4.3)
40
+
41
+ PLATFORMS
42
+ x86_64-linux
43
+
44
+ DEPENDENCIES
45
+ bundler (~> 2.4.10)
46
+ fluent-plugin-sdns-api!
47
+ rake (~> 13.1.0)
48
+ test-unit (~> 3.6.1)
49
+
50
+ BUNDLED WITH
51
+ 2.4.10
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,49 @@
1
+ # fluent-plugin-sdns-api
2
+
3
+ [Fluentd](https://fluentd.org/) input plugin to do something.
4
+
5
+ sdns-api is a fluentd input plugin to do something.
6
+
7
+ ## Installation
8
+
9
+ ### Fluentd
10
+
11
+ ```shell
12
+ fluent-gem install fluent-plugin-sdns-api
13
+ ```
14
+
15
+ ### td-agent
16
+
17
+ ```shell
18
+ td-agent-gem install fluent-plugin-sdns-api
19
+ ```
20
+
21
+ ### Bundler
22
+
23
+ Add following line to your Gemfile:
24
+
25
+ ```ruby
26
+ gem "fluent-plugin-sdns-api"
27
+ ```
28
+
29
+ And then execute:
30
+
31
+ ```shell
32
+ bundle
33
+ ```
34
+
35
+ ## Configuration
36
+
37
+ You can generate configuration template:
38
+
39
+ ```shell
40
+ fluent-plugin-config-format input sdns-api
41
+ ```
42
+
43
+ You can copy and paste generated documents here.
44
+
45
+ ## Copyright
46
+
47
+ * Copyright(c) 2023- yinqiwei
48
+ * License
49
+ * Apache License, Version 2.0
data/Rakefile ADDED
@@ -0,0 +1,13 @@
1
+ require "bundler"
2
+ Bundler::GemHelper.install_tasks
3
+
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs.push("lib", "test")
8
+ t.test_files = FileList["test/**/test_*.rb"]
9
+ t.verbose = true
10
+ t.warning = true
11
+ end
12
+
13
+ task default: [:test]
@@ -0,0 +1,27 @@
1
+ lib = File.expand_path("../lib", __FILE__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+
4
+ Gem::Specification.new do |spec|
5
+ spec.name = "fluent-plugin-sdns-api"
6
+ spec.version = "0.1.1"
7
+ spec.authors = ["yinqiwei"]
8
+ spec.email = ["772006843@qq.com"]
9
+
10
+ spec.summary = %q{Input Plugin for Fluentd.}
11
+ spec.description = %q{Input Plugin for Fluentd.}
12
+ spec.homepage = "https://github.com/meimeitou/fluent-plugin-sdns-api"
13
+ spec.license = "Apache-2.0"
14
+
15
+ test_files, files = `git ls-files -z`.split("\x0").partition do |f|
16
+ f.match(%r{^(test|spec|features)/})
17
+ end
18
+ spec.files = files
19
+ spec.executables = files.grep(%r{^bin/}) { |f| File.basename(f) }
20
+ spec.test_files = test_files
21
+ spec.require_paths = ["lib"]
22
+
23
+ spec.add_development_dependency "bundler", "~> 2.4.10"
24
+ spec.add_development_dependency "rake", "~> 13.1.0"
25
+ spec.add_development_dependency "test-unit", "~> 3.6.1"
26
+ spec.add_runtime_dependency "fluentd", [">= 0.14.10", "< 2"]
27
+ end
@@ -0,0 +1,188 @@
1
+ #
2
+ # Copyright 2023- yinqiwei
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ require 'uri'
17
+ require 'net/http'
18
+ require 'openssl'
19
+ require 'base64'
20
+ require 'date'
21
+ require 'cgi'
22
+
23
+ module Fluent
24
+ module Plugin
25
+ module SdnsApiSinger
26
+ Algorithm = "SDK-HMAC-SHA256"
27
+ BasicDateFormat = "%Y%m%dT%H%M%SZ"
28
+ HeaderXDate = "X-Sdk-Date"
29
+ HeaderHost = "host"
30
+ HeaderAuthorization = "Authorization"
31
+ HeaderContentSha256 = "x-sdk-content-sha256"
32
+
33
+ class HttpRequest
34
+ attr_accessor :method, :scheme, :host, :uri, :query, :headers, :body
35
+
36
+ def initialize(method = "", url = "", headers = nil, body = "")
37
+ @method = method
38
+ uri_parse=URI.parse(url)
39
+
40
+ spl = url.split("://", 2)
41
+ @scheme = 'http'
42
+ if spl.length > 1
43
+ @scheme = spl[0]
44
+ url = spl[1]
45
+ end
46
+ @query = {}
47
+ if uri_parse.query
48
+ @query = CGI.parse(uri_parse.query)
49
+ end
50
+ @host = uri_parse.host
51
+ @uri = uri_parse.path
52
+ @headers = headers.nil? ? {} : headers.dup
53
+ @body = body.encode('utf-8')
54
+ end
55
+ end
56
+
57
+ class Signer
58
+ attr_accessor :key, :secret
59
+
60
+ def initialize
61
+ @key = ""
62
+ @secret = ""
63
+ end
64
+
65
+ def hmacsha256(key_byte, message)
66
+ OpenSSL::HMAC.digest('sha256', key_byte, message)
67
+ end
68
+
69
+ def hex_encode_sha256_hash(data)
70
+ Digest::SHA256.hexdigest(data)
71
+ end
72
+
73
+ def string_to_sign(canonical_request, t)
74
+ bytes = hex_encode_sha256_hash(canonical_request)
75
+ "#{Algorithm}\n#{t.strftime(BasicDateFormat)}\n#{bytes}"
76
+ end
77
+
78
+ def url_encode(s)
79
+ CGI.escape(s).gsub('+', '%20')
80
+ end
81
+
82
+ def canonical_request(r, signed_headers)
83
+ canonical_headers = canonical_headers(r, signed_headers)
84
+ hexencode = find_header(r, HeaderContentSha256)
85
+ if hexencode.nil?
86
+ hexencode = hex_encode_sha256_hash(r.body)
87
+ end
88
+ "#{r.method.upcase}\n#{canonical_uri(r)}\n#{canonical_query_string(r)}\n#{canonical_headers}\n#{signed_headers.join(';')}\n#{hexencode}"
89
+ end
90
+
91
+ def canonical_uri(r)
92
+ patterns = CGI.unescape(r.uri).split('/')
93
+ uri = patterns.map { |v| url_encode(v) }
94
+ url_path = uri.join('/')
95
+ url_path += '/' unless url_path[-1] == '/'
96
+ url_path
97
+ end
98
+
99
+ def canonical_query_string(r)
100
+ keys = r.query.keys.sort
101
+ keys.map do |key|
102
+ k = url_encode(key)
103
+ value = r.query[key]
104
+ if value.is_a?(Array)
105
+ value.sort.map { |v| "#{k}=#{url_encode(v.to_s)}" }
106
+ else
107
+ "#{k}=#{url_encode(value.to_s)}"
108
+ end
109
+ end.join('&')
110
+ end
111
+
112
+ def canonical_headers(r, signed_headers)
113
+ a = []
114
+ headers = {}
115
+ r.headers.each do |key, value|
116
+ key_encoded = key.downcase
117
+ value_encoded = value.strip
118
+ headers[key_encoded] = value_encoded
119
+ r.headers[key] = value_encoded.encode('utf-8').force_encoding('iso-8859-1')
120
+ end
121
+ signed_headers.each { |key| a << "#{key}:#{headers[key]}" }
122
+ "#{a.join("\n")}\n"
123
+ end
124
+
125
+ def canonical_headers(r, signed_headers)
126
+ headers = r.headers.transform_keys(&:downcase)
127
+ signed_headers.map { |key| "#{key}:#{headers[key]}" }.join("\n") + "\n"
128
+ end
129
+
130
+ def signed_headers(r)
131
+ r.headers.keys.map(&:downcase).sort
132
+ end
133
+
134
+ def sign_string_to_sign(string_to_sign, signing_key)
135
+ hm = hmacsha256(signing_key, string_to_sign)
136
+ hm.unpack1('H*')
137
+ end
138
+
139
+ def auth_header_value(signature, app_key, signed_headers)
140
+ "#{Algorithm} Access=#{app_key}, SignedHeaders=#{signed_headers.join(';')}, Signature=#{signature}"
141
+ end
142
+
143
+ def find_header(r, header)
144
+ r.headers.each do |k, v|
145
+ return v if k.downcase == header.downcase
146
+ end
147
+ nil
148
+ end
149
+
150
+ def verify(r, authorization)
151
+ r.body = r.body.encode('UTF-8') if r.body.is_a?(String)
152
+ header_time = find_header(r, HeaderXDate)
153
+ return false if header_time.nil?
154
+
155
+ t = DateTime.strptime(header_time, BasicDateFormat)
156
+ signed_headers = signed_headers(r)
157
+ canonical_request = canonical_request(r, signed_headers)
158
+ string_to_sign = string_to_sign(canonical_request, t)
159
+ authorization == sign_string_to_sign(string_to_sign, @secret)
160
+ end
161
+
162
+ def sign(r)
163
+ r.body = r.body.encode('UTF-8') if r.body.is_a?(String)
164
+ header_time = find_header(r, HeaderXDate)
165
+ if header_time.nil?
166
+ t = DateTime.now
167
+ r.headers[HeaderXDate] = t.strftime(BasicDateFormat)
168
+ else
169
+ t = DateTime.strptime(header_time, BasicDateFormat)
170
+ end
171
+
172
+ unless r.headers.keys.any? { |key| key.downcase == 'host' }
173
+ r.headers["host"] = r.host
174
+ end
175
+ signed_headers = signed_headers(r)
176
+ canonical_request = canonical_request(r, signed_headers)
177
+ string_to_sign = string_to_sign(canonical_request, t)
178
+ signature = sign_string_to_sign(string_to_sign, @secret)
179
+ auth_value = auth_header_value(signature, @key, signed_headers)
180
+ r.headers[HeaderAuthorization] = auth_value
181
+ r.headers["content-length"] = r.body.length.to_s
182
+ query_string = canonical_query_string(r)
183
+ r.uri += "?#{query_string}" unless query_string.empty?
184
+ end
185
+ end
186
+ end
187
+ end
188
+ end
@@ -0,0 +1,198 @@
1
+ #
2
+ # Copyright 2023- yinqiwei
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ require "fluent/plugin/input"
17
+ require "fluent/plugin/aksk/signer"
18
+ require 'uri'
19
+ require 'cgi'
20
+ require 'json'
21
+
22
+ module Fluent
23
+ module Plugin
24
+ class SdnsApiListThreatDetailInput < Fluent::Plugin::Input
25
+ attr_accessor :query_end_time, :query_start_time
26
+
27
+ Fluent::Plugin.register_input("sdns_api", self)
28
+
29
+ helpers :timer
30
+
31
+ desc "Tag string"
32
+ config_param :tag, :string, default: nil
33
+
34
+ desc "Interval secends to pull SDNS API. default: 600"
35
+ config_param :scrape_interval, :time, default: 600
36
+
37
+ desc "SDNS API endpoint."
38
+ config_param :endpoint, :string, default: ""
39
+
40
+ desc "SDNS API params page_size. 20/50/100, default: 100"
41
+ config_param :page_size, :integer, default: 100
42
+
43
+ desc "SDNS API params client_ip: 资产ip地址"
44
+ config_param :client_ip, :string, default: "" # 资产ip地址
45
+
46
+ desc "SDNS API params security_zone_id: 安全域" # 安全域
47
+ config_param :security_zone_id, :string, default: ""
48
+
49
+ desc "SDNS API params domain: 域名" # 域名
50
+ config_param :domain, :string, default: ""
51
+
52
+ desc "SDNS API params threat_level: 威胁等级(low/middle/high/critical),默认值:所有" # 威胁等级
53
+ config_param :threat_level, :array, default: [], value_type: :string
54
+
55
+ desc "SDNS API key."
56
+ config_param :access_key, :string, default: ""
57
+
58
+ desc "SDNS API secret."
59
+ config_param :access_secret, :string, default: ""
60
+
61
+ def configure(conf)
62
+ super
63
+ if @access_key == ""
64
+ raise Fluent::ConfigError, "access_key is required"
65
+ end
66
+ if @access_secret == ""
67
+ raise Fluent::ConfigError, "access_secret is required"
68
+ end
69
+ if @endpoint == ""
70
+ raise Fluent::ConfigError, "endpoint is required"
71
+ end
72
+ if @scrape_interval < 60
73
+ raise Fluent::ConfigError, "scrape_interval must be greater than 60"
74
+ end
75
+ @query_start_time = (Time.now.to_i - @scrape_interval).to_i
76
+ $log.info("sdns api query start time: #{@query_start_time}")
77
+ end
78
+
79
+ def start
80
+ super
81
+ # Startup code goes here!
82
+ $log.info("sdns api start")
83
+ # run inmediately
84
+ refresh_watchers()
85
+ timer_execute(:execute_sdns_api, @scrape_interval, &method(:refresh_watchers))
86
+ end
87
+
88
+ def get_full_url(start_time, end_time, cur_page)
89
+ uri_parse = URI.parse(@endpoint)
90
+ query = CGI.parse(uri_parse.query ? uri_parse.query : "")
91
+ query["time_start"] = start_time
92
+ query["time_end"] = end_time
93
+ query["cur_page"] = cur_page
94
+ query["page_size"] = @page_size
95
+ query["domain"] = @domain if @domain != ""
96
+ query["client_ip"] = @client_ip if @client_ip != ""
97
+ query["security_zone_id"] = @security_zone_id if @security_zone_id != ""
98
+ query["threat_level"] = @threat_level if @threat_level.length > 0
99
+
100
+ uri_parse.query = URI.encode_www_form(query)
101
+ uri_parse.to_s
102
+ end
103
+
104
+ def refresh_watchers
105
+ begin
106
+ cur_page = 1
107
+ start_time = @query_start_time
108
+ end_time = Time.now.to_i
109
+
110
+ @query_start_time = end_time # set next query start time
111
+ $log.debug("sdns api query time duration: #{start_time} - #{end_time}")
112
+ full_url = get_full_url(start_time, end_time, cur_page)
113
+ $log.debug("sdns api query: #{full_url}")
114
+ res = get_sdns_api_data(full_url)
115
+ if res.nil?
116
+ return
117
+ end
118
+ $log.info("sdns api query result total: #{res['data']['total']}")
119
+ send_msg(res['data']['items'])
120
+ for cur_page in 2..res['data']['total_pages'] do
121
+ full_url = get_full_url(start_time, end_time, cur_page)
122
+ $log.debug("sdns api query: #{full_url}")
123
+ res = get_sdns_api_data(full_url)
124
+ if res.nil?
125
+ return
126
+ end
127
+ # puts res['data']['cur_page']
128
+ send_msg(res['data']['items'])
129
+ end
130
+ rescue => e
131
+ $log.error(e.message)
132
+ end
133
+ end
134
+
135
+ def send_msg(items)
136
+ begin
137
+ for item in items do
138
+ record = {
139
+ "query_timestamp" => item["query_timestamp"],
140
+ "query_time_format" => item["query_time_format"],
141
+ "security_zone_id" => item["security_zone_id"],
142
+ "security_zone_name" => item["security_zone_name"],
143
+ "client_ip" => item["client_ip"],
144
+ "client_port" => item["client_port"],
145
+ "domain" => item["domain"],
146
+ "query_type" => item["query_type"],
147
+ "action" => item["action"],
148
+ "threat_level" => item["threat_level"],
149
+ "threat_type" => item["threat_type"],
150
+ "event_id" => item["event_id"],
151
+ "event_name" => item["event_name"],
152
+ "event_description" => item["event_description"].gsub("\n", '\\n').gsub("\t", '\\t'),
153
+ }
154
+ es = OneEventStream.new(Fluent::EventTime.now, record)
155
+ router.emit_stream(@tag, es)
156
+ end
157
+ rescue => e
158
+ $log.error(e.message)
159
+ end
160
+ end
161
+
162
+ def get_sdns_api_data(full_url)
163
+ begin
164
+ sig = SdnsApiSinger::Signer.new
165
+ sig.key = @access_key
166
+ sig.secret = @access_secret
167
+
168
+ r = SdnsApiSinger::HttpRequest.new("GET", full_url)
169
+ r.headers = {"content-type" => "application/json"}
170
+ r.body = ''
171
+ sig.sign(r)
172
+ uri = URI.parse("#{r.scheme}://#{r.host}#{r.uri}")
173
+ http = Net::HTTP.new(uri.host, uri.port)
174
+ http.use_ssl = true if uri.scheme == 'https'
175
+ request = Net::HTTP::Get.new(uri)
176
+ request.initialize_http_header(r.headers)
177
+ response = http.request(request)
178
+ if response.code != "200"
179
+ $log.error("sdns api query failed: #{response.code} #{response.message}")
180
+ return
181
+ end
182
+ response_body_hash = JSON.parse(response.body)
183
+ if response_body_hash["errno"] != 0
184
+ $log.error("sdns api query failed: #{response_body_hash["errno"]} #{response_body_hash["errmsg"]}")
185
+ return
186
+ end
187
+ response_body_hash
188
+ rescue => e
189
+ $log.error(e.message)
190
+ end
191
+ end
192
+
193
+ def shutdown
194
+ super
195
+ end
196
+ end
197
+ end
198
+ end
data/test/helper.rb ADDED
@@ -0,0 +1,7 @@
1
+ require "test-unit"
2
+ require "fluent/test"
3
+ require "fluent/test/driver/input"
4
+ require "fluent/test/helpers"
5
+
6
+ Test::Unit::TestCase.include(Fluent::Test::Helpers)
7
+ Test::Unit::TestCase.extend(Fluent::Test::Helpers)
@@ -0,0 +1,30 @@
1
+ require "helper"
2
+ require "fluent/plugin/aksk/signer.rb"
3
+ require 'net/http'
4
+ require 'resolv-replace'
5
+ require 'uri'
6
+
7
+ class SdnsApiSignerTest < Test::Unit::TestCase
8
+
9
+ def test_sdns_api_signer
10
+ sig = Fluent::Plugin::SdnsApiSinger::Signer.new
11
+ sig.key = "Fad3mbhh9NwadtEd7t0ekFp5HwrNJiDc" # test key
12
+ sig.secret = "5MLR15LYGn8IeTHQwPs7tZyJslGqNZmYI6g8eHETGrWZYZ6J7U9Ak8CrRlSyCEMT"
13
+
14
+ r = Fluent::Plugin::SdnsApiSinger::HttpRequest.new("GET", "https://api-fake.dns.qihoo.net/apis/grpc/v2/ListThreatDetail")
15
+ r.headers = {"content-type" => "application/json"}
16
+
17
+ r.body = ''
18
+ sig.sign(r)
19
+ puts r.headers["X-Sdk-Date"]
20
+ puts r.headers["Authorization"]
21
+
22
+ uri = URI.parse("#{r.scheme}://#{r.host}#{r.uri}")
23
+ http = Net::HTTP.new(uri.host, uri.port)
24
+ http.use_ssl = true if uri.scheme == 'https'
25
+ request = Net::HTTP::Get.new(uri)
26
+ request.initialize_http_header(r.headers)
27
+ response = http.request(request)
28
+ assert response.code == "200"
29
+ end
30
+ end
@@ -0,0 +1,78 @@
1
+ require "helper"
2
+ require "fluent/plugin/in_sdns_api.rb"
3
+
4
+ class SdnsApiListThreatDetailInputTest < Test::Unit::TestCase
5
+ setup do
6
+ Fluent::Test.setup
7
+ end
8
+
9
+ # Default configuration for tests
10
+ CONFIG = %[
11
+ client_ip '1.1.1.1'
12
+ access_key 'xxx'
13
+ endpoint 'https://api-fake.dns.qihoo.net/apis/grpc/v2/ListThreatDetail'
14
+ access_secret 'sdf'
15
+ ]
16
+
17
+ sub_test_case 'configured with configurations' do
18
+ test 'param1 should reject too short string' do
19
+ assert_raise Fluent::ConfigError do
20
+ create_driver(%[
21
+ param1 a
22
+ ])
23
+ end
24
+ end
25
+
26
+ test 'param is set correctly' do
27
+ d = create_driver(CONFIG)
28
+ assert_equal('', d.instance.domain)
29
+ assert_not_nil(d.instance.endpoint)
30
+ assert_not_nil(d.instance.query_start_time)
31
+ # puts d.instance.get_full_url(d.instance.query_start_time, d.instance.query_end_time, 1)
32
+ end
33
+ end
34
+
35
+ sub_test_case 'api watcher' do
36
+ test 'get api data' do
37
+ d = create_driver(%[
38
+ access_key 'L2guCE9mRsuvUhNxUDKfgjKR083RqIFB'
39
+ access_secret 'Vy4HrnHHZdewCkeQ9pHeiN6repMUgzjeoP2mqzMCVY2Hbne0k4jlKzZ10unYIKo5'
40
+ endpoint 'https://api-fake.dns.qihoo.net/apis/grpc/v2/ListThreatDetail'
41
+ page_size 20
42
+ scrape_interval 600
43
+ ])
44
+ assert_equal(600, d.instance.scrape_interval)
45
+ start_time = d.instance.query_start_time
46
+ end_time = Time.now.to_i
47
+ full_url = d.instance.get_full_url(start_time, end_time , 1)
48
+ res = d.instance.get_sdns_api_data(full_url)
49
+ assert_not_nil(res)
50
+ end
51
+ end
52
+
53
+ sub_test_case 'plugin will emit some events' do
54
+ test 'test expects plugin emits events 4 times' do
55
+ d = create_driver(%[
56
+ access_key 'L2guCE9mRsuvUhNxUDKfgjKR083RqIFB'
57
+ access_secret 'Vy4HrnHHZdewCkeQ9pHeiN6repMUgzjeoP2mqzMCVY2Hbne0k4jlKzZ10unYIKo5'
58
+ endpoint 'https://api-fake.dns.qihoo.net/apis/grpc/v2/ListThreatDetail'
59
+ page_size 100
60
+ scrape_interval 600
61
+ ])
62
+
63
+ # or 10 seconds lapse.
64
+ # d.run(expect_emits: 4, timeout: 10)
65
+ d.instance.refresh_watchers()
66
+
67
+ # An array of `[tag, time, record]`
68
+ puts d.events
69
+ assert_not_nil(d.events)
70
+ end
71
+ end
72
+
73
+ private
74
+
75
+ def create_driver(conf)
76
+ Fluent::Test::Driver::Input.new(Fluent::Plugin::SdnsApiListThreatDetailInput).configure(conf)
77
+ end
78
+ end
metadata ADDED
@@ -0,0 +1,120 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: fluent-plugin-sdns-api
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - yinqiwei
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2023-11-29 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 2.4.10
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 2.4.10
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 13.1.0
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 13.1.0
41
+ - !ruby/object:Gem::Dependency
42
+ name: test-unit
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: 3.6.1
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: 3.6.1
55
+ - !ruby/object:Gem::Dependency
56
+ name: fluentd
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 0.14.10
62
+ - - "<"
63
+ - !ruby/object:Gem::Version
64
+ version: '2'
65
+ type: :runtime
66
+ prerelease: false
67
+ version_requirements: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: 0.14.10
72
+ - - "<"
73
+ - !ruby/object:Gem::Version
74
+ version: '2'
75
+ description: Input Plugin for Fluentd.
76
+ email:
77
+ - 772006843@qq.com
78
+ executables: []
79
+ extensions: []
80
+ extra_rdoc_files: []
81
+ files:
82
+ - ".gitignore"
83
+ - Gemfile
84
+ - Gemfile.lock
85
+ - LICENSE
86
+ - README.md
87
+ - Rakefile
88
+ - fluent-plugin-sdns-api.gemspec
89
+ - lib/fluent/plugin/aksk/signer.rb
90
+ - lib/fluent/plugin/in_sdns_api.rb
91
+ - test/helper.rb
92
+ - test/plugin/test_aksk_signer.rb
93
+ - test/plugin/test_in_sdns_api.rb
94
+ homepage: https://github.com/meimeitou/fluent-plugin-sdns-api
95
+ licenses:
96
+ - Apache-2.0
97
+ metadata: {}
98
+ post_install_message:
99
+ rdoc_options: []
100
+ require_paths:
101
+ - lib
102
+ required_ruby_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: '0'
107
+ required_rubygems_version: !ruby/object:Gem::Requirement
108
+ requirements:
109
+ - - ">="
110
+ - !ruby/object:Gem::Version
111
+ version: '0'
112
+ requirements: []
113
+ rubygems_version: 3.4.10
114
+ signing_key:
115
+ specification_version: 4
116
+ summary: Input Plugin for Fluentd.
117
+ test_files:
118
+ - test/helper.rb
119
+ - test/plugin/test_aksk_signer.rb
120
+ - test/plugin/test_in_sdns_api.rb