keynub_licdongle 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9b4e6087fb299d00885c4fc56d124188a9fb87d500755a388ddf2062ebd0ad5a
4
+ data.tar.gz: 9f772865a5cf6a98083273832dc61c987a7a53faa1490b6a4e34cc03ee9d0276
5
+ SHA512:
6
+ metadata.gz: cf8163cfabf981bad451ad8e14b3f36a5a96ebdfabf6ec6539005d9c0d9562e8af1e3c8232c58f105bd24c7c5927a71a91e2cc337eeb477529ba1505dffd6809
7
+ data.tar.gz: 62dd686dce927513a341d23689b02e501c4b0f423cfcff71923b06e40edaf7f11fd3c27c7a0f487bbfebac0def34cebfcbb3bf22943b96682a7d650be9c8af58
@@ -0,0 +1,91 @@
1
+ ================================================================================
2
+ KEYNUB LICENSE DONGLE SDK
3
+ Licence for the prebuilt native libraries
4
+ ================================================================================
5
+
6
+ This distribution contains two kinds of thing, under two different licences.
7
+
8
+
9
+ 1. SOURCE - Apache License, Version 2.0
10
+ --------------------------------------------------------------------------------
11
+
12
+ The language bindings, the samples and the C ABI header are licensed under the
13
+ Apache License, Version 2.0. The full text is in the accompanying LICENSE file,
14
+ and the source is published at https://github.com/AB-KeyNub/KeyNub-SDK.
15
+
16
+
17
+ 2. PREBUILT NATIVE LIBRARIES - these terms
18
+ --------------------------------------------------------------------------------
19
+
20
+ The compiled libraries - keynub_licdongle, keynub_licdongle_flat and the KeyNub
21
+ COM server, supplied as .dll and .lib, .so, .dylib and .a - are not published as
22
+ source and are NOT licensed under Apache-2.0. They are licensed as follows.
23
+
24
+ GRANT
25
+
26
+ Subject to these terms, KeyNub grants you a worldwide, royalty-free,
27
+ non-exclusive licence to:
28
+
29
+ (a) use and reproduce the libraries to develop, test and support your own
30
+ application; and
31
+
32
+ (b) distribute the libraries, in binary form, as an integral component of
33
+ that application, to your customers and end users.
34
+
35
+ CONDITIONS
36
+
37
+ (1) You distribute the libraries unmodified.
38
+
39
+ (2) You distribute them only as a component of your own application - not as
40
+ a standalone product, library, SDK or download, and not in a form whose
41
+ principal purpose is to supply the libraries to others.
42
+
43
+ (3) You keep this file, LICENSE, NOTICE and THIRD-PARTY-NOTICES.txt with any
44
+ distribution that includes the libraries, and you do not remove or alter
45
+ any copyright, trademark or attribution notice they contain.
46
+
47
+ (4) You do not sublicense, rent, lease or sell the libraries on their own.
48
+
49
+ RESERVED RIGHTS
50
+
51
+ No rights are granted in the "KeyNub" name, logo or other trademarks. All
52
+ rights not expressly granted above are reserved by KeyNub.
53
+
54
+ YOUR STATUTORY RIGHTS
55
+
56
+ Nothing in these terms restricts any right you have under applicable law that
57
+ cannot be restricted by agreement. In the European Union, for example, that
58
+ includes the right to decompile for interoperability purposes under Article 6
59
+ of Directive 2009/24/EC.
60
+
61
+
62
+ 3. THIRD-PARTY COMPONENTS
63
+ --------------------------------------------------------------------------------
64
+
65
+ The libraries statically link Mbed TLS and hidapi. The licences KeyNub has elected
66
+ for them, their copyright notices and the full licence texts are in
67
+ THIRD-PARTY-NOTICES.txt. Those attribution obligations apply to you as well when
68
+ you redistribute the libraries inside your application.
69
+
70
+
71
+ 4. NO WARRANTY
72
+ --------------------------------------------------------------------------------
73
+
74
+ THE LIBRARIES ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
75
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
76
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
77
+
78
+
79
+ 5. LIMITATION OF LIABILITY
80
+ --------------------------------------------------------------------------------
81
+
82
+ TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, KEYNUB SHALL NOT BE LIABLE FOR
83
+ ANY INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES, OR FOR ANY LOSS OF
84
+ PROFITS, REVENUE OR DATA, ARISING OUT OF OR IN CONNECTION WITH THE LIBRARIES OR
85
+ THEIR USE. Nothing in these terms excludes or limits liability that cannot be
86
+ excluded or limited under applicable law.
87
+
88
+
89
+ --------------------------------------------------------------------------------
90
+ Questions about these terms, or about a use they do not cover - OEM redistribution,
91
+ source escrow, an unusual platform: https://www.keynub.com/#contact
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
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/NOTICE ADDED
@@ -0,0 +1,14 @@
1
+ KeyNub License Dongle SDK
2
+ Copyright (c) 2026 KeyNub
3
+
4
+ This product includes software developed as part of the KeyNub License Dongle
5
+ SDK (https://github.com/AB-KeyNub/KeyNub-SDK). The bindings, samples and C ABI
6
+ header published there are licensed under the Apache License, Version 2.0; see
7
+ the LICENSE file for the full terms. The prebuilt native libraries are not
8
+ published as source and are covered by the accompanying BINARY-LICENSE.txt.
9
+
10
+ This product also includes third-party software. The native library
11
+ (keynub_licdongle) statically links Mbed TLS and hidapi; the Java binding
12
+ depends on JNA. Their copyright notices, the licenses elected for them, and the
13
+ full text of those licenses are recorded in THIRD-PARTY-NOTICES.txt, which is
14
+ distributed with this product.
data/README.md ADDED
@@ -0,0 +1,95 @@
1
+ # KeyNub License Dongle — Ruby binding
2
+
3
+ `keynub_licdongle` — the KeyNub dongle from Ruby. **No gems, no compiler**: the
4
+ FFI layer is [Fiddle](https://docs.ruby-lang.org/en/master/Fiddle.html), which is
5
+ part of Ruby's standard library. Ruby 3.0+, Windows / Linux / macOS.
6
+
7
+ ```ruby
8
+ require 'keynub_licdongle'
9
+
10
+ KeyNubLicDongle::Context.open do |ctx|
11
+ dongle = ctx.open # first dongle, or ctx.open(serial)
12
+ dongle.verify_genuine! # raises unless genuine
13
+
14
+ dongle.session do |session|
15
+ data = session.app_decrypt(blob) # <- build your licence check on this
16
+ end
17
+ end
18
+ ```
19
+
20
+ > Read [`../../docs/integration-security.md`](https://github.com/AB-KeyNub/KeyNub-SDK/blob/master/docs/integration-security.md)
21
+ > first. `exit unless licensed?` is one line to delete, and Ruby ships as source —
22
+ > even a `.rbc` or an obfuscator only slows that down. What cannot be deleted is
23
+ > data the program needs and only the dongle can decrypt.
24
+
25
+ ## Why no `ffi` gem
26
+
27
+ The `ffi` gem is the usual choice and it is a fine library. Fiddle wins here for
28
+ one reason that matters specifically to licensing: it is **already in the standard
29
+ library**, so the check has no third-party dependency that a customer could
30
+ replace with a stub of their own. Nothing to install, nothing to build, nothing in
31
+ the load path but Ruby itself.
32
+
33
+ The cost is that the C signatures live in
34
+ [`lib/keynub_licdongle/native.rb`](https://github.com/AB-KeyNub/KeyNub-SDK/blob/master/bindings/ruby/lib/keynub_licdongle/native.rb) as data no
35
+ compiler verifies — which is why every one of them is written out by hand. Struct
36
+ layouts go through `Fiddle::Importer`, so the padding is computed rather than
37
+ hand-maintained; a hand-written offset that is wrong reads a neighbouring field
38
+ and produces a plausible wrong value rather than a crash.
39
+
40
+ ## Errors
41
+
42
+ Failures raise `KeyNubLicDongle::Error` or a subclass, each carrying `status`
43
+ (the numeric `licd_status`), `operation`, and `detail` (the SDK's diagnostic text).
44
+
45
+ ```ruby
46
+ begin
47
+ dongle.verify_genuine!
48
+ rescue KeyNubLicDongle::DeviceNotFoundError
49
+ warn 'please insert your KeyNub dongle'
50
+ rescue KeyNubLicDongle::CertificateInvalidError => e
51
+ warn "this dongle was rejected: #{e.detail}"
52
+ end
53
+ ```
54
+
55
+ `dongle.genuine?` is the non-raising form for a gate and **fails closed**: a
56
+ missing dongle, an I/O error and an invalid certificate all return `false`.
57
+
58
+ Blocks close things for you — `Context.open`, `dongle.session` — and are the
59
+ recommended form; `#close` is there when the lifetime is not lexical.
60
+
61
+ ## Progress callbacks
62
+
63
+ `read_record` and `write_record` take a block called as `(done, total)`. Return
64
+ `false` to cancel, which raises `OperationCancelledError`. An exception raised
65
+ inside the block is held until the SDK has unwound its own transfer and then
66
+ re-raised with its own identity — letting it escape through the C frames would
67
+ skip that cleanup and strand the device mid-transfer.
68
+
69
+ ```ruby
70
+ data = session.read_record('license') do |done, total|
71
+ print "\r#{done}/#{total}"
72
+ true
73
+ end
74
+ ```
75
+
76
+ ## Shipping the native library
77
+
78
+ The binding looks for the core library, in order:
79
+
80
+ 1. `KEYNUB_LICDONGLE_LIBRARY` — an absolute path to a specific library
81
+ 2. `vendor/` inside the gem
82
+ 3. beside `lib/keynub_licdongle/`
83
+ 4. the system search path
84
+
85
+ ## License
86
+
87
+ Apache-2.0, like the rest of the SDK — [`../../LICENSE`](https://github.com/AB-KeyNub/KeyNub-SDK/blob/master/LICENSE),
88
+ [`../../THIRD-PARTY-NOTICES.txt`](https://github.com/AB-KeyNub/KeyNub-SDK/blob/master/THIRD-PARTY-NOTICES.txt).
89
+
90
+ ## Links
91
+
92
+ - [KeyNub License Dongle for Ruby](https://www.keynub.com/developers/ruby/): the product, and how to
93
+ order one
94
+ - [Source, samples and issue tracker](https://github.com/AB-KeyNub/KeyNub-SDK) on GitHub
95
+ - [Native library for your platform](https://github.com/AB-KeyNub/KeyNub-SDK/blob/master/NATIVES.md)
@@ -0,0 +1,107 @@
1
+ ================================================================================
2
+ THIRD-PARTY NOTICES - KeyNub License Dongle SDK
3
+ ================================================================================
4
+
5
+ The KeyNub License Dongle SDK's published source - the language bindings, the
6
+ samples and the C ABI header, as published at
7
+ https://github.com/AB-KeyNub/KeyNub-SDK - is licensed under the Apache License,
8
+ Version 2.0 (see the accompanying LICENSE file).
9
+
10
+ The prebuilt native libraries (keynub_licdongle, keynub_licdongle_flat and the
11
+ KeyNub COM server) are not published as source and are NOT licensed under
12
+ Apache-2.0. Their distribution terms are in the accompanying BINARY-LICENSE.txt.
13
+
14
+ Either way, this distribution incorporates the third-party components listed
15
+ below, and their attribution obligations travel with every copy of it.
16
+
17
+ Several of these components are offered by their authors under a CHOICE of
18
+ licenses. For each one, the license KeyNub has elected is stated explicitly, and
19
+ the options that are not elected are named so there is no ambiguity about which
20
+ terms apply to this distribution. Where Apache-2.0 is elected, the text in the
21
+ accompanying LICENSE file is the applicable license text.
22
+
23
+ Components marked "statically linked" are compiled into the native library
24
+ (keynub_licdongle.dll / libkeynub_licdongle.so / libkeynub_licdongle.dylib).
25
+ Their attribution obligations therefore travel with every binary distribution of
26
+ the SDK - the NuGet package, the Python wheel, the Maven JAR, and the C/Delphi
27
+ archives each carry a copy of this file alongside LICENSE and NOTICE.
28
+
29
+ --------------------------------------------------------------------------------
30
+ 1. Mbed TLS 3.6.7 - statically linked into the native library
31
+ --------------------------------------------------------------------------------
32
+
33
+ Project: https://github.com/Mbed-TLS/mbedtls (tag mbedtls-3.6.7)
34
+ Offered: dual license - Apache-2.0 OR GPL-2.0-or-later
35
+ ELECTED: Apache-2.0
36
+ The GPL-2.0-or-later option is NOT elected and does not apply to
37
+ this distribution.
38
+
39
+ Copyright The Mbed TLS Contributors
40
+
41
+ Licensed under the Apache License, Version 2.0. The full text of that
42
+ license is in the accompanying LICENSE file.
43
+
44
+ --------------------------------------------------------------------------------
45
+ 2. hidapi 0.15.0 - statically linked into the native library
46
+ --------------------------------------------------------------------------------
47
+
48
+ Project: https://github.com/libusb/hidapi (tag hidapi-0.15.0)
49
+ Offered: a choice of three licenses - GPL-3.0, a BSD-style license, or the
50
+ more liberal original HIDAPI license
51
+ ELECTED: the BSD-style license (hidapi's LICENSE-bsd.txt), reproduced in
52
+ full below.
53
+ The GPL-3.0 option is NOT elected and does not apply to this
54
+ distribution. Note that some operating-system distributions
55
+ package hidapi under GPL-3.0; that packaging is unrelated to this
56
+ distribution, which vendors hidapi from source under the terms
57
+ below.
58
+
59
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
60
+ Copyright (c) 2010, Alan Ott, Signal 11 Software
61
+ All rights reserved.
62
+
63
+ Redistribution and use in source and binary forms, with or without
64
+ modification, are permitted provided that the following conditions are met:
65
+
66
+ * Redistributions of source code must retain the above copyright notice,
67
+ this list of conditions and the following disclaimer.
68
+ * Redistributions in binary form must reproduce the above copyright
69
+ notice, this list of conditions and the following disclaimer in the
70
+ documentation and/or other materials provided with the distribution.
71
+ * Neither the name of Signal 11 Software nor the names of its
72
+ contributors may be used to endorse or promote products derived from
73
+ this software without specific prior written permission.
74
+
75
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
76
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
77
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
78
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
79
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
80
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
81
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
82
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
83
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
84
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
85
+ POSSIBILITY OF SUCH DAMAGE.
86
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
87
+
88
+ --------------------------------------------------------------------------------
89
+ 3. Java Native Access (JNA) 5.14.0 - Java binding only
90
+ --------------------------------------------------------------------------------
91
+
92
+ Project: https://github.com/java-native-access/jna
93
+ Offered: dual license - LGPL-2.1-or-later OR Apache-2.0
94
+ ELECTED: Apache-2.0
95
+ The LGPL-2.1-or-later option is NOT elected and does not apply to
96
+ this distribution.
97
+
98
+ Copyright (c) 2007-2023 Timothy Wall, Wayne Meissner, Matthias Bläsing and
99
+ the JNA contributors
100
+
101
+ JNA is a dependency of the Java binding only. It is resolved from Maven
102
+ Central at build time and is NOT redistributed inside the KeyNub JAR; it is
103
+ recorded here so that consumers assembling a distribution have the election
104
+ in writing. Licensed under the Apache License, Version 2.0 - full text in
105
+ the accompanying LICENSE file.
106
+
107
+ ================================================================================
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KeyNubLicDongle
4
+ # Native status codes (mirrors licd_status). OK is 0; errors are negative.
5
+ module Status
6
+ OK = 0
7
+ INVALID_ARGUMENT = -1
8
+ NO_DEVICE = -2
9
+ ACCESS_DENIED = -3
10
+ IO = -4
11
+ TIMEOUT = -5
12
+ PROTOCOL = -6
13
+ NOT_GENUINE = -7
14
+ CERTIFICATE_INVALID = -8
15
+ SESSION_EXPIRED = -9
16
+ TAG_MISMATCH = -10
17
+ RANGE = -11
18
+ STORAGE_FULL = -12
19
+ BUSY = -13
20
+ NOT_FOUND = -14
21
+ AUTH_REQUIRED = -15
22
+ FIRMWARE_INCOMPATIBLE = -16
23
+ SDK_TOO_OLD = -17
24
+ CANCELLED = -18
25
+ NOT_IMPLEMENTED = -19
26
+ INTERNAL = -20
27
+ end
28
+
29
+ # Raised when a native operation fails. +status+ carries the specific code and
30
+ # +detail+ the SDK's diagnostic text — log it, do not parse it.
31
+ class Error < StandardError
32
+ attr_reader :status, :operation, :detail
33
+
34
+ def initialize(status, message, operation: nil, detail: nil)
35
+ super(message)
36
+ @status = status
37
+ @operation = operation
38
+ @detail = detail.to_s
39
+ end
40
+ end
41
+
42
+ # The dongle failed its authenticity (challenge-response) check.
43
+ class NotGenuineError < Error; end
44
+ # The device certificate, or its chain to the trusted root, was invalid.
45
+ class CertificateInvalidError < Error; end
46
+ # The operation needs the write role (see Session#authorize_write).
47
+ class WriteAuthorizationRequiredError < Error; end
48
+ # No session for an operation that requires one, or it expired.
49
+ class SessionExpiredError < Error; end
50
+ # No matching dongle was found or present.
51
+ class DeviceNotFoundError < Error; end
52
+ # The named record does not exist on the dongle.
53
+ class RecordNotFoundError < Error; end
54
+ # A transfer was cancelled from its progress callback.
55
+ class OperationCancelledError < Error; end
56
+
57
+ SUBCLASS = {
58
+ Status::NOT_GENUINE => NotGenuineError,
59
+ Status::CERTIFICATE_INVALID => CertificateInvalidError,
60
+ Status::AUTH_REQUIRED => WriteAuthorizationRequiredError,
61
+ Status::SESSION_EXPIRED => SessionExpiredError,
62
+ Status::NO_DEVICE => DeviceNotFoundError,
63
+ Status::NOT_FOUND => RecordNotFoundError,
64
+ Status::CANCELLED => OperationCancelledError
65
+ }.freeze
66
+ private_constant :SUBCLASS
67
+
68
+ module_function
69
+
70
+ # Builds the error type that goes with +status+ without raising it.
71
+ def build_error(status, operation, detail = '')
72
+ text = Native.read_c_string(Native.call(:licd_strerror, status))
73
+ message = "#{operation}: #{text}"
74
+ message += " (#{detail})" unless detail.to_s.empty?
75
+ (SUBCLASS[status] || Error).new(status, message, operation: operation, detail: detail)
76
+ end
77
+
78
+ # Raises the mapped error unless +status+ is OK.
79
+ def check(status, operation, ctx_handle = nil)
80
+ return if status == Status::OK
81
+
82
+ detail = ctx_handle ? Native.read_c_string(Native.call(:licd_error_detail, ctx_handle)) : ''
83
+ raise build_error(status, operation, detail)
84
+ end
85
+ end
@@ -0,0 +1,242 @@
1
+ # frozen_string_literal: true
2
+
3
+ # FFI layer: locates the native core and declares the C ABI
4
+ # (SDK/core/include/licdongle.h).
5
+ #
6
+ # Built on Fiddle, which is part of Ruby's standard library, so this binding needs
7
+ # **no gems at all** — not ffi, not a compiled extension. For a licensing library
8
+ # that matters twice: no build toolchain at the customer, and no third-party
9
+ # dependency in the path of the check.
10
+ #
11
+ # The cost is that these signatures are strings no compiler verifies, which is why
12
+ # so every one of them is written out by hand.
13
+
14
+ require 'fiddle'
15
+ require 'fiddle/import'
16
+ require 'rbconfig'
17
+
18
+ module KeyNubLicDongle
19
+ # C struct layouts. Fiddle computes the padding, so the offsets are not
20
+ # hand-maintained — getting one wrong reads a neighbouring field, and the
21
+ # symptom is a plausible-looking wrong value rather than a crash.
22
+ module Types
23
+ extend Fiddle::Importer
24
+
25
+ Info = struct [
26
+ 'unsigned char proto_version_major',
27
+ 'unsigned char proto_version_minor',
28
+ 'unsigned char fw_version_major',
29
+ 'unsigned char fw_version_minor',
30
+ 'unsigned char fw_version_patch',
31
+ 'int se_ready',
32
+ 'int provisioned',
33
+ 'unsigned int data_capacity',
34
+ 'unsigned int data_free',
35
+ 'int watchdog_reboot',
36
+ 'int isolated',
37
+ 'int writeauth_rotated'
38
+ ]
39
+
40
+ GenuineResult = struct [
41
+ 'int genuine',
42
+ 'char serial[15]',
43
+ 'char provisioned_date[11]'
44
+ ]
45
+
46
+ DeviceInfo = struct [
47
+ 'char serial[15]',
48
+ 'char path[512]',
49
+ 'unsigned short vendor_id',
50
+ 'unsigned short product_id'
51
+ ]
52
+ end
53
+
54
+ # Not part of the public API.
55
+ module Native
56
+ BASENAMES = {
57
+ 'mswin' => 'keynub_licdongle.dll',
58
+ 'mingw' => 'keynub_licdongle.dll',
59
+ 'cygwin' => 'keynub_licdongle.dll',
60
+ 'darwin' => 'libkeynub_licdongle.dylib'
61
+ }.freeze
62
+
63
+ def self.default_basename
64
+ host = RbConfig::CONFIG['host_os']
65
+ BASENAMES.each { |key, name| return name if host.include?(key) }
66
+ 'libkeynub_licdongle.so'
67
+ end
68
+
69
+ # Where to look, in order. The environment override names a specific library
70
+ # to point at the simulator library.
71
+ def self.candidate_paths
72
+ override = ENV['KEYNUB_LICDONGLE_LIBRARY']
73
+ return [override] if override && !override.empty?
74
+
75
+ here = File.dirname(__FILE__)
76
+ [
77
+ File.expand_path(File.join(here, '..', '..', 'vendor', default_basename)),
78
+ # The prebuilt library a checkout of the SDK carries, per platform: what
79
+ # makes a clone runnable with nothing set.
80
+ File.expand_path(File.join(here, '..', '..', '..', '..', 'natives',
81
+ repo_rid, default_basename)),
82
+ File.expand_path(File.join(here, default_basename)),
83
+ default_basename # system search path
84
+ ]
85
+ end
86
+
87
+ # The natives/<rid> directory name for this Ruby.
88
+ def self.repo_rid
89
+ host = RbConfig::CONFIG['host_os']
90
+ os = if host.include?('mswin') || host.include?('mingw') || host.include?('cygwin')
91
+ 'win'
92
+ elsif host.include?('darwin')
93
+ 'osx'
94
+ else
95
+ 'linux'
96
+ end
97
+ arch = case RbConfig::CONFIG['host_cpu']
98
+ when 'x86_64', 'x64', 'amd64' then 'x64'
99
+ when 'i386', 'i486', 'i586', 'i686', 'x86' then 'x86'
100
+ when 'aarch64', 'arm64' then 'arm64'
101
+ else 'unknown'
102
+ end
103
+ "#{os}-#{arch}"
104
+ end
105
+
106
+ def self.load_library
107
+ errors = []
108
+ candidate_paths.each do |path|
109
+ return Fiddle.dlopen(path)
110
+ rescue Fiddle::DLError => e
111
+ errors << "#{path}: #{e.message}"
112
+ end
113
+ raise LoadError,
114
+ "could not load the keynub_licdongle native library; tried:\n #{errors.join("\n ")}"
115
+ end
116
+
117
+ LIB = load_library
118
+
119
+ INT = Fiddle::TYPE_INT
120
+ VOIDP = Fiddle::TYPE_VOIDP
121
+ SIZE_T = Fiddle::TYPE_SIZE_T
122
+ U32 = Fiddle::TYPE_INT # uint32 by value: int is 32-bit everywhere the SDK runs
123
+ VOID = Fiddle::TYPE_VOID
124
+
125
+ SIGNATURES = {
126
+ licd_version: [VOID, [VOIDP, VOIDP, VOIDP]],
127
+ licd_init: [INT, [VOIDP]],
128
+ licd_free: [VOID, [VOIDP]],
129
+ licd_set_trust_root: [INT, [VOIDP, VOIDP, SIZE_T]],
130
+
131
+ licd_enumerate: [INT, [VOIDP, VOIDP, VOIDP]],
132
+ licd_free_device_list: [VOID, [VOIDP, SIZE_T]],
133
+ licd_open: [INT, [VOIDP, VOIDP, VOIDP]],
134
+ licd_open_path: [INT, [VOIDP, VOIDP, VOIDP]],
135
+ licd_close: [VOID, [VOIDP]],
136
+
137
+ licd_get_info: [INT, [VOIDP, VOIDP]],
138
+ licd_get_serial: [INT, [VOIDP, VOIDP, SIZE_T]],
139
+
140
+ licd_verify_genuine: [INT, [VOIDP, VOIDP]],
141
+ licd_session_open: [INT, [VOIDP]],
142
+ licd_session_close: [INT, [VOIDP]],
143
+ licd_write_auth: [INT, [VOIDP, VOIDP, SIZE_T]],
144
+ licd_write_auth_rotate: [INT, [VOIDP, VOIDP, SIZE_T]],
145
+
146
+ licd_record_list: [INT, [VOIDP, VOIDP, VOIDP, VOIDP]],
147
+ licd_free_record_list: [VOID, [VOIDP, VOIDP, SIZE_T]],
148
+ licd_record_read: [INT, [VOIDP, VOIDP, U32, VOIDP, U32, VOIDP, VOIDP, VOIDP, VOIDP]],
149
+ licd_record_write: [INT, [VOIDP, VOIDP, VOIDP, U32, VOIDP, VOIDP]],
150
+ licd_record_erase: [INT, [VOIDP, VOIDP]],
151
+
152
+ licd_counter_read: [INT, [VOIDP, INT, VOIDP]],
153
+ licd_counter_increment: [INT, [VOIDP, INT, VOIDP]],
154
+
155
+ licd_app_encrypt: [INT, [VOIDP, INT, VOIDP, U32, VOIDP, VOIDP]],
156
+ licd_app_decrypt: [INT, [VOIDP, VOIDP, U32, VOIDP, VOIDP]],
157
+ licd_free_buffer: [VOID, [VOIDP]],
158
+
159
+ licd_strerror: [VOIDP, [INT]],
160
+ licd_error_detail: [VOIDP, [VOIDP]]
161
+ }.freeze
162
+
163
+ BOUND = SIGNATURES.each_with_object({}) do |(name, (ret, args)), acc|
164
+ acc[name] = Fiddle::Function.new(LIB[name.to_s], args, ret, name: name.to_s)
165
+ end.freeze
166
+
167
+ def self.call(name, *args)
168
+ BOUND.fetch(name).call(*args)
169
+ end
170
+
171
+ # --- marshalling helpers ------------------------------------------------
172
+
173
+ PTR_SIZE = Fiddle::SIZEOF_VOIDP
174
+ SIZE_T_SIZE = Fiddle::SIZEOF_SIZE_T
175
+ SIZE_T_PACK = SIZE_T_SIZE == 8 ? 'Q' : 'L'
176
+
177
+ # A writable buffer, freed by Ruby's GC.
178
+ def self.buffer(size)
179
+ Fiddle::Pointer.malloc(size, Fiddle::RUBY_FREE)
180
+ end
181
+
182
+ def self.out_pointer
183
+ buffer(PTR_SIZE)
184
+ end
185
+
186
+ def self.out_int32
187
+ buffer(4)
188
+ end
189
+
190
+ def self.out_size_t
191
+ buffer(SIZE_T_SIZE)
192
+ end
193
+
194
+ def self.read_int32(pointer)
195
+ pointer[0, 4].unpack1('l')
196
+ end
197
+
198
+ def self.read_uint32(pointer)
199
+ pointer[0, 4].unpack1('L')
200
+ end
201
+
202
+ def self.read_size_t(pointer)
203
+ pointer[0, SIZE_T_SIZE].unpack1(SIZE_T_PACK)
204
+ end
205
+
206
+ # A NUL-terminated string out of a fixed-size buffer we own.
207
+ def self.read_fixed_string(bytes)
208
+ nul = bytes.index("\0")
209
+ (nul ? bytes[0, nul] : bytes).dup.force_encoding(Encoding::UTF_8)
210
+ end
211
+
212
+ # A NUL-terminated string from a `char *` the library owns.
213
+ def self.read_c_string(address)
214
+ value = address.respond_to?(:to_i) ? address.to_i : address
215
+ return '' if value.zero?
216
+
217
+ Fiddle::Pointer.new(value).to_s.dup.force_encoding(Encoding::UTF_8)
218
+ end
219
+
220
+ # Copies `length` bytes out of a library-allocated buffer, then frees it.
221
+ def self.take_buffer(out_ptr, length)
222
+ address = out_ptr.ptr
223
+ return String.new(encoding: Encoding::BINARY) if address.to_i.zero? || length.zero?
224
+
225
+ begin
226
+ # A pointer read out of another pointer has no size of its own; tell Fiddle
227
+ # how much is really there so the read is in bounds.
228
+ address.size = length
229
+ address[0, length].dup.force_encoding(Encoding::BINARY)
230
+ ensure
231
+ call(:licd_free_buffer, address)
232
+ end
233
+ end
234
+
235
+ # A NUL-terminated C string Fiddle can pass, or NULL for nil.
236
+ def self.c_string(value)
237
+ return nil if value.nil?
238
+
239
+ "#{value}\0"
240
+ end
241
+ end
242
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KeyNubLicDongle
4
+ # The binding's version. Tracks the SDK's; the native core reports its own via
5
+ # KeyNubLicDongle::Context.library_version.
6
+ VERSION = '1.1.1'
7
+ end
@@ -0,0 +1,458 @@
1
+ # frozen_string_literal: true
2
+
3
+ # KeyNub License Dongle — Ruby binding.
4
+ #
5
+ # require 'keynub_licdongle'
6
+ #
7
+ # KeyNubLicDongle::Context.open do |ctx|
8
+ # dongle = ctx.open # first dongle, or ctx.open(serial)
9
+ # dongle.verify_genuine! # raises unless genuine
10
+ # dongle.session do |session|
11
+ # data = session.app_decrypt(blob) # <- build the licence check on this
12
+ # end
13
+ # end
14
+ #
15
+ # No gems: the FFI layer is Ruby's own Fiddle. Every call is synchronous — a
16
+ # dongle round trip is a millisecond or two of USB HID.
17
+ #
18
+ # Read docs/integration-security.md before deciding where the check goes.
19
+ # `exit unless licensed?` is one line to delete, and Ruby ships as source. What
20
+ # cannot be deleted is data the program needs and only the dongle can decrypt.
21
+
22
+ require_relative 'keynub_licdongle/version'
23
+ require_relative 'keynub_licdongle/native'
24
+ require_relative 'keynub_licdongle/errors'
25
+
26
+ module KeyNubLicDongle
27
+ # Who can decrypt data produced by Session#app_encrypt.
28
+ module Scope
29
+ DEVICE = 0 # only this one physical dongle
30
+ DEVELOPER = 1 # any dongle issued by the same developer
31
+ ALL = [DEVICE, DEVELOPER].freeze
32
+ end
33
+
34
+ SERIAL_BUFFER = 15 # LICD_SERIAL_HEX_LEN + 1
35
+ private_constant :SERIAL_BUFFER
36
+
37
+ # The library context: the entry point for finding and opening dongles.
38
+ class Context
39
+ # Yields a context and closes it afterwards, whatever happens.
40
+ def self.open
41
+ ctx = new
42
+ begin
43
+ yield ctx
44
+ ensure
45
+ ctx.close
46
+ end
47
+ end
48
+
49
+ # The native core's version, as [major, minor, patch].
50
+ def self.library_version
51
+ parts = Array.new(3) { Native.out_int32 }
52
+ Native.call(:licd_version, *parts)
53
+ parts.map { |p| Native.read_int32(p) }
54
+ end
55
+
56
+ def initialize
57
+ out = Native.out_pointer
58
+ KeyNubLicDongle.check(Native.call(:licd_init, out), 'licd_init')
59
+ @handle = out.ptr
60
+ @closed = false
61
+ end
62
+
63
+ def closed?
64
+ @closed
65
+ end
66
+
67
+ def close
68
+ return if @closed
69
+
70
+ @closed = true
71
+ Native.call(:licd_free, @handle)
72
+ @handle = nil
73
+ end
74
+
75
+ # The raw handle, for mixing this binding with direct Fiddle calls.
76
+ def handle
77
+ raise Error.new(Status::INVALID_ARGUMENT, 'the context has been closed') if @closed
78
+
79
+ @handle
80
+ end
81
+
82
+ # The SDK's diagnostic detail for the most recent failure on this thread.
83
+ def last_error_detail
84
+ Native.read_c_string(Native.call(:licd_error_detail, handle))
85
+ end
86
+
87
+ # Overrides the CA root that Dongle#verify_genuine checks against.
88
+ #
89
+ # Applications do not need this: a release build embeds the KeyNub production
90
+ # root. It exists for dongles provisioned against a different CA, and for
91
+ # vendor tooling.
92
+ def trust_root=(der)
93
+ bytes = der.to_s.b
94
+ check(Native.call(:licd_set_trust_root, handle, bytes, bytes.bytesize),
95
+ 'licd_set_trust_root')
96
+ end
97
+
98
+ # Connected dongles, as an array of hashes. Empty when none are attached,
99
+ # which is a normal result rather than an error.
100
+ def enumerate
101
+ list = Native.out_pointer
102
+ count_ptr = Native.out_size_t
103
+ check(Native.call(:licd_enumerate, handle, list, count_ptr), 'licd_enumerate')
104
+ count = Native.read_size_t(count_ptr)
105
+ base = list.ptr
106
+ return [] if count.zero? || base.to_i.zero?
107
+
108
+ begin
109
+ stride = Types::DeviceInfo.size
110
+ Array.new(count) do |i|
111
+ entry = Types::DeviceInfo.new(base + (i * stride))
112
+ {
113
+ serial: Native.read_fixed_string(entry.serial.pack('c*')),
114
+ path: Native.read_fixed_string(entry.path.pack('c*')),
115
+ vendor_id: entry.vendor_id,
116
+ product_id: entry.product_id
117
+ }
118
+ end
119
+ ensure
120
+ Native.call(:licd_free_device_list, base, count)
121
+ end
122
+ end
123
+
124
+ # Opens the dongle with this serial, or the first one found.
125
+ def open(serial = nil)
126
+ out = Native.out_pointer
127
+ check(Native.call(:licd_open, handle, Native.c_string(serial), out), 'licd_open')
128
+ Dongle.new(self, out.ptr)
129
+ end
130
+
131
+ # Opens a specific dongle by the +:path+ from #enumerate.
132
+ def open_path(path)
133
+ out = Native.out_pointer
134
+ check(Native.call(:licd_open_path, handle, Native.c_string(path), out), 'licd_open_path')
135
+ Dongle.new(self, out.ptr)
136
+ end
137
+
138
+ # Adopts a device opened through the C ABI directly. Lets this binding be
139
+ # introduced into existing Fiddle code a call at a time, and is how the test
140
+ # harness wraps a simulated device.
141
+ def adopt(device_handle)
142
+ Dongle.new(self, device_handle)
143
+ end
144
+
145
+ def check(status, operation) # :nodoc:
146
+ KeyNubLicDongle.check(status, operation, @closed ? nil : @handle)
147
+ end
148
+ end
149
+
150
+ # An open connection to a dongle. Plaintext operations here; stored data needs
151
+ # a Session.
152
+ class Dongle
153
+ def initialize(context, handle)
154
+ @context = context
155
+ @handle = handle
156
+ @closed = false
157
+ end
158
+
159
+ attr_reader :context
160
+
161
+ def closed?
162
+ @closed
163
+ end
164
+
165
+ def close
166
+ return if @closed
167
+
168
+ @closed = true
169
+ Native.call(:licd_close, @handle)
170
+ @handle = nil
171
+ end
172
+
173
+ def handle
174
+ raise Error.new(Status::INVALID_ARGUMENT, 'the dongle has been closed') if @closed
175
+
176
+ @handle
177
+ end
178
+
179
+ # Plaintext device info, as a hash.
180
+ #
181
+ # +:watchdog_reboot+ reports that the dongle's *previous* boot ended in a
182
+ # watchdog timeout — the firmware hung and reset itself. It is the only trace
183
+ # a field hang leaves behind, and a power cycle clears it, so log it.
184
+ #
185
+ # +:isolated+ reports that the dongle confirmed at boot that its USB and parsing code is fenced off
186
+ # from keys and storage. Anything that is not a dongle reports false.
187
+ def info
188
+ raw = Types::Info.malloc(Fiddle::RUBY_FREE)
189
+ @context.check(Native.call(:licd_get_info, handle, raw), 'licd_get_info')
190
+ {
191
+ protocol_version: [raw.proto_version_major, raw.proto_version_minor],
192
+ firmware_version: [raw.fw_version_major, raw.fw_version_minor, raw.fw_version_patch],
193
+ se_ready: !raw.se_ready.zero?,
194
+ provisioned: !raw.provisioned.zero?,
195
+ data_capacity: raw.data_capacity,
196
+ data_free: raw.data_free,
197
+ watchdog_reboot: !raw.watchdog_reboot.zero?,
198
+ isolated: !raw.isolated.zero?,
199
+ writeauth_rotated: !raw.writeauth_rotated.zero?
200
+ }
201
+ end
202
+
203
+ # The dongle serial as hex.
204
+ def serial
205
+ buffer = Native.buffer(SERIAL_BUFFER)
206
+ @context.check(Native.call(:licd_get_serial, handle, buffer, SERIAL_BUFFER),
207
+ 'licd_get_serial')
208
+ Native.read_fixed_string(buffer[0, SERIAL_BUFFER])
209
+ end
210
+
211
+ # Proves authenticity: the certificate chain to the trusted root plus a live
212
+ # ECDSA challenge-response. Raises unless the dongle is genuine.
213
+ def verify_genuine!
214
+ raw = Types::GenuineResult.malloc(Fiddle::RUBY_FREE)
215
+ @context.check(Native.call(:licd_verify_genuine, handle, raw), 'licd_verify_genuine')
216
+ {
217
+ genuine: !raw.genuine.zero?,
218
+ serial: Native.read_fixed_string(raw.serial.pack('c*')),
219
+ provisioned_date: Native.read_fixed_string(raw.provisioned_date.pack('c*'))
220
+ }
221
+ end
222
+
223
+ # The non-raising form, for a licence gate. Fails closed: a missing dongle, an
224
+ # I/O error and an invalid certificate all return false.
225
+ def genuine?
226
+ verify_genuine![:genuine]
227
+ rescue Error
228
+ false
229
+ end
230
+
231
+ # Opens an encrypted session (P-256 ECDH, HKDF-SHA256, AES-256-GCM). With a
232
+ # block, closes it afterwards.
233
+ def session
234
+ @context.check(Native.call(:licd_session_open, handle), 'licd_session_open')
235
+ session = Session.new(self)
236
+ return session unless block_given?
237
+
238
+ begin
239
+ yield session
240
+ ensure
241
+ session.close
242
+ end
243
+ end
244
+ alias open_session session
245
+ end
246
+
247
+ # An open encrypted session: records, counters and app-crypto.
248
+ class Session
249
+ def initialize(dongle)
250
+ @dongle = dongle
251
+ @closed = false
252
+ end
253
+
254
+ def closed?
255
+ @closed
256
+ end
257
+
258
+ # Ends the session, zeroizing the session keys on the dongle. Never raises:
259
+ # teardown is local state, and this runs from ensure blocks.
260
+ def close
261
+ return if @closed
262
+
263
+ @closed = true
264
+ Native.call(:licd_session_close, @dongle.handle) unless @dongle.closed?
265
+ end
266
+
267
+ # Elevates to the write role with the developer master key (a DER EC private
268
+ # key). This belongs in your licence-issuing tooling; never ship
269
+ # that key in the application your users run.
270
+ def authorize_write(master_key_der)
271
+ bytes = master_key_der.to_s.b
272
+ check(Native.call(:licd_write_auth, device, bytes, bytes.bytesize), 'licd_write_auth')
273
+ end
274
+
275
+ # Replaces the dongle's write-auth key with your own (a DER EC private key).
276
+ # Call authorize_write with the current key first. From the next session on,
277
+ # only the new key elevates.
278
+ def rotate_write_key(new_key_der)
279
+ bytes = new_key_der.to_s.b
280
+ check(Native.call(:licd_write_auth_rotate, device, bytes, bytes.bytesize),
281
+ 'licd_write_auth_rotate')
282
+ end
283
+
284
+ # Records stored on the dongle, as an array of {name:, size:} hashes.
285
+ def list_records
286
+ names = Native.out_pointer
287
+ sizes = Native.out_pointer
288
+ count_ptr = Native.out_size_t
289
+ check(Native.call(:licd_record_list, device, names, sizes, count_ptr), 'licd_record_list')
290
+ count = Native.read_size_t(count_ptr)
291
+ name_base = names.ptr
292
+ size_base = sizes.ptr
293
+ return [] if count.zero? || name_base.to_i.zero?
294
+
295
+ begin
296
+ Array.new(count) do |i|
297
+ name_ptr = name_base[i * Native::PTR_SIZE, Native::PTR_SIZE].unpack1(Native::SIZE_T_PACK)
298
+ {
299
+ name: Native.read_c_string(name_ptr),
300
+ size: size_base[i * 4, 4].unpack1('L')
301
+ }
302
+ end
303
+ ensure
304
+ Native.call(:licd_free_record_list, name_base, size_base, count)
305
+ end
306
+ end
307
+
308
+ # Reads a record. A block is called as +progress(done, total)+; return false
309
+ # from it to cancel, which raises OperationCancelledError.
310
+ def read_record(name, &progress)
311
+ require_name(name)
312
+ cname = Native.c_string(name)
313
+
314
+ # Probe for the size first, so progress runs monotonically from 0 to total.
315
+ got = Native.out_int32
316
+ total = Native.out_int32
317
+ probe = Native.buffer(1)
318
+ check(Native.call(:licd_record_read, device, cname, 0, probe, 1, got, total, nil, nil),
319
+ 'licd_record_read')
320
+ size = Native.read_uint32(total)
321
+ return String.new(encoding: Encoding::BINARY) if size.zero?
322
+
323
+ buffer = Native.buffer(size)
324
+ status = with_progress(progress) do |callback|
325
+ Native.call(:licd_record_read, device, cname, 0, buffer, size, got, total, callback, nil)
326
+ end
327
+ check(status, 'licd_record_read')
328
+ buffer[0, Native.read_uint32(got)].dup.force_encoding(Encoding::BINARY)
329
+ end
330
+
331
+ # Atomically replaces a record. Requires the write role.
332
+ def write_record(name, data, &progress)
333
+ require_name(name)
334
+ bytes = data.to_s.b
335
+ status = with_progress(progress) do |callback|
336
+ Native.call(:licd_record_write, device, Native.c_string(name), bytes, bytes.bytesize,
337
+ callback, nil)
338
+ end
339
+ check(status, 'licd_record_write')
340
+ nil
341
+ end
342
+
343
+ # Erases one record. Requires the write role.
344
+ def erase_record(name)
345
+ # A nil name means "erase everything" to the C API; that is #erase_all_records
346
+ # here, so an empty string cannot wipe the dongle.
347
+ require_name(name)
348
+ check(Native.call(:licd_record_erase, device, Native.c_string(name)), 'licd_record_erase')
349
+ end
350
+
351
+ # Erases every record. Requires the write role.
352
+ def erase_all_records
353
+ check(Native.call(:licd_record_erase, device, nil), 'licd_record_erase')
354
+ end
355
+
356
+ # Reads a hardware monotonic counter.
357
+ def read_counter(counter_id)
358
+ value = Native.out_int32
359
+ check(Native.call(:licd_counter_read, device, counter_id, value), 'licd_counter_read')
360
+ Native.read_uint32(value)
361
+ end
362
+
363
+ # Increments a counter and returns the new value. Irreversible: the counter is
364
+ # monotonic in hardware. Requires the write role.
365
+ def increment_counter(counter_id)
366
+ value = Native.out_int32
367
+ check(Native.call(:licd_counter_increment, device, counter_id, value),
368
+ 'licd_counter_increment')
369
+ Native.read_uint32(value)
370
+ end
371
+
372
+ # Encrypts so that only a dongle of +scope+ can decrypt.
373
+ #
374
+ # This is the pair to build a licence check on: put something the program
375
+ # genuinely needs through it, so removing the check removes the data.
376
+ def app_encrypt(scope, plaintext)
377
+ unless Scope::ALL.include?(scope)
378
+ raise ArgumentError, "scope must be Scope::DEVICE or Scope::DEVELOPER, got #{scope.inspect}"
379
+ end
380
+
381
+ bytes = plaintext.to_s.b
382
+ out = Native.out_pointer
383
+ out_len = Native.out_int32
384
+ check(Native.call(:licd_app_encrypt, device, scope, bytes, bytes.bytesize, out, out_len),
385
+ 'licd_app_encrypt')
386
+ Native.take_buffer(out, Native.read_uint32(out_len))
387
+ end
388
+
389
+ # Decrypts a blob produced by #app_encrypt, using the dongle.
390
+ def app_decrypt(packed)
391
+ bytes = packed.to_s.b
392
+ out = Native.out_pointer
393
+ out_len = Native.out_int32
394
+ check(Native.call(:licd_app_decrypt, device, bytes, bytes.bytesize, out, out_len),
395
+ 'licd_app_decrypt')
396
+ Native.take_buffer(out, Native.read_uint32(out_len))
397
+ end
398
+
399
+ private
400
+
401
+ def device
402
+ raise SessionExpiredError.new(Status::SESSION_EXPIRED, 'the session has been closed') if @closed
403
+
404
+ @dongle.handle
405
+ end
406
+
407
+ def check(status, operation)
408
+ @dongle.context.check(status, operation)
409
+ end
410
+
411
+ def require_name(name)
412
+ return unless name.nil? || name.to_s.empty?
413
+
414
+ raise ArgumentError, 'the record name must not be empty'
415
+ end
416
+
417
+ # Wraps a Ruby block as a C progress callback and returns the native status.
418
+ #
419
+ # An exception raised inside the block is held until the SDK has unwound its
420
+ # own transfer, then re-raised: letting it escape through the C frames would
421
+ # skip that cleanup and strand the device mid-transfer. It takes precedence
422
+ # over the resulting LICD_E_CANCELLED, because the callback's failure is the
423
+ # cause and the cancellation is only its consequence.
424
+ def with_progress(progress)
425
+ return yield(nil) if progress.nil?
426
+
427
+ raised = nil
428
+ callback = Fiddle::Closure::BlockCaller.new(
429
+ Fiddle::TYPE_INT, [Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP]
430
+ ) do |done, total, _user|
431
+ if raised
432
+ 0
433
+ else
434
+ begin
435
+ # Anything but an explicit false continues, so a callback that only
436
+ # draws a progress bar is safe.
437
+ progress.call(done, total) == false ? 0 : 1
438
+ rescue StandardError => e
439
+ raised = e
440
+ 0
441
+ end
442
+ end
443
+ end
444
+
445
+ # Held in an ivar, not just a local, so the closure cannot be collected while
446
+ # C holds a pointer to it.
447
+ @active_callback = callback
448
+ begin
449
+ status = yield(callback)
450
+ raise raised if raised
451
+
452
+ status
453
+ ensure
454
+ @active_callback = nil
455
+ end
456
+ end
457
+ end
458
+ end
metadata ADDED
@@ -0,0 +1,61 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: keynub_licdongle
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.1.1
5
+ platform: ruby
6
+ authors:
7
+ - KeyNub
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-09-12 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: |
14
+ Talks to a KeyNub USB-C license dongle: authenticity verification, an
15
+ encrypted session, licence records, monotonic counters, and envelope
16
+ encryption bound to the dongle. Built on Fiddle from Ruby's standard library,
17
+ so it needs no gems and no compiler.
18
+ email:
19
+ executables: []
20
+ extensions: []
21
+ extra_rdoc_files: []
22
+ files:
23
+ - BINARY-LICENSE.txt
24
+ - LICENSE
25
+ - NOTICE
26
+ - README.md
27
+ - THIRD-PARTY-NOTICES.txt
28
+ - lib/keynub_licdongle.rb
29
+ - lib/keynub_licdongle/errors.rb
30
+ - lib/keynub_licdongle/native.rb
31
+ - lib/keynub_licdongle/version.rb
32
+ homepage: https://www.keynub.com/developers/ruby/
33
+ licenses:
34
+ - Apache-2.0
35
+ - LicenseRef-KeyNub-Binary
36
+ metadata:
37
+ homepage_uri: https://www.keynub.com/developers/ruby/
38
+ source_code_uri: https://github.com/AB-KeyNub/KeyNub-SDK
39
+ documentation_uri: https://github.com/AB-KeyNub/KeyNub-SDK/blob/master/bindings/ruby/README.md
40
+ bug_tracker_uri: https://github.com/AB-KeyNub/KeyNub-SDK/issues
41
+ rubygems_mfa_required: 'true'
42
+ post_install_message:
43
+ rdoc_options: []
44
+ require_paths:
45
+ - lib
46
+ required_ruby_version: !ruby/object:Gem::Requirement
47
+ requirements:
48
+ - - ">="
49
+ - !ruby/object:Gem::Version
50
+ version: '3.0'
51
+ required_rubygems_version: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - ">="
54
+ - !ruby/object:Gem::Version
55
+ version: '0'
56
+ requirements: []
57
+ rubygems_version: 3.4.19
58
+ signing_key:
59
+ specification_version: 4
60
+ summary: Ruby binding for the KeyNub USB-C license dongle
61
+ test_files: []