|
| 1 | +// SPDX-License-Identifier: CC0-1.0 |
| 2 | + |
| 3 | +use core::marker::PhantomData; |
| 4 | +use core::mem::ManuallyDrop; |
| 5 | +use core::ptr::NonNull; |
| 6 | + |
| 7 | +use crate::context::spinlock::SpinLock; |
| 8 | +use crate::{ffi, Context, Secp256k1}; |
| 9 | + |
| 10 | +mod self_contained_context { |
| 11 | + use core::mem::MaybeUninit; |
| 12 | + use core::ptr::NonNull; |
| 13 | + |
| 14 | + use crate::ffi::types::{c_void, AlignedType}; |
| 15 | + use crate::{ffi, AllPreallocated, Context as _}; |
| 16 | + |
| 17 | + const MAX_PREALLOC_SIZE: usize = 16; // measured at 208 bytes on Andrew's 64-bit system |
| 18 | + |
| 19 | + /// A secp256k1 context object which can be allocated on the stack or in static storage. |
| 20 | + pub struct SelfContainedContext( |
| 21 | + [MaybeUninit<AlignedType>; MAX_PREALLOC_SIZE], |
| 22 | + Option<NonNull<ffi::Context>>, |
| 23 | + ); |
| 24 | + |
| 25 | + // SAFETY: the context object owns all its own data. |
| 26 | + unsafe impl Send for SelfContainedContext {} |
| 27 | + |
| 28 | + impl SelfContainedContext { |
| 29 | + /// Creates a new uninitialized self-contained context. |
| 30 | + pub const fn new_uninitialized() -> Self { |
| 31 | + Self([MaybeUninit::uninit(); MAX_PREALLOC_SIZE], None) |
| 32 | + } |
| 33 | + |
| 34 | + /// Accessor for the underlying raw context pointer |
| 35 | + fn buf(&mut self) -> NonNull<c_void> { |
| 36 | + NonNull::new(self.0.as_mut_ptr() as *mut c_void).unwrap() |
| 37 | + } |
| 38 | + |
| 39 | + pub fn clone_into(&mut self, other: &mut SelfContainedContext) { |
| 40 | + // SAFETY: just FFI calls |
| 41 | + unsafe { |
| 42 | + let other = other.raw_ctx().as_ptr(); |
| 43 | + assert!( |
| 44 | + ffi::secp256k1_context_preallocated_clone_size(other) |
| 45 | + <= core::mem::size_of::<[AlignedType; MAX_PREALLOC_SIZE]>(), |
| 46 | + "prealloc size exceeds our guessed compile-time upper bound", |
| 47 | + ); |
| 48 | + ffi::secp256k1_context_preallocated_clone(other, self.buf()); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + /// Accessor for the context as a raw context pointer. |
| 53 | + /// |
| 54 | + /// On the first call, this will create the context. |
| 55 | + pub fn raw_ctx(&mut self) -> NonNull<ffi::Context> { |
| 56 | + let buf = self.buf(); |
| 57 | + *self.1.get_or_insert_with(|| { |
| 58 | + // SAFETY: just FFI calls |
| 59 | + unsafe { |
| 60 | + assert!( |
| 61 | + ffi::secp256k1_context_preallocated_size(AllPreallocated::FLAGS) |
| 62 | + <= core::mem::size_of::<[AlignedType; MAX_PREALLOC_SIZE]>(), |
| 63 | + "prealloc size exceeds our guessed compile-time upper bound", |
| 64 | + ); |
| 65 | + ffi::secp256k1_context_preallocated_create(buf, AllPreallocated::FLAGS) |
| 66 | + } |
| 67 | + }) |
| 68 | + } |
| 69 | + } |
| 70 | +} |
| 71 | +// Needs to be pub(super) so that we can define a constructor for |
| 72 | +// SpinLock<SelfContainedContext> in the spinlock module. (We cannot do so generically |
| 73 | +// because we need a const constructor.) |
| 74 | +pub(super) use self_contained_context::SelfContainedContext; |
| 75 | + |
| 76 | +static SECP256K1: SpinLock<SelfContainedContext> = SpinLock::new(); |
| 77 | + |
| 78 | +/// Borrows the global context and do some operation on it. |
| 79 | +/// |
| 80 | +/// If `randomize_seed` is provided, it is used to rerandomize the context after the |
| 81 | +/// operation is complete. If it is not provided, randomization is skipped. |
| 82 | +/// |
| 83 | +/// Only a bit or two per signing operation is needed; if you have any entropy at all, |
| 84 | +/// you should provide it, even if you can't provide 32 random bytes. |
| 85 | +pub fn with_global_context<T, Ctx: Context, F: FnOnce(&Secp256k1<Ctx>) -> T>( |
| 86 | + f: F, |
| 87 | + rerandomize_seed: Option<&[u8; 32]>, |
| 88 | +) -> T { |
| 89 | + with_raw_global_context( |
| 90 | + |ctx| { |
| 91 | + let secp = ManuallyDrop::new(Secp256k1 { ctx, phantom: PhantomData }); |
| 92 | + f(&*secp) |
| 93 | + }, |
| 94 | + rerandomize_seed, |
| 95 | + ) |
| 96 | +} |
| 97 | + |
| 98 | +/// Borrows the global context as a raw pointer and do some operation on it. |
| 99 | +/// |
| 100 | +/// If `randomize_seed` is provided, it is used to rerandomize the context after the |
| 101 | +/// operation is complete. If it is not provided, randomization is skipped. |
| 102 | +/// |
| 103 | +/// Only a bit or two per signing operation is needed; if you have any entropy at all, |
| 104 | +/// you should provide it, even if you can't provide 32 random bytes. |
| 105 | +pub fn with_raw_global_context<T, F: FnOnce(NonNull<ffi::Context>) -> T>( |
| 106 | + f: F, |
| 107 | + rerandomize_seed: Option<&[u8; 32]>, |
| 108 | +) -> T { |
| 109 | + // Our function may be expensive, so before calling it, we copy the global |
| 110 | + // context into this local buffer on the stack. Then we can release it, |
| 111 | + // allowing other callers to use it simultaneously. |
| 112 | + let mut ctx = SelfContainedContext::new_uninitialized(); |
| 113 | + if let Some(mut guard) = SECP256K1.try_lock() { |
| 114 | + let global_ctx = &mut *guard; |
| 115 | + ctx.clone_into(global_ctx) |
| 116 | + // (the lock is now dropped) |
| 117 | + } |
| 118 | + |
| 119 | + // Obtain a raw pointer to the context, creating one if it has not been already, |
| 120 | + // and call the function. |
| 121 | + let ctx_ptr = ctx.raw_ctx(); |
| 122 | + let ret = f(ctx_ptr); |
| 123 | + |
| 124 | + // ...then rerandomize the local copy, and try to replace the global one |
| 125 | + // with this. There are three cases for how this can work: |
| 126 | + // |
| 127 | + // 1. In the happy path, we succeeded in getting the lock above, have |
| 128 | + // a copy of the global context, are rerandomizing and storing it. |
| 129 | + // Great. |
| 130 | + // 2. Same as above, except that another thread is doing the same thing |
| 131 | + // in parallel. Now we both have copies that we're rerandomizing, and |
| 132 | + // both will try to store it. One of us will clobber the other, wasting |
| 133 | + // work but otherwise not causing any problems. |
| 134 | + // 3. If we -failed- to get the lock above, we are rerandomizing a fresh |
| 135 | + // copy of the context object. This may "undo" previous rerandomization. |
| 136 | + // In theory if an attacker is able to reliably and repeatedly trigger |
| 137 | + // this situation, they will have defeated the rerandomization. Since |
| 138 | + // this is a defense-in-depth measure, we will accept this. |
| 139 | + if let Some(seed) = rerandomize_seed { |
| 140 | + // SAFETY: just a FFI call |
| 141 | + unsafe { |
| 142 | + assert_eq!(ffi::secp256k1_context_randomize(ctx_ptr, seed.as_ptr()), 1); |
| 143 | + } |
| 144 | + if let Some(ref mut guard) = SECP256K1.try_lock() { |
| 145 | + guard.clone_into(&mut ctx); |
| 146 | + } |
| 147 | + } |
| 148 | + ret |
| 149 | +} |
| 150 | + |
| 151 | +/// Rerandomize the global context, using the given data as a seed. |
| 152 | +/// |
| 153 | +/// The provided data will be mixed with the entropy from previous calls in a timing |
| 154 | +/// analysis resistant way. It is safe to directly pass secret data to this function. |
| 155 | +pub fn rerandomize_global_context(seed: &[u8; 32]) { with_raw_global_context(|_| {}, Some(seed)) } |
0 commit comments