Debian Codegraph @

ref10/README.md

raw symbols SCIP
1 # Extracting ref10 from SUPERCOP #
2
3 To implement XEdDSA, access to low-level cryptographic functions is required, which are usually not exported by crypto-libraries.
4
5 ref10 by Daniel J. Bernstein is a solid implementation of these low-level functions. It comes as part of the [SUPERCOP](https://bench.cr.yp.to/supercop.html) benchmark and is not available as a standalone library.
6
7 This guide explains the steps to extract the ref10 implementation from the SUPERCOP benchmarking system.
8
9 __NOTE__: You do __NOT__ have to follow this guide to use libxeddsa.
10
11 __NOTE__: The SUPERCOP benchmark assumes a UNIX-like system and so does the first part of this guide. The following steps explain how to extract the required C source code and how to compile it into static libraries and shared object files. Section `3. Making the code portable` contains notes about cross-platform usage.
12
13 ### 1. Download and run the benchmark ###
14
15 The first step is to download and run the benchmark. The benchmark generates some files on-the-fly, based on the hosts os/system architecture. Some of these generated files are required to build ref10 standalone, that's why the benchmark has to run first. Note that the benchmark is HUGE and it may take multiple days to finish one run. Follow the instructions [here](https://bench.cr.yp.to/supercop.html) to run the "Alternative: Incremental benchmarks".
16
17 __NOTE__: Consider actually closing all other applications and running the benchmark as intended, look at the SUPERCOP website for additional information.
18
19 __NOTE__: It is probably easier to "guess" how the missing files have to look like instead of running the whole benchmark just to have them generated.
20
21 ### 2. Extract the ref10 source code ###
22
23 After running the benchmark there is a `supercop-YYYYMMDD` directory with the original benchmark files and a `supercop-data` directory with the results of the run. The first one will be referred to as the base directory and the second one as the data directory.
24
25 Only one module is required to implement XEdDSA: The `crypto_sign` module for the Ed25519 signature scheme. For completeness this guide also covers how to extract the second part of the ref10 implementation: `crypto_scalarmult` for Curve25519. The following steps explain how to compile static libraries and shared object files for each of these two modules.
26
27 ### 2.1. crypto_scalarmult ###
28
29 The ref10 source code for the `crypto_scalarmult` module can be found in the base directory, following `crypto_scalarmult/curve25519/ref10`.
30
31 Bernstein uses scripts to generate some of his files, one of the tools he's using is called `qhasm`, other files are generated by Python scripts.
32 Luckily, he uploaded the generated files, so there is no need to install qhasm and reproduce this step.
33
34 For that reason, it is safe to delete his Makefiles and everything else related to qhasm and Python:
35
36 - All `*.do` files
37 - All `*.q` files
38 - All `*.py` files
39 - The Makefiles
40
41 The remaining files are almost enough to generate the shared object for this module, just a few files generated by the benchmark are missing.
42
43 A couple of files that define fixed-size integers are missing. Those are located inside of the data directory, following the path `inttypes/include/<architecture>`.
44
45 Now just two more header files are missing: `crypto_scalarmult.h` and `crypto_scalarmult_curve25519.h`. The benchmark runs each module with a set of different compiler arguments, e.g. with different optimization levels. It creates a unique directory for each of the configurations, located inside of the data directory. The benchmark puts additional generated header files into these directores, including the two headers for the `crypto_scalarmult` module. The full path to the header files looks like this: `<architecture>/try/c/<configuration>/crypto_scalarmult/curve25519/ref10/compiled`. It does not matter which architecture or configuration, the headers are the same for all of them. This guide uses the `amd64` architecture and the `gcc` configuration.
46
47 These are the three locations that contain all the code required to build the static library and the shared object file.
48 The compiler needs to know where to find these files. This can be accomplished by either copying all files into one common directory or by using the `-I<path>` option to tell `gcc` about the locations.
49
50 Possible commands to build the shared object:
51
52 ```bash
53 $ # Compile the sources to object files.
54 $ gcc -Wall -Werror -Iinttypes -c -fpic -x c *.c
55 $ # Link the object files into a shared object.
56 $ gcc -Wall -Werror -shared -Wl,--no-undefined -o libcrypto_scalarmult.so *.o
57 $ # Pack the object files into a static library.
58 $ ar rcs libcrypto_scalarmult.a *.o
59 ```
60
61 ### 2.2. crypto_sign ###
62
63 The `crypto_sign` module is a lot trickier, because it has quite a few dependencies. Most of these are easy to build though. `crypto_sign` needs:
64
65 - An implementation of sha512
66 - An implementation of 32 byte verification
67 - A random number source
68
69 The benchmark comes with multiple implementations for each of these dependencies and automatically selects the best performing one. This guide focusses on portable implementations, using ref10 or its predecessor ref whenever possible.
70
71 ### 2.2.1. Collecting dependencies ###
72
73 Some of the dependencies have more dependencies themselves. The next section creates a summary of all modules that need to be built.
74
75 #### sha512 ####
76
77 The benchmark comes with a ref implementation of sha512, which is located in `crypto_hash/sha512/ref`. This implementation uses another module: sha512 hashblocks, which comes with a ref implementation as well (`crypto_hashblocks/sha512/ref`).
78
79 #### 32 byte verification ####
80
81 The only implementation available for 32 byte verification is a ref implementation found in `crypto_verify/32/ref`.
82
83 #### random number source ####
84
85 The `fastrandombytes` module generates random data by initializing a stream cipher using just a few secure bytes retrieved from the operating system. It depends on `kernelrandombytes` to get secure bytes from the os and on `crypto_rng` to generate more random data from the kernel bytes. `fastrandombytes` and `kernelrandombytes` boath are fixed implementations. `crypto_rng` comes with multiple different implementations again.
86
87 #### crypto_rng ####
88
89 This guide uses the salsa20 rng, because all dependencies are available as ref implementations. The module path is `crypto_rng/salsa20/ref`, which depends on a salsa20 stream cipher implementation.
90
91 #### salsa20 stream cipher ####
92
93 Again, a ref implementation, located at `crypto_stream/salsa20/ref`, which depends on a salsa20 implementation.
94
95 #### salsa20 ####
96
97 This is the last one! Another ref implementation, located at `crypto_core/salsa20/ref`.
98
99 ### 2.2.2. Dependencies summarized ###
100
101 Following modules can all be compiled the same way:
102
103 - `crypto_hash/sha512/ref`
104 - `crypto_hashblocks/sha512/ref`
105 - `crypto_verify/32/ref`
106 - `crypto_rng/salsa20/ref`
107 - `crypto_stream/salsa20/ref`
108 - `crypto_core/salsa20/ref`
109 - `fastrandombytes`
110
111 The only module that needs special treatment is `kernelrandombytes`.
112
113 ### 2.2.3. The easy ones ###
114
115 __NOTE__: To keep things simple, this guide only shows how to pack the dependencies into static libraries. Because static libraries are not linked, static libraries do not check references at build-time, which simplifies the following steps a lot.
116
117 The source code of each of these modules is split into two locations, with the exception of `fastrandombytes`, which has all of its sources in the base directory:
118
119 - The main sources in the base directory
120 - The additional generated sources in the data directory
121
122 These commands show how to build the static library for `crypto_hash/sha512/ref`, it works just the same way for the other modules:
123
124 ```bash
125 $ # Copy the main source files into a new directory
126 $ cp -r <base>/crypto_hash/sha512/ref/ sha512
127 $ cd sha512
128 $ # Copy the additional generated source, if necessary
129 $ cp <data>/amd64/try/c/gcc/crypto_hash/sha512/ref/compiled/crypto_hash.h .
130 $ cp <data>/amd64/try/c/gcc/crypto_hash/sha512/ref/compiled/crypto_hash_sha512.h .
131 $ # Compile the source files into object files
132 $ gcc -Wall -Werror -c -fpic -x c *.c
133 $ # Package the object files into a static library
134 $ ar rcs libcrypto_hash.a *.o
135 ```
136
137 Use the `-I<path>` option to tell gcc where to find missing headers.
138
139 ### 2.2.4. `kernelrandombytes` ###
140
141 The `kernelrandombytes` module is the only one containing os-dependent code. It contains different implementations of the same function, where each implementation uses different APIs that may be available on some operating system and may not be available on other ones. The idea is to just use the first file that compiles successfully. Only use the `urandom.c` file if all other options fail on your os, it is the least stable/secure one. [This article](https://lwn.net/Articles/606141/) has an interesting explanation why using system calls is better then relying on `/dev/urandom`.
142
143 ### 2.2.5. Putting it all together ###
144
145 As usual the `crypto_sign` module has its main sources in the base directory, located at `crypto_sign/ed25519/ref10` and some benchmark generated source found in your data directory.
146
147 The sources include a `fe.h` header file. This file contains declarations for two external functions `fe_cswap` and `fe_mul121666`, which neither exist nor are being used by the remaining code. These were probably included by accident. Some systems, such as [cffi](https://bitbucket.org/cffi/cffi/), may get confused by these orphaned declarations. To fix this, the following lines have to be deleted:
148
149 ```cpp
150 ...
151 #define fe_cswap crypto_sign_ed25519_ref10_fe_cswap
152 ...
153 #define fe_mul121666 crypto_sign_ed25519_ref10_fe_mul121666
154 ...
155 extern void fe_cswap(fe,fe,unsigned int);
156 ...
157 extern void fe_mul121666(fe,const fe);
158 ...
159 ```
160
161 Finally, all the dependencies can be linked together using following commands:
162
163 ```bash
164 $ gcc -Wall -Werror -Iinttypes -Icrypto_hash -c -fpic -x c *.c
165 $ gcc -Wall -Werror -shared -Wl,--no-undefined -o libcrypto_sign.so *.o -lcrypto_hash -lcrypto_hashblocks -lcrypto_verify -lfastrandombytes -lkernelrandombytes -lcrypto_rng -lcrypto_stream -lcrypto_core
166 ```
167
168 Or another static library can be built:
169
170 ```bash
171 $ ar rcs libcrypto_sign.so *.o
172 ```
173
174 __NOTE__: When using the static library, ALL the static libraries of ALL recursive dependencies have to be linked aswell, e.g.:
175
176 ```bash
177 $ gcc -c someCodeUsingLibCryptoSign.c
178 $ gcc -o out *.o -lcrypto_sign -lcrypto_hash -lcrypto_hashblocks -lcrypto_verify -lfastrandombytes -lkernelrandombytes -lcrypto_rng -lcrypto_stream -lcrypto_core
179 ```
180
181 ### 3. Making the code portable ###
182
183 This section addresses the topic of making the code portable/platform-independent.
184
185 ### 3.1. Fixed-width integers ###
186
187 The first step is to replace the hardcoded int-type headers that were generated by the SUPERCOP benchmarking system with platform-independent int-type definitions.
188
189 The `stdint.h` header is available for all major C-toolchains and offers fixed-width integer types. As an example this guide shows the refactoring of the `crypto_uint64.h` header.
190
191 Before refactoring the file looks something like this:
192
193 ```cpp
194 #ifndef crypto_uint64_h
195 #define crypto_uint64_h
196
197 typedef unsigned long long crypto_uint64;
198
199 #endif
200 ```
201
202 This code can be made platform-independent be replacing it with following:
203
204 ```cpp
205 #ifndef crypto_uint64_h
206 #define crypto_uint64_h
207
208 #include <stdint.h>
209
210 typedef uint64_t crypto_uint64;
211
212 #endif
213 ```
214
215 In the same way all int-type headers can be refactored, using following mapping:
216
217 | header | stdint type |
218 |:----------------|:------------|
219 | crypto_int8.h | int8_t |
220 | crypto_int16.h | int16_t |
221 | crypto_int32.h | int32_t |
222 | crypto_int64.h | int64_t |
223 | crypto_uint8.h | uint8_t |
224 | crypto_uint16.h | uint16_t |
225 | crypto_uint32.h | uint32_t |
226 | crypto_uint64.h | uint64_t |
227
228 ### 3.2. Cross-platform kernelrandombytes ###
229
230 The kernelrandombytes module uses system-dependent code to retrieve cryptographically secure random bytes.
231
232 The version shipped with SUPERCOP only contains implementations for UNIX-like systems.
233
234 This section covers adding an implementation for Windows.
235
236 On Windows there are two main sources for cryptographically secure random bytes: `CryptGenRandom` and `rand_s`. Both have major disadvantages:
237
238 - `CryptGenRandom` requires to load the whole Windows CryptoAPI. It requires to create a crypto context first which is a lot of overhead.
239 - `rand_s` is part of the Windows CRT, thus requires to load the whole CRT. Also, `rand_s` yields only one random integer, which creates a lot of call overhead to get larger amounts of random bytes.
240
241 Both methods have one thing in common: Under the hood they both use `RtlGenRandom`, which is the most convenient way to get random data. It neither has extensive call overhead nor does it only return a small number of bytes.
242
243 The `RtlGenRandom` [documentation](https://docs.microsoft.com/en-us/windows/desktop/api/ntsecapi/nf-ntsecapi-rtlgenrandom) includes a warning that the function "may be altered or unavailable in subsequent versions". [Various](https://bugzilla.mozilla.org/show_bug.cgi?id=504270) [sources](https://blogs.msdn.microsoft.com/michael_howard/2005/01/14/cryptographically-secure-random-number-on-windows-without-using-cryptoapi/) [state](https://github.com/jedisct1/libsodium/blob/master/src/libsodium/randombytes/sysrandom/randombytes_sysrandom.c), that the `RtlGenRandom` function is indeed safe to use and will not disappear (note: some of the sources are from 2005 and 2009 and the function is still here). Also Firefox and Chrome/Chromium are said to use the function.
244
245 The function is available from Windows XP SP3 on, a requirement which I rate acceptable for this guide.
246
247 An implementation of the `kernelrandombytes` function using `RtlGenRandom` could look like this (has to be linked with `-lADVAPI32`):
248
249 ```cpp
250 #include <Windows.h>
251
252 #define RtlGenRandom SystemFunction036
253
254 #ifdef __cplusplus
255 extern "C" {
256 #endif
257 BOOLEAN NTAPI RtlGenRandom(PVOID RandomBuffer, ULONG RandomBufferLength);
258 #ifdef __cplusplus
259 }
260 #endif
261
262 void kernelrandombytes(unsigned char *x,unsigned long long xlen)
263 {
264 int i;
265
266 while (xlen > 0) {
267 if (xlen < 256) i = xlen; else i = 256;
268 RtlGenRandom(x, i);
269 x += i;
270 xlen -= i;
271 }
272 }
273 ```
274
275 __NOTE__: The documentation of `RtlGenRandom` states that the function could fail.
276 Sadly, the documentation does not state WHY the function could fail.
277 This makes it impossible to know how to react to such a failure, thus the possible failure gets ignored in the example above.
278
279 ### 3.3. Cross-platform dynamic libraries ###
280
281 The guide uses `gcc` to compile the sources into shared object files and `ar` to create static libraries.
282
283 This section covers the required commands to build static and dynamic versions of the libraries on Windows and Mac.
284 Generally it is probably a good idea to use [CMake](https://cmake.org/) if cross-platform compilation is the goal.
285
286 ### 3.3.1 Windows ###
287
288 On Windows, [MinGW](http://www.mingw.org/) or it's 64-bit pendant [MinGW-w64](https://mingw-w64.org/doku.php) offers an open source `gcc` environment, which allows to use slightly modified UNIX commands to compile Windows-native static and dynamic libraries.
289
290 The file extension for dynamic libraries is `.dll` and for static libraries `.lib`.
291 Dynamic libraries come with an additional static library called "import library", which contains the code to load the corresponding dynamic library.
292 Import libraries don't have a specific extension, this guide will use `.dll.lib`.
293
294 #### Adjusting the code ####
295
296 All C code needs to be extended to tell Windows which functions to export/import into/from the library.
297
298 `__declspec(dllexport)` marks a function as exported:
299
300 ```cpp
301 // some_header.h
302
303 extern void __declspec(dllexport) myExportedFunction();
304 ```
305
306 To use the library, the function has to be marked as imported using `__declspec(dllimport)`:
307 ```cpp
308 // some_header.h
309
310 extern void __declspec(dllimport) myExportedFunction();
311 ```
312
313 #### Static libraries ####
314
315 MinGW comes with the `ar` tool, which can be used just the same way as on some UNIXes to build static libraries:
316
317 ```bash
318 $ gcc -c -fpic *.c
319 $ ar rcs mylib.lib *.o
320 ```
321
322 #### Dynamic libraries ####
323
324 These are example commands for UNIX:
325
326 ```bash
327 $ gcc -c -fpic *.c
328 $ gcc -shared -Wl,--no-undefined -o libmylib.so *.o
329 ```
330
331 To build the same on Windows, the file extensions have to be adjusted and `gcc` has to be told to build an import library as well:
332
333 ```bash
334 $ gcc -c -fpic *.c
335 $ gcc -shared -Wl,--no-undefined -Wl,--out-implib,mylib.dll.lib -o mylib.dll *.o
336 ```
337
338 ### 3.3.2 Mac OS ###
339
340 I'll add this section as soon as I get access to a system running Mac OS.