Expand description
Safe bindings for the Windows Notification Facility
The Windows Notification Facility (WNF) is a registrationless publisher/subscriber mechanism that was introduced in Windows 8 and forms an undocumented part of the Windows API.
This crate provides safe Rust abstractions over (a part of) this API. If you are looking for raw bindings to the
API, take a look at the ntapi
crate.
Note that while great care was taken in making these abstractions memory-safe, there cannot be a guarantee due to the undocumented nature of the API.
This is a Windows-only crate and will fail to compile on other platforms. If you target multiple platforms, it is recommended that you declare it as a platform specific dependency.
§How WNF works
WNF is built upon the core concept of a state name. Processes can publish to and subscribe to a state name, represented by a 64-bit identifier. In this crate, in order to distinguish between such an identifier and the actual operating system object it represents, we call the identifier a state name, while the underlying object will be referred to as a state.
A state can have different lifetimes:
- A well-known state is provisioned with the system and cannot be created or deleted.
- A permanent state can be created and stays alive even across system reboots until it is explicitly deleted.
- A persistent or volatile state can be created and stays alive until the next system reboot or until it is explicitly deleted.
- A temporary state can be created and stays alive until the process it was created from exits or until it is explicitly deleted.
For details, see StateLifetime
.
A state has an associated payload, called the state data or state value, of up to 4 KB in size. Processes can query and update these data and subscribe to changes of the data. Furthermore, a state has an associated change stamp, which starts at zero when the state is created and increases by one on every update of the data.
A state that lives across system reboots (i.e. with well-known or permanent lifetime) can be configured to persist its data across reboots. Otherwise, the state itself stays alive but its data is reset on reboots.
A state can have different data scopes that control whether it maintains multiple independent instances of its
data that are scoped in different ways. See DataScope
for the available options.
A state can have an associated type id, which is a GUID that identifies the type of the data. While WNF does not maintain a registry of types itself, it can ensure that state data are only updated if the correct type id is provided. This can be useful if you maintain your own type registry or just want to avoid accidental updates with invalid data.
Access to a state is secured by a standard
Windows Security Descriptor. In
addition, creating a permanent or persistent state or a state with process scope requires the
SeCreatePermanentPrivilege
privilege.
The WNF mechanism, though officially undocumented, has been described by various sources. Its API is part of the
Windows Native API exposed through ntdll.dll
and has been (partly) reverse engineered and described. For details,
refer to these sources:
- A. Allievi et al.: Windows Internals, Part 2, 7th Edition, p. 224ff.
- Quarkslab’s Blog: Playing with the Windows Notification Facility (WNF)
- A. Ionescu, G. Viala: The Windows Notification Facility: Peeling the Onion of the Most Undocumented Kernel Attack Surface Yet, Talk at black hat USA 2018
- A. Ionescu, G. Viala: WNF Utilities 4 Newbies (WNFUN), including a list of the names of well-known states
§What this crate offers
This crate provides memory-safe abstractions over most of the WNF API to accomplish these tasks:
- Create and delete a state
- Query information on a state
- Query and update state data
- Subscribe to state data
Subscribing uses higher-level functions from ntdll.dll
whose names start with Rtl
, standing for runtime
library:
RtlSubscribeWnfStateChangeNotification
RtlUnsubscribeWnfStateChangeNotification
The other features use more low-level functions from ntdll.dll
whose names start with Nt*
:
NtCreateWnfStateName
NtDeleteWnfStateName
NtQueryWnfStateNameInformation
NtQueryWnfStateData
NtUpdateWnfStateData
In addition, this crate provides some higher-level abstractions:
- Apply a transformation to state data
- Replace state data
- Wait for updates of state data (in both blocking and async variants)
- Wait until state data satisfy a certain condition (in both blocking and async variants)
The following WNF features are currently not supported:
- Subscriptions in meta-notification mode, i.e. subscribing to consumers becoming active or inactive or publishers terminating
- Event aggregation through the Common Event Aggregator to subscribe to updates of one out of multiple states
- Kernel mode
§Representing states
There are two types in this crate that represent states: OwnedState<T>
and BorrowedState<'_, T>
. They work in a similar way as the OwnedHandle
and
BorrowedHandle<'_>
types from the standard library:
- An
OwnedState<T>
has no lifetime, does not implementCopy
orClone
and deletes the represented state on drop. - A
BorrowedState<'_, T>
has a lifetime, implementsCopy
andClone
and does not delete the represented state on drop.
Note that copying/cloning a BorrowedState<'_, T>
just copies the borrow, returning another borrow
of the same underlying state, rather than cloning the state itself.
You can abstract over ownership (i.e. whether a state is owned or borrowed) through the AsState
trait and its
as_state
method. This trait is similar to the AsHandle
trait in the standard library and is implemented by both OwnedState<T>
and BorrowedState<'_, T>
as well as any type that derefs to one of these types. Calling as_state
on an OwnedState<T>
borrows it as a BorrowedState<'_, T>
while calling it on a
BorrowedState<'_, T>
just copies the borrow.
You can obtain an instance of OwnedState<T>
or BorrowedState<'_, T>
in the following ways:
- Create a new owned state through the
StateCreation::create_owned
method
This is common for temporary states, for which there is also theOwnedState::create_temporary
shortcut method. - Create a new state and statically borrow it through the
StateCreation::create_static
method
This is common for permanent or persistent states. - Statically borrow an existing state through the
BorrowedState::from_state_name
method
This is common for well-known states.
An owned state can be “leaked” as a statically borrowed state through the OwnedState::leak
method, while a
borrowed state can be turned into an owned state through the BorrowedState::to_owned_state
method.
§Representing state data
The types OwnedState<T>
and BorrowedState<'_, T>
are generic over a type T
that describes
the shape of the data associated with the state.
The state types themselves impose no trait bounds on the data type. However, in order for querying or updating state data to be memory-safe, the data type needs to satisfy certain conditions:
- Querying state data as a
T
requires that any byte slice whose length is the size ofT
represent a validT
or that it can at least be checked at runtime whether it represents a validT
. - Updating state data from a
T
requires that the typeT
contain no uninitialized (i.e. padding) bytes.
These conditions cannot be checked at runtime and hence need to be encoded in the type system.
Note that querying state data as a T
also requires that the size of the state data match the size of T
in the
first place, but this condition can be checked at runtime. In fact, the data type can also be a slice type [T]
, in
which case the size of the state data is required to be a multiple of the size of T
.
Defining how to properly encode the above conditions in the type system is part of the scope of the Project “safe transmute”, which is still in RFC stage. However, there are various third-party crates that define (unsafe) traits encoding the above conditions, among them being the bytemuck and zerocopy crates. Both of them implement the appropriate traits for many standard types and also provide macros to derive them for your own types, checking at compile-time whether a type satisfies the necessary conditions and enabling you to avoid unsafe code in most cases.
The wnf
crate does not have a hard dependency on any of these crates. Instead, it defines its own
(unsafe) traits that are modelled after the traits from the bytemuck crate
with the same names:
AnyBitPattern
andCheckedBitPattern
encode the requirements for querying state dataNoUninit
encodes the requirements for updating state data
These traits are already implemented for many standard types. In case your code already makes use of one of the bytemuck or zerocopy crates or you want to take advantage of the derive macros provided by either of those crates, you can do the following:
- Enable the
bytemuck_v1
resp.zerocopy
feature of this crate (producing a dependency on bytemuck v1 resp. zerocopy) - Implement the appropriate trait from one of these crates for your type, e.g. by using a derive macro
- Derive the corresponding trait from the
wnf
crate using thederive_from_bytemuck_v1
resp.derive_from_zerocopy
macros. See the documentations of these macros for examples.
All methods that query state data require the data type to
- either be a type
T
that implementsCheckedBitPattern
- or be a slice type
[T]
where the element typeT
implementsCheckedBitPattern
In addition, they exist in non-boxed and boxed variants, e.g. OwnedState::get
and OwnedState::get_boxed
. The
non-boxed variants query the data by value (i.e. on the stack), but require the data type T
to be Sized
.
The boxed variants work for both sized and unsized data types T
and query the data as a Box<T>
(i.e. allocated
on the heap). All of this is encapsulated in the Read<T>
trait where
T: Read<T>
means thatT
can be read by valueT: Read<Box<T>>
means thatT
can be read as a box
Note that methods that update state data don’t make a distinction between sized and unsized types/slices or boxed and non-boxed variants because they take the data by reference.
If you want to be able to support arbitrary state data without any restriction on the size (apart from the upper
bound of 4 KB), you can always use a byte slice [u8]
as the data type. In the rare case that you want to query a
state without caring about the content of the data at all, you can use the OpaqueData
type. This is useful e.g.
if you just want to query the size or if you want to check if you have the right permissions to query the state.
§Examples
For more detailed examples, see the examples
folder in the crate repository. Some common use cases:
§Creating a state and querying/updating its data
use wnf::{CreatableStateLifetime, DataScope, OwnedState, StateCreation};
let state: OwnedState<u32> = StateCreation::new()
.lifetime(CreatableStateLifetime::Temporary)
.scope(DataScope::Machine)
.create_owned()?;
state.set(&42)?;
assert_eq!(state.get()?, 42);
§Reading a wide string from a well-known state
use std::ffi::{OsStr, OsString};
use std::os::windows::ffi::OsStringExt;
use wnf::BorrowedState;
const WNF_SHEL_DESKTOP_APPLICATION_STARTED: u64 = 0x0D83063EA3BE5075;
let state = BorrowedState::<[u16]>::from_state_name(WNF_SHEL_DESKTOP_APPLICATION_STARTED);
let last_application_started_wide = {
let data = state.get_boxed()?;
OsString::from_wide(&data)
};
println!("{}", last_application_started_wide.to_string_lossy());
§Subscribing to a well-known state
This requires the subscribe
feature flag to be enabled.
use std::io::{stdin, Read};
use wnf::{BorrowedState, DataAccessor, OwnedState, SeenChangeStamp};
const WNF_PO_DISCHARGE_ESTIMATE: u64 = 0x41C6013DA3BC5075;
let state = BorrowedState::<u64>::from_state_name(WNF_PO_DISCHARGE_ESTIMATE);
let subscription = state.subscribe(
|accessor: DataAccessor<'_, _>| {
println!("Estimated battery duration in seconds: {}", accessor.get().unwrap());
},
SeenChangeStamp::Current,
)?;
stdin().read_exact(&mut [0u8])?; // wait for keypress
subscription.unsubscribe()?;
§Tracing
This crate emits diagnostic information using the tracing
crate whenever there is an interaction with the WNF
API. For guidance on how to subscribe to this information, consult the tracing
documentation. The general
structure is like this:
- For every invocation of a WNF API function by the
wnf
crate, anEvent
with the following payload is emitted:- The
target
is alwayswnf::ntapi
. - The
level
isDEBUG
. - The message is the name of the WNF API routine.
- The
fields
consist of three groups:result
: The result (return code) of the invocationinput.*
: Inputs of the invocation, depending on the routineoutput.*
: Outputs of the invocation, depending on the routine
- The
- For every invocation of a callback function in the
wnf
crate, aSpan
with the following payload is emitted:
See the examples
folder in the crate repository for examples on how to subscribe to these events and spans.
§Cargo features
This crate has various feature flags, none of which are enabled by default. They fall into two groups:
-
Features enabling compatibility with other crates:
bytemuck_v1
: Enables the optional bytemuck dependency and provides thederive_from_bytemuck_v1
macrouuid
: Enables the optional uuid dependency and provides conversions between theuuid::Uuid
andwnf::GUID
typeswinapi
: Enables the optional winapi dependency and provides conversions between thewinapi::shared::guiddef::GUID
andwnf::GUID
typeswindows
: Provides conversions between thewindows::core::GUID
andwnf::GUID
types (thewindows
dependency is not optional because it is also used bywnf
internally)windows_permissions
: Enables the optional windows-permissions dependency and enables the use ofwindows_permissions::SecurityDescriptor
when creating a statezerocopy
: Enables the optional zerocopy dependency and provides thederive_from_zerocopy
macro
-
Features enabling functionality that uses the higher-level
Rtl*
functions fromntdll.dll
(see above):subscribe
: Enables subscribing to state updateswait_blocking
: Enables blocking waits for state updates, implies thesubscribe
featurewait_async
: Enables async waits for state updates, implies thesubscribe
feature
§Stability
Since this crate depends on the WNF API, which is undocumented and hence must be considered unstable, it will
probably stay on an unstable 0.x
version forever.
§Minimum Supported Rust Version (MSRV) Policy
The current MSRV of this crate is 1.74
.
Increasing the MSRV of this crate is not considered a breaking change. However, in such cases there will be at least a minor version bump.
Each version of this crate will support at least the four latest stable Rust versions at the time it is published.
Macros§
- derive_
from_ bytemuck_ v1 bytemuck_v1
- Macro for deriving
wnf
traits frombytemuck
traits - derive_
from_ zerocopy zerocopy
- Macro for deriving
wnf
traits fromzerocopy
traits
Structs§
- Borrowed
State - A borrowed state
- Boxed
Security Descriptor - An owned security descriptor allocated on the local heap
- Change
Stamp - The change stamp of a state
- Data
Accessor subscribe
- A handle to state data passed to state listeners
- GUID
- A Globally Unique Identifier (GUID)
- Opaque
Data - A placeholder for state data whose content is irrelevant
- Owned
State - An owned state
- Security
Descriptor - A Windows security descriptor
- Stamped
Data - State data together with a change stamp
- State
Creation - A builder type for creating states
- State
Name - A state name
- State
Name Descriptor - The descriptor of a state name
- Subscription
subscribe
- A subscription of a listener to updates of a state
- Unspecified
Lifetime - A marker type for an unspecified lifetime when creating a state
- Unspecified
Scope - A marker type for an unspecified scope when creating a state
- Unspecified
Security Descriptor - A marker type for an unspecified security descriptor when creating a state
- Wait
wait_async
- The future returned by
wait_async
methods - Wait
Until wait_async
- The future returned by
wait_until_async
methods - Wait
Until Boxed wait_async
- The future returned by
wait_until_boxed_async
methods
Enums§
- Creatable
State Lifetime - The lifetime of a state when specified upon creation
- Data
Scope - The data scope of a state
- Read
Error - An error reading state data
- Seen
Change Stamp subscribe
- The change stamp that a state listener has last seen
- State
Lifetime - The lifetime of a state
- State
Name Descriptor From State Name Error - An error converting a
StateName
into aStateNameDescriptor
- State
Name From Descriptor Error - An error converting a
StateNameDescriptor
into aStateName
Constants§
- MAXIMUM_
STATE_ SIZE - The maximum size of a state in bytes
Traits§
- AnyBit
Pattern - A marker trait for types for which any bit pattern is valid
- AsState
- A trait for types that can be borrowed as a state
- Checked
BitPattern - A trait for types that can be checked for valid bit patterns at runtime
- NoUninit
- A marker trait for types without uninitialized (padding) bytes
- Read
- A trait for types that can be read from state data
- State
Listener subscribe
- A trait for types that are capable of listening to state updates
- TryInto
Security Descriptor - A trait for types that can be fallibly converted into a security descriptor
Functions§
- can_
create_ permanent_ shared_ objects - Returns whether the current process has the
SeCreatePermanentPrivilege
privilege