ovh_dnsup 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e1ac8b726a44dd4004ac71fc04ce7933329500d8b506647cb8c6d51758853b08
4
+ data.tar.gz: 4957373f5151ad11041ccc39e9308d1c699e0e04cc76fb92e36f25fce28ba086
5
+ SHA512:
6
+ metadata.gz: 0a70d7dcbb1aed2ae47e6300e525851a5d30402e8d0bbef24ef6dbecf7c03296bb8c232e1dd8e30db45df044be1d1367a85da1eb80f448ea8ea64df7cccfc8d2
7
+ data.tar.gz: 00b6ec721be8a9e0319e605fb8d6be7c10fa778231cc36705eef6f636d55279b943ae660e52386f1ad7b511ad6c324c400b581b8c221735bc31965860ab9baf0
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ /vendor
10
+
11
+ # Vim Swap
12
+ *.swp
data/Gemfile ADDED
@@ -0,0 +1,2 @@
1
+ source "https://rubygems.org"
2
+ gemspec
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.
@@ -0,0 +1,127 @@
1
+ # OvhDnsup - Dynamic DNS for IPv6
2
+
3
+ This software enables you to safely update DNS zone entries hosted by OVH. As of January 2021, OVH does not allow dynamic DNS (DynDNS) updates for IPv6 addresses when using their DynHost protocol. This software provides a work-around for this limitation by using the OVH API to perform this task. Security is ensured by generating a DNS-entry-specific access token, which can only be used to update the corresponding entry. Hence, if this token is stolen the possible damage is limited.
4
+
5
+ This client also supports IPv4, however, in this case you probably want to use OVH's DynHost feature.
6
+
7
+ ## Installation
8
+
9
+ Either clone or download this repository and execute (after installing [Bundler](https://bundler.io/)):
10
+
11
+ $ bundle install
12
+
13
+ Or install it yourself by running:
14
+
15
+ $ gem install ovh_dnsup
16
+
17
+ You might want to add the `--user-install` flag to install into your home directory.
18
+
19
+ ## Quick Start
20
+
21
+ This section describes how to setup OvhDnsup to dynamically update a domain. We shall use `dynamic.example.com` as an example. You have to replace the domain `example.com` and the hostname `dynamic` according to your needs.
22
+
23
+ First, you need to register the application with the OVH API. Enter
24
+
25
+ $ ovh_dnsup register
26
+
27
+ (without the dollar sign) into a console, which will start the registration process. Follow the instructions on the screen.
28
+
29
+ Next, you need to login:
30
+
31
+ $ ovh_dnsup login
32
+
33
+ Again, follow the instructions. This login will request access to a few API functions, which are needed for the management of the dynamic hosts. We can, however, later drop these privileges to ensure security.
34
+
35
+ Now, you have to request the an authorization token for the domain update. Note, *the A and/or AAAA record need to be created first in the OVH customer center!* When the subdomain is created, execute:
36
+
37
+ $ ovh_dnsup authorize example.com dynamic dynamic_example_com.token
38
+
39
+ After following the instructions on the screen, you have created a file `dynamic_example_com.token` which contains the authorization information to update the hostname. The file is restricted to updating only the hostname you have authorized. Note, you can inspect and manage all authorizations using the `ovh_dnsup sessions` command. Furthermore, make sure to grant access for the time period that you want to perform updates in.
40
+
41
+ Updating the IP address can be done essentially in two ways. You can set the IP address manually by executing:
42
+
43
+ $ ovh_dnsup update --ip 2001:db8::abcd dynamic_example_com.token
44
+
45
+ You can also use an interface name to update the IP address:
46
+
47
+ $ ovh_dnsup update --if eth0 --daemon dynamic_example_com.token
48
+
49
+ The `--daemon` option instructs OvhDnsup to periodically check if the IP of the interface has changed and in this case to update the hostname.
50
+
51
+ When you have convinced yourself that your setup is working, you can run the command
52
+
53
+ $ ovh_dnsup logout
54
+
55
+ to log out from the management interface. From now on, only DNS updates are possible using the corresponding token files. (You can, of course, re-login at any time.)
56
+
57
+ ## Usage
58
+
59
+ In general, you use OvhDnsup by executing:
60
+
61
+ $ ovh_dnsup command [arguments...]
62
+
63
+ The following commands are possible
64
+
65
+ | Command | Description |
66
+ | :--- | :--- |
67
+ | register | Register application with the API. |
68
+ | unregister | Unregister (the) application(s). |
69
+ | login | Login to manage the DNS updaters. |
70
+ | logout | Logout. |
71
+ | list | List a DNS zone. |
72
+ | authorize | Authorize a DNS updater. |
73
+ | update | Perform DNS updates. |
74
+ | sessions | List all authorized updaters. |
75
+ | interfaces | List the local network interfaces. |
76
+
77
+ For more information on the individual commands run:
78
+
79
+ $ ovh_dnsup command --help
80
+
81
+ ## Running as a Service
82
+
83
+ ### Linux with Systemd
84
+
85
+ The following commands need to be executed as root. First, create a service user.
86
+
87
+ useradd --system ovh_dnsup
88
+
89
+ Then, save the token file as `/etc/ovh_dnsup.token` and execute
90
+
91
+ $ chown ovh_dnsup /etc/ovh_dnsup.token
92
+ $ chmod 700 /etc/ovh_dnsup.token
93
+
94
+ to set the right permissions. Afterwards, create a service file:
95
+
96
+ $ cat > /etc/systemd/system/ovh_dnsup.service << EOF
97
+ [Unit]
98
+ Description=Update OVH DNS
99
+
100
+ [Service]
101
+ User=ovh_dnsup
102
+ Group=nogroup
103
+ ExecStart=sh -c '/usr/local/bin/ovh_dnsup update \$(cat /etc/ovh_dnsup.conf) --daemon /etc/ovh_dnsup.token'
104
+
105
+ [Install]
106
+ WantedBy=multi-user.target
107
+ EOF
108
+
109
+ Set you configuration by executing
110
+
111
+ $ echo "--if=eth0" > /etc/ovh_dnsup.conf
112
+
113
+ where you replace the `eth0` by the interface of your choice.
114
+
115
+ You can now start and enable the service by
116
+
117
+ systemctl start ovh_dnsup.service
118
+ systemctl enable ovh_dnsup.service
119
+
120
+ ## Development
121
+
122
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
123
+
124
+ ## Contributing
125
+
126
+ Bug reports and pull requests are welcome on GitHub at https://github.com/hrittich/ovh_dnsup.
127
+
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "ovh_dnsup"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'ovh_dnsup'
4
+ OvhDnsup::Cli.run()
@@ -0,0 +1,22 @@
1
+ # Copyright 2021 Hannah Rittich
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ require_relative 'ovh_dnsup/version'
16
+ require_relative 'ovh_dnsup/domain_manager'
17
+ require_relative 'ovh_dnsup/cli'
18
+
19
+ module OvhDnsup
20
+ class Error < StandardError; end
21
+ end
22
+
@@ -0,0 +1,378 @@
1
+ # Copyright 2021 Hannah Rittich
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ require 'optparse'
16
+ require 'socket'
17
+ require_relative 'domain_manager'
18
+
19
+ module OvhDnsup
20
+ module Cli
21
+ def self.run
22
+
23
+ @conf_fn = File.join(Dir.home, '.ovh_dnsup.conf')
24
+
25
+ command = ARGV.shift
26
+
27
+ if %w{register unregister login logout list authorize update interfaces sessions}.include? command
28
+ self.send command.to_sym()
29
+ else
30
+ usage
31
+ puts "Invalid command #{command}"
32
+ end
33
+ end
34
+
35
+ def self.usage
36
+ puts <<~EOS
37
+ Usage: ovh_dnsup command [arguments...]
38
+
39
+ OVH DNS updater
40
+
41
+ Commands:
42
+
43
+ register Register application with the API.
44
+ unregister Unregister (the) application(s).
45
+ login Login to manage the DNS updaters.
46
+ logout Logout.
47
+ list List a DNS zone.
48
+ authorize Authorize a DNS updater.
49
+ update Perform DNS updates.
50
+ sessions List all authorized updaters.
51
+ interfaces List the local network interfaces.
52
+
53
+ EOS
54
+ end
55
+
56
+ def self.load_config
57
+ begin
58
+ conf = File.open(@conf_fn, 'r') { |fp| JSON.parse(fp.read) }
59
+ rescue
60
+ puts "Could not load configuration"
61
+ conf = {}
62
+ end
63
+ @api = DomainManager.new(state: conf)
64
+ end
65
+
66
+ def self.save_config
67
+ File.open(@conf_fn, 'w') { |fp| fp.write(@api.state.to_json) }
68
+ end
69
+
70
+ def self.register
71
+ parser = OptionParser.new do |opts|
72
+ opts.banner = 'Usage: ovh_dnsup register [options]'
73
+ end
74
+ parser.parse!
75
+ if ARGV.length != 0
76
+ puts 'Invalid number of arguments'
77
+ puts parser
78
+ return
79
+ end
80
+
81
+
82
+ print "Endpoint (#{OvhApi.endpoints.join(', ')}): "
83
+ endpoint = gets.strip
84
+
85
+ if !OvhApi.endpoint_url(endpoint)
86
+ puts 'Invalid endpoint'
87
+ return
88
+ end
89
+
90
+ puts <<~EOS
91
+ Please visit
92
+
93
+ #{OvhApi.endpoint_url(endpoint)}createApp/
94
+
95
+ and create an application. Afterwards, come back and answer the
96
+ questions below.
97
+ EOS
98
+
99
+ print 'Application key: '
100
+ application_key = gets().strip
101
+ print 'Application secret: '
102
+ application_secret = gets().strip
103
+
104
+ @api = DomainManager.new(endpoint: endpoint,
105
+ application_key: application_key,
106
+ application_secret: application_secret)
107
+ save_config
108
+ end
109
+
110
+ def self.unregister
111
+ load_config
112
+
113
+ params = {}
114
+ parser = OptionParser.new do |opts|
115
+ opts.banner = "Usage: ovh_dnsup unregister [-a|--all]"
116
+ opts.on('-a', '--all', 'Unregister all applications.')
117
+ end
118
+ parser.parse!(into: params)
119
+ if ARGV.length != 0
120
+ puts 'Invalid number of arguments'
121
+ puts parser
122
+ return
123
+ end
124
+
125
+ puts 'All sessions of unregistered applications become invalid. To continue, please type "YES"'
126
+ if gets.strip != 'YES'
127
+ puts 'Abort'
128
+ return
129
+ end
130
+
131
+ @api.unregister(all: params[:all])
132
+ if params[:all]
133
+ puts "All applications have been unregistered"
134
+ else
135
+ puts "This application has been unregistered"
136
+ end
137
+ end
138
+
139
+ def self.login
140
+ parser = OptionParser.new do |opts|
141
+ opts.banner = 'Usage: ovh_dnsup login'
142
+ end
143
+ parser.parse!
144
+ if ARGV.length != 0
145
+ puts 'Invalid number of arguments'
146
+ puts parser
147
+ return
148
+ end
149
+
150
+ load_config
151
+ @api.login
152
+ save_config
153
+ end
154
+
155
+ def self.logout
156
+ parser = OptionParser.new do |opts|
157
+ opts.banner = 'Usage: ovh_dnsup logout'
158
+ end
159
+ parser.parse!
160
+ if ARGV.length != 0
161
+ puts 'Invalid number of arguments'
162
+ puts parser
163
+ return
164
+ end
165
+
166
+ load_config
167
+ @api.logout
168
+ end
169
+
170
+ def self.list
171
+ parser = OptionParser.new do |opts|
172
+ opts.banner = 'Usage: ovh_dnsup list domain'
173
+ end
174
+ parser.parse!
175
+ if ARGV.length != 1
176
+ puts 'Invalid number of arguments'
177
+ puts parser
178
+ return
179
+ end
180
+
181
+ load_config
182
+ @api.list_zone ARGV[0]
183
+ end
184
+
185
+ def self.authorize
186
+ parser = OptionParser.new do |opts|
187
+ opts.banner = 'Usage: ovh_dnsup authorize domain subdomain token_file'
188
+ end
189
+ parser.parse!
190
+ if ARGV.length != 3
191
+ puts 'Invalid number of arguments'
192
+ puts parser
193
+ return
194
+ end
195
+ domain, subdomain, token_file = ARGV
196
+
197
+ load_config
198
+ map = @api.subdomain_type_map(domain, subdomain)
199
+
200
+ if map.empty?
201
+ puts "Subdomain has no A or AAAA record."
202
+ return
203
+ end
204
+
205
+ up = DomainUpdater.new(endpoint: @api.endpoint,
206
+ application_key: @api.application_key,
207
+ application_secret: @api.application_secret)
208
+ up.login(domain: domain, subdomain: subdomain, type_map: map)
209
+
210
+ File.open(token_file, 'w') do |of|
211
+ of.write(up.state.to_json)
212
+ end
213
+ end
214
+
215
+ def self.update
216
+ banner = "Usage: ovh_dnsup update [options] token_file"
217
+ params = {}
218
+ parser = OptionParser.new do |opts|
219
+ opts.banner = banner
220
+
221
+ opts.on("--ipv6", "Force IPv6")
222
+ opts.on("--ipv4", "Force IPv4")
223
+ opts.on("--ip IP", "The IP address to set")
224
+ opts.on("--if INTERFACE", "The interface")
225
+ opts.on("-d", "--daemon", "Run continuously")
226
+ opts.on("-v", "--verbose", "Run verbosely")
227
+ opts.on("--delay SECONDS", "Time in seconds between checks")
228
+ end
229
+ parser.parse!(into: params)
230
+
231
+ if ARGV.length != 1
232
+ puts "Invalid number of arguments"
233
+ puts parser
234
+ return
235
+ end
236
+ token_file, = ARGV
237
+
238
+ delay = params[:delay] ? params[:delay] : 60
239
+
240
+ if params[:ipv6]
241
+ version = 6
242
+ elsif params[:ipv4]
243
+ version = 4
244
+ end
245
+
246
+ if !params[:ip] && !params[:if]
247
+ puts "Either provide IP address of interface name"
248
+ return
249
+ end
250
+ if params[:ip] && params[:if]
251
+ puts "You cannot provide IP and interface!"
252
+ return
253
+ end
254
+
255
+ if params[:daemon] && !params[:if]
256
+ puts "Daemon mode requires an interface to be given"
257
+ return
258
+ end
259
+
260
+ state = File.open(token_file, 'r') { |fp| JSON.parse(fp.read) }
261
+ @up = DomainUpdater.new(state: state)
262
+
263
+ ip = nil
264
+ running = true
265
+ while running
266
+ begin
267
+ if params[:ip]
268
+ new_ip = params[:ip]
269
+ else
270
+ new_ip = get_interface_address(interface: params[:if], version: version)
271
+ end
272
+
273
+ if new_ip != ip
274
+ puts "Setting new IP #{new_ip}" if params[:verbose]
275
+ @up.update new_ip
276
+ ip = new_ip
277
+
278
+ if !params[:daemon]
279
+ running = false
280
+ end
281
+ else
282
+ puts "IP not changed" if params[:verbose]
283
+ end
284
+
285
+ rescue Interrupt
286
+ puts "Interrupted" if params[:verbose]
287
+ running = false
288
+ rescue Exception => e
289
+ puts "WARNING: #{e.to_s}"
290
+ end
291
+
292
+ begin
293
+ sleep delay if running
294
+ rescue Interrupt
295
+ running = false
296
+ end
297
+ end
298
+ end
299
+
300
+ def self.sessions
301
+ load_config
302
+
303
+ params = {}
304
+ parser = OptionParser.new do |opts|
305
+ opts.banner = 'Usage: ovh_dnsup sessions'
306
+ opts.on('-a', '--all', 'List all sessions')
307
+ opts.on('-d', '--delete ID', 'Delete session')
308
+ opts.on('--delete-all', 'Delte all sessions')
309
+ end
310
+ parser.parse!(into: params)
311
+ if ARGV.length != 0
312
+ puts 'Invalid number of arguments'
313
+ puts parser
314
+ return
315
+ end
316
+
317
+ if params[:delete]
318
+ @api.delete_session(params[:delete].to_i)
319
+ elsif params["delete-all".to_sym]
320
+ @api.delete_all_sessions()
321
+ else
322
+ @api.list_sessions(all: params[:all])
323
+ end
324
+ end
325
+
326
+ # version: the IP version
327
+ def self.get_interface_address(interface:, version: nil)
328
+ ipv4 = []
329
+ ipv6 = []
330
+ Socket.getifaddrs.each do |ifaddr|
331
+ if ifaddr.name == interface
332
+ if ifaddr.addr.ipv4?
333
+ ipv4.push(ifaddr.addr.ip_address)
334
+ end
335
+ if ifaddr.addr.ipv6?
336
+ ipv6.push(ifaddr.addr.ip_address)
337
+ end
338
+ end
339
+ end
340
+
341
+ # filter local addresses
342
+ ipv6.select { |addr| !/^fe80/ =~ addr }
343
+
344
+ if !ipv6.empty? && (version == nil || version == 6)
345
+ return ipv6[0]
346
+ elsif !ipv4.empty? && (version == nil || version == 4)
347
+ return ipv4[0]
348
+ else
349
+ raise 'No suitable address found.'
350
+ end
351
+ end
352
+
353
+ def self.interfaces
354
+ parser = OptionParser.new do |opts|
355
+ opts.banner = 'Usage: ovh_dnsup interfaces'
356
+ end
357
+ parser.parse!
358
+ if ARGV.length != 0
359
+ puts 'Invalid number of arguments'
360
+ puts parser
361
+ return
362
+ end
363
+
364
+ interfaces = Hash.new { |h, k| h[k] = [] }
365
+ Socket.getifaddrs.each do |a|
366
+ if a.addr.ip?
367
+ interfaces[a.name].push(a.addr)
368
+ end
369
+ end
370
+
371
+ interfaces.each do |k,v|
372
+ puts k
373
+ v.each { |i| puts " #{i.ip_address}" }
374
+ end
375
+
376
+ end
377
+ end
378
+ end
@@ -0,0 +1,199 @@
1
+ # Copyright 2021 Hannah Rittich
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ require_relative 'ovh_api'
16
+
17
+ module OvhDnsup
18
+
19
+ class DomainManager
20
+ def initialize(args)
21
+ @api = OvhApi.new(args)
22
+ end
23
+
24
+ def endpoint; @api.endpoint; end
25
+ def application_key; @api.application_key; end
26
+ def application_secret; @api.application_secret; end
27
+
28
+ def state
29
+ @api.state
30
+ end
31
+
32
+ def state= h
33
+ @api.state = h
34
+ end
35
+
36
+ def register
37
+ @api.register
38
+ end
39
+
40
+ def unregister(all: false)
41
+ response = @api.get('auth/currentCredential')
42
+ app_id = response['applicationId']
43
+
44
+ # unregister all applications other
45
+ if all
46
+ other_apps = @api.get('me/api/application').select {|id| id != app_id }
47
+ other_apps.each do |id|
48
+ @api.delete("me/api/application/#{id}")
49
+ end
50
+ end
51
+
52
+ @api.delete("me/api/application/#{app_id}")
53
+ end
54
+
55
+ def login
56
+ @api.login [{:method => 'GET', :path => '/domain/zone/*'},
57
+ {:method => 'GET', :path => '/me/api/application'},
58
+ {:method => 'DELETE', :path => '/me/api/application/*'},
59
+ {:method => 'GET', :path => '/me/api/credential'},
60
+ {:method => 'GET', :path => '/me/api/credential/*'},
61
+ {:method => 'DELETE', :path => '/me/api/credential/*'}]
62
+ end
63
+
64
+ def logout
65
+ @api.post('auth/logout')
66
+ end
67
+
68
+ def list_zone(domain)
69
+ ids = @api.get("domain/zone/#{domain}/record")
70
+ ids.each do |id|
71
+ record = @api.get("domain/zone/#{domain}/record/#{id}")
72
+ if !record['subDomain'].empty?
73
+ full_domain = "#{record['subDomain']}.#{domain}"
74
+ else
75
+ full_domain = domain
76
+ end
77
+ puts "#{record['fieldType']} #{full_domain} => #{record['target']}"
78
+ end
79
+ end
80
+
81
+ def subdomain_type_map(domain, sub)
82
+ # get IDs of all entries of this subdomain
83
+ ids = @api.get("domain/zone/#{domain}/record", subDomain: sub)
84
+
85
+ type_map = {}
86
+
87
+ ids.each do |id|
88
+ record = @api.get("domain/zone/#{domain}/record/#{id}")
89
+ field_type = record['fieldType']
90
+ if ['A', 'AAAA'].include? field_type
91
+ type_map[field_type] = id
92
+ end
93
+ end
94
+
95
+ type_map
96
+ end
97
+
98
+ def list_sessions(all: false)
99
+ params = nil
100
+ if !all
101
+ app_id = @api.get('auth/currentCredential')['applicationId']
102
+ params = {'applicationId' => app_id}
103
+ end
104
+
105
+ cred_ids = @api.get('me/api/credential', params)
106
+ cred_ids.each do |id|
107
+ info = @api.get("me/api/credential/#{id}")
108
+
109
+ next if info['status'] == 'expired' && !all
110
+
111
+ app_info = @api.get("me/api/credential/#{id}/application") if all
112
+
113
+ puts "id: #{id}"
114
+ puts " app: #{app_info['name']} (#{app_info['description']})" if all
115
+ puts " status: #{info['status']}" if all
116
+ puts " creation: #{info['creation']} expiration: #{info['expiration']}"
117
+
118
+ info['rules'].each do |rule|
119
+ if /^\/domain\/zone\/(?<zone>[^\/]+)\/record\/(?<eid>[^\/]+)$/ =~ rule['path'] then
120
+
121
+ begin
122
+ entry = @api.get("domain/zone/#{zone}/record/#{eid}")
123
+ puts " zone: #{zone} subdomain: #{entry['subDomain']}"
124
+ rescue OvhException
125
+ end
126
+ end
127
+
128
+ if rule['path'] == '/domain/zone/*'
129
+ puts " domain management"
130
+ end
131
+ end # info['rules'].each
132
+ end # cred_ids.each
133
+ end
134
+
135
+ def delete_session(id)
136
+ @api.delete("me/api/credential/#{id}")
137
+ end
138
+
139
+ def delete_all_sessions()
140
+ cred_id = @api.get('auth/currentCredential')['credentialId']
141
+
142
+ other_ids = @api.get('me/api/credential').select {|id| id != cred_id}
143
+ other_ids.each &method(:delete_session)
144
+ delete_session(cred_id)
145
+ end
146
+ end
147
+
148
+ class DomainUpdater
149
+ def initialize(endpoint: nil, application_key: nil, application_secret: nil, state: nil)
150
+ if state
151
+ self.state = state
152
+ else
153
+ @api = OvhApi.new(endpoint: endpoint,
154
+ application_key: application_key,
155
+ application_secret: application_secret)
156
+ end
157
+ end
158
+
159
+ def state
160
+ { 'api_state' => @api.state,
161
+ 'domain' => @domain,
162
+ 'subdomain' => @subdomain,
163
+ 'type_map' => @type_map }
164
+ end
165
+
166
+ def state= h
167
+ @api = OvhApi.new(state: h['api_state'])
168
+ @domain = h['domain']
169
+ @subdomain = h['subdomain']
170
+ @type_map = h['type_map']
171
+ end
172
+
173
+ def login(domain:, subdomain:, type_map:)
174
+ @domain = domain
175
+ @subdomain = subdomain
176
+ @type_map = type_map
177
+
178
+ access_rules = type_map.map() {
179
+ |type, id| { method: 'PUT', path: "/domain/zone/#{domain}/record/#{id}" }
180
+ }
181
+ access_rules.push({method: 'POST', path: "/domain/zone/#{@domain}/refresh"})
182
+
183
+ @api.login(access_rules)
184
+ end
185
+
186
+ def update(new_ip)
187
+ type = (/:/ =~ new_ip) ? 'AAAA' : 'A'
188
+ id = @type_map[type]
189
+ if !id then raise "Subdomain has no #{type} record" end
190
+
191
+ obj = {'ttl' => 300,
192
+ 'target' => new_ip }
193
+
194
+ @api.put("domain/zone/#{@domain}/record/#{id}", obj)
195
+ @api.post("domain/zone/#{@domain}/refresh")
196
+ end
197
+ end
198
+
199
+ end
@@ -0,0 +1,170 @@
1
+ # Copyright 2021 Hannah Rittich
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ require 'json'
16
+ require 'digest'
17
+ require 'faraday'
18
+
19
+ module OvhDnsup
20
+ class OvhException < Exception; end
21
+
22
+ ENDPOINTS = {
23
+ 'ovh-eu' => 'https://eu.api.ovh.com/',
24
+ 'ovh-us' => 'https://api.us.ovhcloud.com/',
25
+ 'ovh-ca' => 'https://ca.api.ovh.com/',
26
+ 'kimsufi-eu' => 'https://eu.api.kimsufi.com/',
27
+ 'kimsufi-ca' => 'https://ca.api.kimsufi.com/',
28
+ 'soyoustart-eu' => 'https://eu.api.soyoustart.com/',
29
+ 'soyoustart-ca' => 'https://ca.api.soyoustart.com/',
30
+ }
31
+
32
+ class OvhApi
33
+ attr_reader :endpoint, :application_key, :application_secret, :consumer_key
34
+
35
+ def self.endpoints
36
+ ENDPOINTS.map { |k,v| k }
37
+ end
38
+
39
+ def self.endpoint_url(endpoint)
40
+ ENDPOINTS[endpoint]
41
+ end
42
+
43
+ def initialize(endpoint: nil, application_key: nil, application_secret: nil, state: nil)
44
+ if state
45
+ self.state = state
46
+ raise 'Invalid arguments' if application_key || application_secret || endpoint
47
+ else
48
+ @endpoint = endpoint
49
+ @application_key = application_key
50
+ @application_secret = application_secret
51
+ @consumer_key = nil
52
+
53
+ @base_url = ENDPOINTS[@endpoint] + '1.0/'
54
+ @conn = Faraday.new @base_url
55
+ end
56
+ end
57
+
58
+ def state
59
+ { 'endpoint' => @endpoint,
60
+ 'application_key' => @application_key,
61
+ 'application_secret' => @application_secret,
62
+ 'consumer_key' => @consumer_key }
63
+ end
64
+
65
+ def state= h
66
+ @endpoint = h['endpoint']
67
+ @application_key = h['application_key']
68
+ @application_secret = h['application_secret']
69
+ @consumer_key = h['consumer_key']
70
+
71
+ @base_url = ENDPOINTS[@endpoint] + '1.0/'
72
+ @conn = Faraday.new @base_url
73
+ end
74
+
75
+ def login(access_rules, verbose=true)
76
+ register unless @application_key && @application_secret
77
+
78
+ body = { :accessRules => access_rules }.to_json
79
+ headers = { 'Content-type' => 'application/json',
80
+ 'X-Ovh-Application' => @application_key }
81
+ response = @conn.post('auth/credential', body, headers)
82
+ response = process(response)
83
+
84
+ validation_url = response['validationUrl']
85
+ @consumer_key = response['consumerKey']
86
+
87
+ if verbose
88
+ puts <<~EOS
89
+ To complete the authentication process please open
90
+
91
+ #{validation_url}
92
+
93
+ and login with your credentials.
94
+ EOS
95
+ end
96
+ return validation_url
97
+ end
98
+
99
+ def sign(method, url, body, tstamp)
100
+ if !@application_key || !@application_secret
101
+ raise OvhException.new('Application key and/or secret missing.')
102
+ end
103
+ if !@consumer_key
104
+ raise OvhException.new('Not logged in')
105
+ end
106
+
107
+ "$1$" + Digest::SHA1.hexdigest(
108
+ @application_secret + "+" +
109
+ @consumer_key + "+" +
110
+ method + "+" +
111
+ url + "+" +
112
+ body + "+" +
113
+ tstamp.to_s)
114
+ end
115
+
116
+ def auth_header(method, path, params = nil, body = '')
117
+ raise 'Only relative paths are allowed' if path.start_with?('/')
118
+ url = @base_url + path
119
+ if params
120
+ url += '?' + Faraday::FlatParamsEncoder.encode(params)
121
+ end
122
+ tstamp = Time.now.to_i
123
+ {
124
+ 'Content-type' => 'application/json',
125
+ 'X-Ovh-Application' => @application_key,
126
+ 'X-Ovh-Timestamp' => tstamp.to_s,
127
+ 'X-Ovh-Signature' => sign(method, url, body, tstamp),
128
+ 'X-Ovh-Consumer' => @consumer_key
129
+ }
130
+ end
131
+
132
+ def get(path, params = nil)
133
+ response = @conn.get(path, params, auth_header('GET', path, params))
134
+ return process(response)
135
+ end
136
+
137
+ def post(path, body='')
138
+ response = @conn.post(path, body, auth_header('POST', path, nil, body))
139
+ return process(response)
140
+ end
141
+
142
+ def put(path, obj)
143
+ body = obj.to_json
144
+ response = @conn.put(path, body, auth_header('PUT', path, nil, body))
145
+ return process(response)
146
+ end
147
+
148
+ def delete(path, params=nil)
149
+ response = @conn.delete(path, params, auth_header('DELETE', path))
150
+ return process(response)
151
+ end
152
+
153
+ private
154
+ def process(response)
155
+ if !response.success?
156
+ begin
157
+ msg = JSON.parse(response.body)['message']
158
+ rescue
159
+ msg = "#{response.status}: #{response.body}"
160
+ end
161
+ raise OvhException.new(msg)
162
+ else
163
+ return JSON.parse(response.body)
164
+ end
165
+ end
166
+ end
167
+
168
+
169
+
170
+ end
@@ -0,0 +1,17 @@
1
+ # Copyright 2021 Hannah Rittich
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ module OvhDnsup
16
+ VERSION = "0.1.0"
17
+ end
@@ -0,0 +1,24 @@
1
+ require_relative 'lib/ovh_dnsup/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "ovh_dnsup"
5
+ spec.version = OvhDnsup::VERSION
6
+ spec.authors = ["Hannah Rittich"]
7
+ spec.email = ["hrittich@users.noreply.github.com"]
8
+ spec.license = 'Apache-2.0'
9
+
10
+ spec.summary = %q{Securely updates DNS records in a zone hosted by OVH.}
11
+ spec.homepage = "https://github.com/hrittich/ovh_dnsup"
12
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
13
+
14
+ # Specify which files should be added to the gem when it is released.
15
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
16
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
17
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
18
+ end
19
+ spec.bindir = "exe"
20
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
21
+ spec.require_paths = ["lib"]
22
+
23
+ spec.add_runtime_dependency 'faraday', '~> 1.3.0', '>= 1.3.0'
24
+ end
metadata ADDED
@@ -0,0 +1,78 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ovh_dnsup
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Hannah Rittich
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-01-03 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: faraday
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 1.3.0
20
+ - - ">="
21
+ - !ruby/object:Gem::Version
22
+ version: 1.3.0
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - "~>"
28
+ - !ruby/object:Gem::Version
29
+ version: 1.3.0
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: 1.3.0
33
+ description:
34
+ email:
35
+ - hrittich@users.noreply.github.com
36
+ executables:
37
+ - ovh_dnsup
38
+ extensions: []
39
+ extra_rdoc_files: []
40
+ files:
41
+ - ".gitignore"
42
+ - Gemfile
43
+ - LICENSE
44
+ - README.md
45
+ - bin/console
46
+ - bin/setup
47
+ - exe/ovh_dnsup
48
+ - lib/ovh_dnsup.rb
49
+ - lib/ovh_dnsup/cli.rb
50
+ - lib/ovh_dnsup/domain_manager.rb
51
+ - lib/ovh_dnsup/ovh_api.rb
52
+ - lib/ovh_dnsup/version.rb
53
+ - ovh_dnsup.gemspec
54
+ homepage: https://github.com/hrittich/ovh_dnsup
55
+ licenses:
56
+ - Apache-2.0
57
+ metadata: {}
58
+ post_install_message:
59
+ rdoc_options: []
60
+ require_paths:
61
+ - lib
62
+ required_ruby_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: 2.3.0
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: '0'
72
+ requirements: []
73
+ rubyforge_project:
74
+ rubygems_version: 2.7.6.2
75
+ signing_key:
76
+ specification_version: 4
77
+ summary: Securely updates DNS records in a zone hosted by OVH.
78
+ test_files: []