Summary: ReaderResult should be bounded by Sync

Affected versions of this crate implements `Sync` for `ReaderResult<T, E>` with the trait bound `T: Send, E: Send`.

Since matching on the public enum `ReaderResult<T, E>` provides access to `&T` & `&E`,
allowing data race to a non-Sync type `T` or `E`.
This can result in a memory corruption when multiple threads concurrently access `&T` or `&E`.

Suggested fix for the bug is change the trait bounds imposed on `T` & `E` to be `T: Sync, E: Sync`.


Summary: dces' World type can cause data races

The `World` type in `dces` is marked as `Send` without bounds on its
`EntityStore` and `ComponentStore`.

This allows non-thread safe `EntityStore` and `ComponentStore`s to be sent
across threads and cause data races.


Summary: `Shared` can cause a data race

`Shared` data structure in `model` crate implements `Send` and `Sync` traits regardless of the inner type.
This allows safe Rust code to trigger a data race, which is undefined behavior in Rust.

Users are advised to treat `Shared` as an unsafe type.
It should not be used outside of the testing context,
and care must be taken so that the testing code does not have a data race
besides a race condition that is expected to be caught by the test.

Check [the Rustonomicon](https://doc.rust-lang.org/nomicon/races.html) for the difference between
a data race and a general race condition.


Summary: MvccRwLock allows data races & aliasing violations

Affected versions of this crate unconditionally implement Send/Sync for `MvccRwLock`.
This can lead to data races when types that are either `!Send` or `!Sync` (e.g. `Rc<T>`, `Arc<Cell<_>>`) are contained inside `MvccRwLock` and sent across thread boundaries. The data races can potentially lead to memory corruption (as demonstrated in the PoC from the original report issue).

Also, safe APIs of `MvccRwLock` allow aliasing violations by allowing `&T` and `LockResult<MutexGuard<Box<T>>>` to co-exist in conflicting lifetime regions. The APIs of `MvccRwLock` should either be marked as `unsafe` or `MbccRwLock` should be changed to private or pub(crate).


Summary: Send bound needed on T (for Send impl of `Bucket2`)

Affected versions of this crate unconditionally implements `Send` for `Bucket2`. This allows sending non-Send types to other threads.

This can lead to data races when non Send types like `Cell<T>` or `Rc<T>` are contained inside `Bucket2` and sent across thread boundaries. The data races can potentially lead to memory corruption (as demonstrated in the PoC from the original report issue).

The flaw was corrected in commit 15b2828 by adding a `T: Send` bound to the `Send` impl of `Bucket2<T>`.


Summary: Queues allow non-Send types to be sent to other threads, allowing data races

Affected versions of this crate unconditionally implemented `Send` for types used in queue implementations (`InnerSend<RW, T>`, `InnerRecv<RW, T>`, `FutInnerSend<RW, T>`, `FutInnerRecv<RW, T>`).

This allows users to send non-Send types to other threads, which can lead to data race bugs or other undefined behavior.


Summary: lzw is unmaintained

The author of the `lzw` crate is unresponsive.

Maintained alternatives:

- [`weezl`](https://crates.io/crates/weezl)


Summary: Use-after-free when cloning a partially consumed `Vec` iterator

The `IntoIter` `Clone` implementation clones the whole underlying `Vec`.
If the iterator is partially consumed the consumed items will be copied, thus creating a use-after-free access.

A proof of concept is available in the original bug report.


Summary: arr! macro erases lifetimes

Affected versions of this crate allowed unsoundly extending
lifetimes using `arr!` macro. This may result in a variety of
memory corruption scenarios, most likely use-after-free.


Summary: rulinalg is unmaintained, use nalgebra instead

The `rulinalg` crate is no longer maintained, use [nalgebra](https://crates.io/crates/nalgebra)
instead.


Summary: Multiple soundness issues in `Ptr`

Affected versions of this crate have the following issues:

1. `Ptr` implements `Send` and `Sync` for all types, this can lead to data
   races by sending non-thread safe types across threads.

2. `Ptr::get` violates mutable alias rules by returning multiple mutable
   references to the same object.

3. `Ptr::write` uses non-atomic writes to the underlying pointer. This means
   that when used across threads it can lead to data races.


Summary: Data race and memory safety issue in `Index`

The `appendix` crate implements a key-value mapping data structure called
`Index<K, V>` that is stored on disk. The crate allows for any type to inhabit
the generic `K` and `V` type parameters and implements Send and Sync for them
unconditionally.

Using a type that is not marked as `Send` or `Sync` with `Index` can allow it
to be used across multiple threads leading to data races. Additionally using
reference types for the keys or values will lead to the segmentation faults
in the crate's code.


Summary: RingBuffer can create multiple mutable references and cause data races

The `RingBuffer` type retrieves mutable references from the `DataProvider` in a
non-atomic manner, potentially allowing the creation of multiple mutable
references. `RingBuffer` also implements the `Send` and `Sync` traits for all
types `T`.

This allows undefined behavior from the aliased mutable references as well
as data races.


Summary: Generators can cause data races if non-Send types are used in their generator functions

The `Generator` type is an iterable which uses a generator function that yields
values. In affected versions of the crate, the provided function yielding values
had no `Send` bounds despite the `Generator` itself implementing `Send`.

The generator function lacking a `Send` bound means that types that are
dangerous to send across threads such as `Rc` could be sent as part of a
generator, potentially leading to data races.

This flaw was fixed in commit [`f7d120a3b`](https://github.com/Xudong-Huang/generator-rs/commit/f7d120a3b724d06a7b623d0a4306acf8f78cb4f0)
by enforcing that the generator function be bound by `Send`.


Summary: ImmediateIO and TransactionalIO can cause data races

The `ImmediateIO` and `TransactionalIO` types implement `Sync` for all contained
`Expander<EI>` types regardless of if the `Expander` itself is safe to use
across threads.

As the `IO` types allow retrieving the `Expander`, this can lead to non-thread
safe types being sent across threads as part of the `Expander` leading to data
races.


Summary: `read` on uninitialized buffer may cause UB (bite::read::BiteReadExpandedExt::read_framed_max)

Affected versions of this crate calls a user provided `Read` implementation on an uninitialized buffer.

`Read` on uninitialized buffer is defined as undefined behavior in Rust.


Summary: InputStream::read_exact : `Read` on uninitialized buffer causes UB

Affected versions of this crate passes an uninitialized buffer to a user-provided `Read` implementation.

Arbitrary `Read` implementations can read from the uninitialized buffer (memory exposure) and also can return incorrect number of bytes written to the buffer.
Reading from uninitialized memory produces undefined values that can quickly invoke undefined behavior.


Summary: `Read` on uninitialized buffer in `fill_buf()` and `read_up_to()`


Summary: Observable Discrepancy in libsecp256k1-rs

A timing vulnerability in the Scalar::check_overflow function in Parity libsecp256k1-rs before 0.3.1 potentially allows an attacker to leak information via a side-channel attack.


Summary: Improper Synchronization and Race Condition in vm-memory

rust-vmm vm-memory before 0.1.1 and 0.2.x before 0.2.1 allows attackers to cause a denial of service (loss of IP networking) because read_obj and write_obj do not properly access memory. This affects aarch64 (with musl or glibc) and x86_64 (with musl).


Summary: slice-deque is unmaintained

The author of the `slice-deque` crate is unresponsive and is not receiving security patches.

Maintained alternatives:

- [`slice-ring-buffer`](https://crates.io/crates/slice-ring-buffer)


Summary: Potential segfault in `localtime_r` invocations

### Impact

Unix-like operating systems may segfault due to dereferencing a dangling pointer in specific circumstances. This requires an environment variable to be set in a different thread than the affected functions. This may occur without the user's knowledge, notably in a third-party library.

### Workarounds

No workarounds are known.

### References

- [time-rs/time#293](https://github.com/time-rs/time/issues/293)


Summary: Threshold value is ignored (all shares are n=3)

Affected versions of this crate did not properly calculate secret shares requirements.

This reduces the security of the algorithm by restricting the crate to always
using a threshold value of three, rather than a configurable limit.

The flaw was corrected by correctly configuring the threshold.


Summary: `array!` macro is unsound in presence of traits that implement methods it calls internally

Affected versions of this crate called some methods using auto-ref. The affected code looked like this.

```rust
let mut arr = $crate::__core::mem::MaybeUninit::uninit();
let mut vec = $crate::__ArrayVec::<T>::new(arr.as_mut_ptr() as *mut T);
```

In this case, the problem is that `as_mut_ptr` is a method of `&mut MaybeUninit`, not `MaybeUninit`. This made it possible for traits to hijack the method calls in order to cause unsoundness.

```rust
trait AsMutPtr<T> {
    fn as_mut_ptr(&self) -> *mut T;
}
impl<T> AsMutPtr<T> for std::mem::MaybeUninit<T> {
    fn as_mut_ptr(&self) -> *mut T {
        std::ptr::null_mut()
    }
}
array![0; 1];
```

The flaw was corrected by explicitly referencing variables in macro body in order to avoid auto-ref.


Summary: `tokio-proto` is deprecated/unmaintained

The [`tokio-proto`](https://crates.io/crates/tokio-proto) crate has been deprecated, and [its GitHub repository](https://github.com/tokio-rs/tokio-proto) has been archived.
Users may be interested in [`tokio-tower`](https://crates.io/crates/tokio-tower) instead, per https://github.com/tokio-rs/tokio/issues/118#issuecomment-452969665


Summary: `term_size` is unmaintained; use `terminal_size` instead

The [`term_size`](https://crates.io/crates/term_size) crate is no longer maintained. Consider using
[`terminal_size`](https://crates.io/crates/terminal_size) instead.


Summary: `cell-project` used incorrect variance when projecting through `&Cell<T>`

## Overview

The issue lies in the implementation of the `cell_project` macro which used `field as *const _` instead of `field as *mut _`.
The problem being that `*const T` is covariant in `T` while `*mut T` is invariant in `T`. Keep in mind that `&Cell<T>` is invariant in `T`,
so casting to `*const T` relaxed the variance, and lead to unsoundness, as shown in the example below.

```rs
use std::cell::Cell;
use cell_project::cell_project as cp;

struct Foo<'a> {
    x: Option<&'a Cell<Foo<'a>>>,
}

impl<'a> Drop for Foo<'a> {
    fn drop(&mut self) {
        // `ourselves` is an &Cell<Self>.
        // NB: `Drop` is unsound.
        if let Some(ourselves) = self.x.as_ref() {
            // replace `self` (but this doesn't actually replace `self`)
            let is_x_none = ourselves.replace(Foo {
                x: None,
            }).x.as_ref().is_none();
            // if we just moved out of `self`, and we had a `Some` originally,
            // how come this is a `None`?
            if is_x_none {
                println!("how did we get a None?");
            }
        }
    }
}

fn main() {
    let foo = Cell::new(Foo {
        x: None,
    });
    let x = cp!(Foo<'_>, foo.x);
    x.set(Some(&foo));
}
```

### MIRI error

```rs
$ cargo +nightly miri run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `<snip>`
error: Undefined Behavior: not granting access to tag <untagged> because incompatible item is protected: [Unique for <2472> (call 796)]
   --> $RUST_STD_PATH/src/rust/library/core/src/cell.rs:404:31
    |
404 |         mem::replace(unsafe { &mut *self.value.get() }, val)
    |                               ^^^^^^^^^^^^^^^^^^^^^^ not granting access to tag <untagged> because incompatible item is protected: [Unique for <2472> (call 796)]
    |
    = help: this indicates a potential bug in the program: it performed an invalid operation, but the rules it violated are still experimental
    = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information

    = note: inside `std::cell::Cell::<Foo>::replace` at $RUST_STD_PATH/src/rust/library/core/src/cell.rs:404:31
note: inside `<Foo as std::ops::Drop>::drop` at src/main.rs:14:29
   --> src/main.rs:14:29
    |
14  |               let is_x_none = ourselves.replace(Foo {
    |  _____________________________^
15  | |                 x: None,
16  | |             }).x.as_ref().is_none();
    | |______________^
    = note: inside `std::ptr::drop_in_place::<Foo> - shim(Some(Foo))` at $RUST_STD_PATH/src/rust/library/core/src/ptr/mod.rs:486:1
    = note: inside `std::ptr::drop_in_place::<std::cell::UnsafeCell<Foo>> - shim(Some(std::cell::UnsafeCell<Foo>))` at $RUST_STD_PATH/src/rust/library/core/src/ptr/mod.rs:486:1
    = note: inside `std::ptr::drop_in_place::<std::cell::Cell<Foo>> - shim(Some(std::cell::Cell<Foo>))` at $RUST_STD_PATH/src/rust/library/core/src/ptr/mod.rs:486:1
note: inside `main` at src/main.rs:32:1
   --> src/main.rs:32:1
    |
32  | }
    | ^

note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace

error: aborting due to previous error
```

## Affected Versions

All versions of the cell-project crate before `0.1.4` are affected.

## Mitigation

This was fixed in [Issues/4], and released as version `0.1.4`.
So just updating to the latest version will include the fix (which may result in a compile error on unsound usage).

## Acknowledgements

This was discovered and fixed by @SoniEx2 in cell-project: [Issues/3] and [Issues/4]

[issues/3]: https://github.com/RustyYato/cell-project/issues/3
[issues/4]: https://github.com/RustyYato/cell-project/issues/4


Summary: mozjpeg DecompressScanlines::read_scanlines is Unsound

This issue and vector is similar to [RUSTSEC-2020-0029] of `rgb` crate which `mozjpeg` depends on.

Affected versions of `mozjpeg` crate allow creating instances of any type `T` from bytes,
and do not correctly constrain `T` to the types for which it is safe to do so.

Examples of safety violation possible for a type `T`:

* `T` contains a reference type, and it constructs a pointer to an invalid, arbitrary memory address.
* `T` requires a safety and/or validity invariant for its construction that may be violated.

The issue was fixed in 0.8.19 by using safer types and involving `rgb` dependency bump.

[RUSTSEC-2020-0029]: https://rustsec.org/advisories/RUSTSEC-2020-0029.html


Summary: personnummer Input validation error

Swedish personal identity is in the form of YYMMDD-XXXX

An issue arises from the regular expression allowing the first three digits in
the last four digits of the personnummer to be 000, which is invalid.

To mitigate this without upgrading, a check on the last four digits can be made
to make sure it's not 000x.

The affected version should not be relied on without the mitigation to check
that the swedish personal identity number is valid.


Summary: `pnet_packet` buffer overrun in `set_payload` setters

As indicated by this [issue](https://github.com/libpnet/libpnet/issues/449#issuecomment-663355987), a buffer overrun is possible in the `set_payload` setter of the various mutable "Packet" struct setters. The offending `set_payload` functions were defined within the struct `impl` blocks in earlier versions of the package, and later by the `packet` macro.

Fixed in the `packet` macro by [this](https://github.com/libpnet/libpnet/pull/455) PR.


Summary: mach is unmaintained

Last release was almost 4 years ago.

Maintainer(s) seem to be completely unreachable.

## Possible Alternative(s)

These may or may not be suitable alternatives and have not been vetted in any way;
- [mach2](https://crates.io/crates/mach2) - direct fork


Summary: multi_mut is Unmaintained

Last release was about 6 years ago.

There is an outstanding [soundness issue](https://github.com/golddranks/multi_mut/issues/1).

The maintainer has not responded for two years to the existing soundness issue.

Rust compiler has enabled errors relating to LLVM noalias rules and may not
compile anymore where as the old compiler versions had turned these off.

The maintainer has stated:

> I will take no responsibility of undefined behaviour possibly caused by this crate.

This crate may or may not be suitable for use anymore given the outstanding issues.


Summary: XSS in mdBook's search page

> This is a cross-post of [the official security advisory][ml]. The official post
> contains a signed version with our PGP key, as well.

[ml]: https://groups.google.com/g/rustlang-security-announcements/c/3-sO6of29O0

The Rust Security Response Working Group was recently notified of a security
issue affecting the search feature of mdBook, which could allow an attacker to
execute arbitrary JavaScript code on the page.

The CVE for this vulnerability is [CVE-2020-26297][1].

## Overview

The search feature of mdBook (introduced in version 0.1.4) was affected by a
cross site scripting vulnerability that allowed an attacker to execute
arbitrary JavaScript code on an user's browser by tricking the user into typing
a malicious search query, or tricking the user into clicking a link to the
search page with the malicious search query prefilled.

mdBook 0.4.5 fixes the vulnerability by properly escaping the search query.

## Mitigations

Owners of websites built with mdBook have to upgrade to mdBook 0.4.5 or greater
and rebuild their website contents with it. It's possible to install mdBook
0.4.5 on the local system with:

```
cargo install mdbook --version 0.4.5 --force
```

## Acknowledgements

Thanks to Kamil Vavra for responsibly disclosing the vulnerability to us
according to [our security policy][2].

## Timeline of events

All times are listed in UTC.

* 2020-12-30 20:14 - The issue is reported to the Rust Security Response WG
* 2020-12-30 20:32 - The issue is acknowledged and the investigation began
* 2020-12-30 21:21 - Found the cause of the vulnerability and prepared the patch
* 2021-01-04 15:00 - Patched version released and vulnerability disclosed

[1]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-26297
[2]: https://www.rust-lang.org/policies/security


Summary: interfaces2 is unmaintained, use interfaces instead

The `interfaces2` crate is not maintained any more;
use [`interfaces`](https://crates.io/crates/interfaces) instead.


Summary: Buffer overflow in SmallVec::insert_many

A bug in the `SmallVec::insert_many` method caused it to allocate a buffer that was smaller than needed.  It then wrote past the end of the buffer, causing a buffer overflow and memory corruption on the heap.

This bug was only triggered if the iterator passed to `insert_many` yielded more items than the lower bound returned from its `size_hint` method.

The flaw was corrected in smallvec 0.6.14 and 1.6.1, by ensuring that additional space is always reserved for each item inserted.  The fix also simplified the implementation of `insert_many` to use less unsafe code, so it is easier to verify its correctness.

Thank you to Yechan Bae (@Qwaz) and the Rust group at Georgia Tech’s SSLab for finding and reporting this bug.


Summary: Missing Send bound for Lazy

All current versions of this crate allow causing data races in safe code.

The flaw will be fixed in the next release.


Summary: Double drop upon panic in 'fn map_array()'

Affected versions of this crate did not guard against panic within the user-provided function `f` (2nd parameter of `fn map_array`), and thus panic within `f`
causes double drop of a single object.

The flaw was corrected in the 0.4.0 release by wrapping the object vulnerable
to a double drop within `ManuallyDrop<T>`.


Summary: Exposes internally used raw pointer

Affected versions of this crate dereference a raw pointer that can be modified
without using `unsafe` code.


Summary: `Frame::copy_from_raw_parts` can lead to segfault without `unsafe`

`fn Frame::copy_from_raw_parts()` is a safe API that can take a
raw pointer and dereference it. It is possible to read arbitrary memory address
with an arbitrarily fed pointer. This allows the safe API to access & read
arbitrary address in memory. Feeding an invalid memory address pointer to
the API may also cause the program to segfault.

The flaw was corrected in https://github.com/rust-av/rust-av/pull/137,
by removing the API `fn Frame::copy_from_raw_parts()`.


Summary: reading on uninitialized buffer can cause UB (`impl<R> BufRead for GreedyAccessReader<R>`)

Affected versions of this crate creates an uninitialized buffer and passes it to user-provided `Read` implementation.

This is unsound, because it allows safe Rust code to exhibit an undefined behavior (read from uninitialized memory).

The flaw was corrected in version 0.1.1 by zero-initializing a newly allocated buffer
before handing it to a user-provided `Read` implementation.


Summary: panic safety issue in `impl TransformContent<S, D> for [S; (2|3|4)]`

Affected versions of this crate did not guard against double drop while temporarily duplicating objects' ownership using `ptr::read()`. Upon panic in a user-provided function `conversion`, objects that are copied by `ptr::read()` are dropped twice, leading to memory corruption.

The flaw was corrected in v0.9.2 by using `ManuallyDrop<T>` to enclose objects that are to be temporarily duplicated.


Summary: panic safety: double drop may happen within `util::{mutate, mutate2}`

Upon panic in a user-provided function `f`, `fn mutate()` & `fn mutate2` drops twice a same object.

Affected versions of this crate did not guard against double drop while temporarily duplicating an object's ownership with `ptr::read()`.

Dropping a same object can result in memory corruption.

The flaw was corrected in version "0.9.11" by fixing the code to abort upon panic.


Summary: EventList's From<EventList> conversions can double drop on panic.

Affected versions of this crate read from a container using `ptr::read` in
`From<EventList>`, and then call a user specified `Into<Event>` function.

This issue can result in a double-free if the user provided function panics.


Summary: Reading uninitialized memory can cause UB (`Deserializer::read_vec`)

`Deserializer::read_vec()` created an uninitialized buffer and passes it to a user-provided `Read` implementation (`Deserializer.reader.read_exact()`).

Passing an uninitialized buffer to an arbitrary `Read` implementation is currently defined as undefined behavior in Rust. Official documentation for the `Read` trait explains the following: "It is your responsibility to make sure that buf is initialized before calling read. Calling read with an uninitialized buf (of the kind one obtains via MaybeUninit<T>) is not safe, and can lead to undefined behavior."

The flaw was corrected in commit ce310f7 by zero-initializing the newly allocated buffer before handing it to `Deserializer.reader.read_exact()`.


Summary: Soundness issues in `raw-cpuid`

## Undefined behavior in `as_string()` methods

`VendorInfo::as_string()`, `SoCVendorBrand::as_string()`,
and `ExtendedFunctionInfo::processor_brand_string()` construct byte slices
using `std::slice::from_raw_parts()`, with data coming from
`#[repr(Rust)]` structs. This is always undefined behavior.

See https://github.com/gz/rust-cpuid/issues/40.

This flaw has been fixed in v9.0.0, by making the relevant structs
`#[repr(C)]`.

## `native_cpuid::cpuid_count()` is unsound

`native_cpuid::cpuid_count()` exposes the unsafe `__cpuid_count()` intrinsic
from `core::arch::x86` or `core::arch::x86_64` as a safe function, and uses
it internally, without checking the
[safety requirement](https://doc.rust-lang.org/core/arch/index.html#overview):

> The CPU the program is currently running on supports the function being
> called.

CPUID is available in most, but not all, x86/x86_64 environments. The crate
compiles only on these architectures, so others are unaffected.

This issue is mitigated by the fact that affected programs are expected
to crash deterministically every time.

See https://github.com/gz/rust-cpuid/issues/41.

The flaw has been fixed in v9.0.0, by intentionally breaking compilation
when targeting SGX or 32-bit x86 without SSE. This covers all affected CPUs.


Summary: Record::read : Custom `Read` on uninitialized buffer may cause UB

Affected versions of this crate passes an uninitialized buffer to a user-provided `Read` implementation. (`Record::read()`)

Arbitrary `Read` implementations can read from the uninitialized buffer (memory exposure) and also can return incorrect number of bytes written to the buffer.
Reading from uninitialized memory produces undefined values that can quickly invoke undefined behavior.

This flaw was fixed in commit 6299af0 by zero-initializing the newly allocated memory (via `data.resize(len, 0)`) instead of exposing uninitialized memory (`unsafe { data.set_len(len) }`).


Summary: `Sectors::get` accesses unclaimed/uninitialized memory

Affected versions of this crate arbitrarily calls `Vec::set_len` to increase length of a vector without claiming more memory for the vector. Affected versions of this crate
also calls user-provided `Read` on the uninitialized memory of the vector that was
extended with `Vec::set_len`.

This can overwrite active entities in adjacent heap memory and seems to be a major security issue. Also, calling user-provided `Read` on uninitialized memory is defined as UB in Rust.


Summary: `IoReader::read()`: user-provided `Read` on uninitialized buffer may cause UB

Affected versions of this crate passes an uninitialized buffer to a user-provided `Read` implementation.

Arbitrary `Read` implementations can read from the uninitialized buffer (memory exposure) and also can return incorrect number of bytes written to the buffer.
Reading from uninitialized memory produces undefined values that can quickly invoke undefined behavior.

The flaw was fixed in commit 599313b by zero-initializing the buffer (via `self.buf.resize(len, 0)`) before passing it to `Read`.


Summary: `Read` on uninitialized buffer may cause UB (`impl Walue for Vec<u8>`)

Affected versions of this crate passes an uninitialized buffer to a user-provided `Read` implementation.

Arbitrary `Read` implementations can read from the uninitialized buffer (memory exposure) and also can return incorrect number of bytes written to the buffer.
Reading from uninitialized memory produces undefined values that can quickly invoke undefined behavior.

This flaw was fixed in commit 8026286 by zero-initializing the buffer before handing to a user-provided `Read`.


Summary: insert_slice_clone can double drop if Clone panics.

Affected versions of this crate used `ptr::copy` when inserting into the middle
of a `Vec`. When ownership was temporarily duplicated during this copy, it calls
the clone method of a user provided element.

This issue can result in an element being double-freed if the clone call panics.

Commit `20cb73d` fixed this issue by adding a `set_len(0)` call before
operating on the vector to avoid dropping the elements during a panic.


Summary: Multiple soundness issues

## Calls `std::str::from_utf8_unchecked()` without any checks

The function `xcb::xproto::GetAtomNameReply::name()` calls
`std::str::from_utf8_unchecked()` on the raw bytes that were received from the
X11 server without any validity checks. The X11 server only prevents interior
null bytes, but otherwise allows any X11 client to create an atom for arbitrary
bytes.

This issue is tracked here: https://github.com/rust-x-bindings/rust-xcb/issues/96

## `xcb::xproto::GetPropertyReply::value()` allows arbitrary return types

The function `xcb::xproto::GetPropertyReply::value()` returns a slice of type
`T` where `T` is an unconstrained type parameter. The raw bytes received from
the X11 server are interpreted as the requested type.

The users of the `xcb` crate are advised to only call this function with the
intended types. These are `u8`, `u16`, and `u32`.

This issue is tracked here: https://github.com/rust-x-bindings/rust-xcb/issues/95

## Out of bounds read in `xcb::xproto::change_property()`

`xcb::xproto::change_property` has (among others) the arguments `format: u8` and
`data: &[T]`. The intended use is one of the following cases:
- `format = 8` and `T = u8`
- `format = 16` and `T = u16`
- `format = 32` and `T = u32`
However, this constraint is not enforced. For example, it is possible to call
the function with `format = 32` and `T = u8`. In this case, a read beyond the
end of the `data` slice is performed and the bytes are sent to the X11 server.

The users of the `xcb` crate are advised to only call this function with one of
the intended argument combinations.

This issue is tracked here: https://github.com/rust-x-bindings/rust-xcb/issues/94

## 'Safe' wrapper around `std::mem::transmute()`

The function `xcb::base::cast_event()` takes a reference to a
`xcb::base::GenericEvent` and returns a reference to an arbitrary type, as
requested by the caller (or found via type interference). The function is
implemented as a direct call to `std::mem::transmute()`. Since the return type
is not constrained, this allows transmution to an incorrect type or a type that
is larger than the X11 event that was passed in.

X11 events are mostly always 32 bytes large and this function works as intended.

Users are advised to only cast to the event structs provided by the `xcb` crate
(and hope for the best).

This issue is tracked here: https://github.com/rust-x-bindings/rust-xcb/issues/78


Summary: Multiple Transfer-Encoding headers misinterprets request payload

hyper's HTTP server code had a flaw that incorrectly understands some requests
with multiple transfer-encoding headers to have a chunked payload, when it
should have been rejected as illegal. This combined with an upstream HTTP proxy
that understands the request payload boundary differently can result in
"request smuggling" or "desync attacks".


Summary: `nb-connect` invalidly assumes the memory layout of std::net::SocketAddr

The [`nb-connect`](https://crates.io/crates/nb-connect) crate has assumed `std::net::SocketAddrV4`
and `std::net::SocketAddrV6` have the same memory layout as the system C representation
`sockaddr`. It has simply casted the pointers to convert the socket addresses to the
system representation. The standard library does not say anything about the memory
layout, and this will cause invalid memory access if the standard library
changes the implementation. No warnings or errors will be emitted once the
change happens.


Summary: Use-after-free in `subscript_next` and `subscript_prev` wrappers

Affected versions of this crate had an unsound implementation which could pass
a pointer to freed memory to `ydb_subscript_next_st` and
`ydb_subscript_prev_st` if the variable and subscripts did not have enough
memory allocated on the first call to hold the next variable in the database.

For example, the following code had undefined behavior:

```rust
let mut key = Key::variable(String::from("a"));
Key::variable("averylongkeywithlotsofletters")
    .set_st(YDB_NOTTP, Vec::new(), b"some val")
    .unwrap();
key.sub_next_self_st(YDB_NOTTP, Vec::new()).unwrap();
```

`yottadb` has no reverse-dependencies on crates.io and there are no known
instances of this API being used incorrectly in practice. The fix is backwards
compatible.

The flaw was corrected by recalculating the pointer each time it was reallocated.


Summary: Incorrect check on buffer length when seeding RNGs

Summary: rand_core::le::read_u32_into and read_u64_into have incorrect checks on the source buffer length, allowing the destination buffer to be under-filled.

Implications: some downstream RNGs, including Hc128Rng (but not the more widely used ChaCha*Rng), allow seeding using the SeedableRng::from_seed trait-function with too short keys.


Summary: crate has been renamed to `sn_api`

This crate has been renamed from `safe-api` to `sn_api`.

The new repository location is:

<https://github.com/maidsafe/sn_api>


Summary: crate has been renamed to `qjsonrpc`

This crate has been renamed from `jsonrpc-quic` to `qjsonrpc`.

The new repository location is:

<https://github.com/maidsafe/sn_api>


Summary: XSS in `comrak`

The [comrak](https://github.com/kivikakk/comrak) we were matching unsafe URL prefixes, such as `data:` or `javascript:` , in a case-sensitive manner. This meant prefixes like `Data:` were untouched.


Summary: Loading a bgzip block can write out of bounds if size overflows.

Affected versions of `bam` set the length of an internal buffer using
`self.compressed.set_len(block_size - HEADER_SIZE - MIN_EXTRA_SIZE)` and then
wrote into it. While `block_size` was constrained to a proper maximum, when it
was too small the subtraction could overflow negatively to a large number past
the capacity of `self.compressed`.

This can result in memory corruption in the form of writing out of bounds when
loading a `bgzip` file with a small `block_size`.

Commit `061eee38d4` fixed this issue by checking for the underflow when setting
the buffer size.


Summary: Multiple memory safety issues in insert_row

When inserting rows from an iterator at a particular index, `toodee` would shift
items over, duplicating their ownership. The space reserved for the new elements
was based on the `len()` returned by the `ExactSizeIterator`.

This could result in elements in the array being freed twice if the iterator
panics. Uninitialized or previously freed elements could also be exposed if the
`len()` didn't match the number of elements.

These issues were fixed in commit `ced70c17` by temporarily setting the length
of the array smaller while processing it and adding assertions on the number
of elements returned by the iterator.


Summary: Tape::take_bytes exposes uninitialized memory to a user-provided Read

Affected versions of this crate passed an unininitialized buffer to a
user-provided `Read` instance in `Tape::take_bytes`.

This can result in safe `Read` implementations reading from the uninitialized
buffer leading to undefined behavior.

The flaw was corrected in commit `1f2dc7f37dd` by removing the unsafe block
and zero-initializing the buffer.


Summary: move_elements can double-free objects on panic

Affected versions of `scratchpad` used `ptr::read` to read elements while
calling a user provided function `f` on them.

Since the pointer read duplicates ownership, a panic inside the user provided
`f` function could cause a double free when unwinding.

The flaw was fixed in commit `891561bea` by removing the unsafe block and using
a plain iterator.


Summary: split_at allows obtaining multiple mutable references to the same data

Affected versions of this crate assumed that `Borrow<Idx>` was guaranteed to
return the same value on `.borrow()`. The borrowed index value was used to
retrieve a mutable reference to a value.

If the `Borrow<Idx>` implementation returned a different index, the split arena
would allow retrieving the index as a mutable reference creating two mutable
references to the same element. This violates Rust's aliasing rules and allows
for memory safety issues such as writing out of bounds and use-after-frees.

The flaw was corrected in commit `6b83f9d` by storing the `.borrow()` value in
a temporary variable.


Summary: Deserializing an array can drop uninitialized memory on panic

The `read_bytes_default_le` function for `[T; n]` arrays, used to deserialize
arrays of `T` from bytes created a `[T; n]` array with `std::mem::uninitialized`
and then called `T`'s deserialization method.

If `T`'s deserialization method panicked, the uninitialized memory could drop
invalid objects.

This flaw was corrected in `a535678` by removing the unsafe block and using
a `.map` function to deserialize each element of the array instead.


Summary: push_cloned can drop uninitialized memory or double free on panic

Affected versions of `stack_dst` used a `push_inner` function that increased
the internal length of the array and then called `val.clone()`.

If the `val.clone()` call panics, the stack could drop an already dropped
element or drop uninitialized memory.

This issue was fixed in `2a4d538` by increasing the length of the array after
elements are cloned.


Summary: office is unmaintained, use calamine instead

The `office` crate is unmaintained. Use [calamine](https://crates.io/crates/calamine)
for reading excel files.

Contact the `office` author for ownership of the package name.


Summary: `quinn` invalidly assumes the memory layout of std::net::SocketAddr

The [`quinn`](https://crates.io/crates/quinn) crate has assumed `std::net::SocketAddrV4`
and `std::net::SocketAddrV6` have the same memory layout as the system C representation
`sockaddr`. It has simply casted the pointers to convert the socket addresses to the
system representation. The standard library does not say anything about the memory
layout, and this will cause invalid memory access if the standard library
changes the implementation. No warnings or errors will be emitted once the
change happens.


Summary: Intern<T>: Data race allowed on T

Affected versions of this crate unconditionally implements `Sync` for `Intern<T>`.
This allows users to create data race on `T: !Sync`, which may lead to undefined behavior
(for example, memory corruption).

The flaw was corrected in commit 2928a87 by adding the trait bound `T: Sync` in the `Sync` impl of `Intern<T>`.


Summary: Fix a use-after-free bug in diesels Sqlite backend

We've misused `sqlite3_column_name`. The
[SQLite](https://www.sqlite.org/c3ref/column_name.html) documentation
states that the following:

> The returned string pointer is valid until either the prepared statement
> is destroyed by sqlite3_finalize() or until the statement is automatically
> reprepared by the first call to sqlite3_step() for a particular
> run or until the next call to sqlite3_column_name()
> or sqlite3_column_name16() on the same column.

As part of our `query_by_name` infrastructure we've first received all
field names for the prepared statement and stored them as string slices
for later use. After that we called `sqlite3_step()` for the first time,
which invalids the pointer and therefore the stored string slice.


Summary: Multiple memory safety issues

Affected versions contain multiple memory safety issues, such as:

 - Setting a multi label type where an image doesn't exist would lead to a NULL pointer dereference.
 - Setting a window icon using a non-raster image (which FLTK rasterizes lazily) would lead to a NULL dereference.
 - Pixmap constructor would not check for correct pixmaps which could lead to out-of bound reads.


Summary: panic in user-provided `Endian` impl triggers double drop of T

Affected versions of the crate does not guard against panic from user-provided impl of `Endian` trait, which is a safe trait that users can implement.
If a user-provided implementation of the `Endian` trait panics, double-drop is triggered due to the duplicated ownership of `T` created by `ptr::read()`.

Double-drop (or double free) can cause memory corruption in the heap.


Summary: panic safety: double drop or uninitialized drop of T upon panic

Affected versions of this crate did not guard against potential panics that may happen from user-provided functions `T::default()` and `T::drop()`.

Panic within `T::default()` leads to dropping uninitialized `T`, when it is invoked from `common::Slice::<T, H>::new()`.
Panic within `T::drop()` leads to double drop of `T`, when it is invoked either from `common::SliceVec::<T, H>::resize_with()` or `common::SliceVec::<T, H>::resize()`

Either case causes memory corruption in the heap memory.


Summary: Denial of service through parsing payloads with too big exponent

The `parse_duration::parse` function allows for parsing duration strings with exponents like `5e5s` where under the hood, the [`BigInt` type along with the `pow` function are used for such payloads](https://github.com/zeta12ti/parse_duration/blob/26940ab5cd4e3a9d6bd97aa101f8d4bbfd18ee8c/src/parse.rs#L335). Passing an arbitrarily big exponent makes the `parse_duration::parse` function to process the payload for a very long time taking up CPU and memory.

This allows an attacker to cause a DoS if the `parse_duration::parse` function is used to process untrusted input.


Summary: insert_many can drop elements twice on panic

Affected versions of `insert_many` used `ptr::copy` to move over items in a
vector to make space before inserting, duplicating their ownership. It then
iterated over a provided `Iterator` to insert the new items.

If the iterator's `.next()` method panics then the vector would drop the same
elements twice.


Summary: PartialReader passes uninitialized memory to user-provided Read

Affected versions of this crate passed an uniniitalized buffer to a
user-provided `Read` instance in `PartialReader::read`.

This can result in safe `Read` implementations reading from the uninitialized
buffer leading to undefined behavior.

The flaw was fixed in commit [`39d62c6`](https://github.com/uutils/coreutils/commit/39d62c6c1f809022c903180471c10fde6ecd12d1)
by zero-initializing the passed buffer.


Summary: Use after free possible in `uri::Formatter` on panic

Affected versions of this crate transmuted a `&str` to a `&'static str` before
pushing it into a `StackVec`, this value was then popped later in the same
function.

This was assumed to be safe because the reference would be valid while the
method's stack was active. In between the push and the pop, however, a function
`f` was called that could invoke a user provided function.

If the user provided panicked, then the assumption used by the function was no
longer true and the transmute to `&'static` would create an illegal static
reference to the string. This could result in a freed string being used during
(such as in a `Drop` implementation) or after (e.g through `catch_unwind`) the
panic unwinding.

This flaw was corrected in commit [e325e2f](https://github.com/SergioBenitez/Rocket/commit/e325e2fce4d9f9f392761e9fb58b418a48cef8bb)
by using a guard object to ensure that the `&'static str` was dropped inside
the function.


Summary: FromIterator implementation for Vector/Matrix can drop uninitialized memory

The `FromIterator<T>` methods for `Vector` and `Matrix` rely on the type
parameter `N` to allocate space in the iterable.

If the passed in `N` type parameter is larger than the number of items returned
by the iterator, it can lead to uninitialized memory being left in the
`Vector` or `Matrix` type which gets dropped.


Summary: misc::vec_with_size() can drop uninitialized memory if clone panics

`misc::vec_with_size` creates a vector of the provided `size` and immediately
calls `vec.set_len(size)` on it, initially filling it with uninitialized memory.
It then inserts elements using `vec[i] = value.clone()`.

If the `value.clone()` call panics, uninitialized items in the vector will be
dropped leading to undefined behavior.


Summary: SliceDeque::drain_filter can double drop an element if the predicate panics

Affected versions of the crate incremented the current index of the drain filter
iterator *before* calling the predicate function `self.pred`.

If the predicate function panics, it is possible for the last element in the
iterator to be dropped twice.


Summary: StackVec::extend can write out of bounds when size_hint is incorrect

`StackVec::extend` used the lower and upper bounds from an Iterator's
`size_hint` to determine how many items to push into the stack based vector.

If the `size_hint` implementation returned a lower bound that was larger than
the upper bound, `StackVec` would write out of bounds and overwrite memory
on the stack. As mentioned by the [size_hint](https://doc.rust-lang.org/std/iter/trait.Iterator.html#provided-methods)
documentation, `size_hint` is mainly for optimization and incorrect
implementations should not lead to memory safety issues.


Summary: `through` and `through_and` causes a double free if the map function panics

`through` and `through_and` take a mutable reference as well as a mapping
function to change the provided reference. They do this by calling `ptr::read`
on the reference which duplicates ownership and then calling the mapping
function.

If the mapping function panics, both the original object and the one
duplicated by `ptr::read` get dropped, causing a double free.


Summary: swap_index can write out of bounds and return uninitialized memory

`swap_index` takes an iterator and swaps the items with their corresponding
indexes. It reserves capacity and sets the length of the vector based on the
`.len()` method of the iterator.

If the `len()` returned by the iterator is larger than the actual number of
elements yielded, then `swap_index` creates a vector containing uninitialized
members. If the `len()` returned by the iterator is smaller than the actual
number of members yielded, then `swap_index` can write out of bounds past
its allocated vector.

As noted by the Rust documentation, [`len()`](https://doc.rust-lang.org/std/iter/trait.ExactSizeIterator.html#method.len)
and `size_hint()` are primarily meant for optimization and incorrect values
from their implementations should not lead to memory safety violations.

# Patch

A new version crate was pushed that marks this function as unsafe.

reorder = "1.1.0"

Previous versions have also been yanked from crates.io.


Summary: KeyValueReader passes uninitialized memory to Read instance

The `KeyValueReader` type in affected versions of this crate set up an
uninitialized memory buffer and passed them to be read in to a user-provided
`Read` instance.

The `Read` instance could read uninitialized memory and cause undefined
behavior and miscompilations.

This issue was fixed in commit [dd59b30](https://github.com/SolraBizna/outer_cgi/commit/dd59b3066e616a08e756f72de8dc3ab11b7036c4)
by zero-initializing the buffers before passing them.


Summary: Multiple functions can cause double-frees

The following functions in the crate are affected:

## `IdMap::clone_from`

The `clone_from` implementation for `IdMap` drops the values present in the
map and then begins cloning values from the other map. If a `.clone()` call
pancics, then the afformentioned dropped elements can be freed again.

## `get_or_insert`

`get_or_insert` reserves space for a value, before calling the user provided
insertion function `f`. If the function `f` panics then uninitialized or
previously freed memory can be dropped.

## `remove_set`

When removing a set of elements, `ptr::drop_in_place` is called on each of the
element to be removed. If the `Drop` impl of one of these elements panics then
the previously dropped elements can be dropped again.


Summary: 'merge_sort::merge()' crashes with double-free for `T: Drop`

In the affected versions of this crate, `merge_sort::merge()` wildly duplicates and drops ownership of `T` without guarding against double-free. Due to such implementation,
simply invoking `merge_sort::merge()` on `Vec<T: Drop>` can cause **double free** bugs.


Summary: Archives may contain uninitialized memory

`rkyv` is a serialization framework that writes struct-compatible memory to be stored or
transmitted. During serialization, struct padding bytes and unused enum bytes may not be
initialized. These bytes may be written to disk or sent over unsecured channels.


Summary: NULL pointer deref in signature_algorithms processing

An OpenSSL TLS server may crash if sent a maliciously crafted renegotiation
ClientHello message from a client. If a TLSv1.2 renegotiation ClientHello omits
the signature_algorithms extension (where it was present in the initial
ClientHello), but includes a signature_algorithms_cert extension then a NULL
pointer dereference will result, leading to a crash and a denial of service
attack.

A server is only vulnerable if it has TLSv1.2 and renegotiation enabled (which
is the default configuration). OpenSSL TLS clients are not impacted by this
issue.


Summary: CA certificate check bypass with X509_V_FLAG_X509_STRICT

The X509_V_FLAG_X509_STRICT flag enables additional security checks of the
certificates present in a certificate chain. It is not set by default.

Starting from OpenSSL version 1.1.1h a check to disallow certificates in
the chain that have explicitly encoded elliptic curve parameters was added
as an additional strict check.

An error in the implementation of this check meant that the result of a
previous check to confirm that certificates in the chain are valid CA
certificates was overwritten. This effectively bypasses the check
that non-CA certificates must not be able to issue other certificates.

If a "purpose" has been configured then there is a subsequent opportunity
for checks that the certificate is a valid CA.  All of the named "purpose"
values implemented in libcrypto perform this check.  Therefore, where
a purpose is set the certificate chain will still be rejected even when the
strict flag has been used. A purpose is set by default in libssl client and
server certificate verification routines, but it can be overridden or
removed by an application.

In order to be affected, an application must explicitly set the
X509_V_FLAG_X509_STRICT verification flag and either not set a purpose
for the certificate verification or, in the case of TLS client or server
applications, override the default purpose.


Summary: Integer overflow in CipherUpdate

Calls to `EVP_CipherUpdate`, `EVP_EncryptUpdate` and `EVP_DecryptUpdate` may overflow
the output length argument in some cases where the input length is close to the
maximum permissable length for an integer on the platform. In such cases the
return value from the function call will be 1 (indicating success), but the
output length value will be negative. This could cause applications to behave
incorrectly or crash.


Summary: Null pointer deref in `X509_issuer_and_serial_hash()`

The OpenSSL public API function `X509_issuer_and_serial_hash()` attempts to
create a unique hash value based on the issuer and serial number data contained
within an X509 certificate. However it fails to correctly handle any errors
that may occur while parsing the issuer field (which might occur if the issuer
field is maliciously constructed). This may subsequently result in a NULL
pointer deref and a crash leading to a potential denial of service attack.

The function `X509_issuer_and_serial_hash()` is never directly called by OpenSSL
itself so applications are only vulnerable if they use this function directly
and they use it on certificates that may have been obtained from untrusted
sources.


Summary: `aesni` has been merged into the `aes` crate

Please use the `aes` crate going forward. The new repository location is at:

<https://github.com/RustCrypto/block-ciphers/tree/master/aes>

AES-NI is now autodetected at runtime on `i686`/`x86-64` platforms.
If AES-NI is not present, the `aes` crate will fallback to a constant-time
portable software implementation.

To prevent this fallback (and have absence of AES-NI result in an illegal
instruction crash instead), continue to pass the same RUSTFLAGS which were
previously required for the `aesni` crate to compile:

```
RUSTFLAGS=-Ctarget-feature=+aes,+ssse3
```


Summary: `aes-soft` has been merged into the `aes` crate

Please use the `aes` crate going forward. The new repository location is at:

<https://github.com/RustCrypto/block-ciphers/tree/master/aes>

AES-NI is now autodetected at runtime on `i686`/`x86-64` platforms.
If AES-NI is not present, the `aes` crate will fallback to a constant-time
portable software implementation.

To force the use of a constant-time portable implementation on these platforms,
even if AES-NI is available, use the new `force-soft` feature of the `aes`
crate to disable autodetection.


Summary: `aes-ctr` has been merged into the `aes` crate

Please use the `aes` crate going forward. The new repository location is at:

<https://github.com/RustCrypto/block-ciphers/tree/master/aes>

The `aes` crate now has an optional `ctr` feature which autodetects SIMD
features on `i686`/`x86-64` targets and uses them if available, or otherwise
falls back to the implementation in the `ctr` crate.

If you would prefer not to have this autodetection performed, use the `aes`
crate directly with the `ctr` crate.


Summary: project abandoned; migrate to the `aes-siv` crate

The Miscreant project has been abandoned and archived.

The Rust implementation has been adapted into the new `aes-siv` crate which
implements both the AES-CMAC-SIV and AES-PMAC-SIV constructions:

<https://github.com/RustCrypto/AEADs/tree/master/aes-siv>

Please migrate to the `aes-siv` crate.

Alternatively see the `aes-gcm-siv` crate for a newer, faster construction
which provides similar properties:

<https://github.com/RustCrypto/AEADs/tree/master/aes-gcm-siv>


Summary: XSS in `comrak`

[comrak](https://github.com/kivikakk/comrak) operates by default in a "safe"
mode of operation where unsafe content, such as arbitrary raw HTML or URLs with
non-standard schemes, are not permitted in the output.  This is per the
reference GFM implementation, [cmark-gfm](https://github.com/github/cmark).

Ampersands were not being correctly escaped in link targets, making it possible
to fashion unsafe URLs using schemes like `data:` or `javascript:` by entering
them as HTML entities, e.g. `&#x64&#x61&#x74&#x61&#x3a`.  The intended
behaviour, demonstrated upstream, is that these should be escaped and therefore
harmless, but this behaviour was broken in comrak.


Summary: `cpuid-bool` has been renamed to `cpufeatures`

Please use the `cpufeatures`` crate going forward:

<https://github.com/RustCrypto/utils/tree/master/cpufeatures>

There will be no further releases of `cpuid-bool`.


Summary: anymap is unmaintained.

The `anymap` crate does not appear to be maintained, and the most recent
published version 0.12.1 includes a soundness bug. This has been
[fixed](https://github.com/chris-morgan/anymap/pull/32) a few years ago, but
was never released.


Summary: Denial of service on EVM execution due to memory over-allocation

Prior to the patch, when executing specific EVM opcodes related
to memory operations that use `evm_core::Memory::copy_large`, the
crate can over-allocate memory when it is not needed, making it
possible for an attacker to perform denial-of-service attack.

The flaw was corrected in commit `19ade85`.


Summary: Memory access due to code generation flaw in Cranelift module

There is a bug in 0.73.0 of the Cranelift x64 backend that can create a
scenario that could result in a potential sandbox escape in a WebAssembly
module. Users of versions 0.73.0 of Cranelift should upgrade to either 0.73.1
or 0.74 to remediate this vulnerability. Users of Cranelift prior to 0.73.0
should update to 0.73.1 or 0.74 if they were not using the old default backend.

More details can be found in the GitHub Security Advisory at:

<https://github.com/bytecodealliance/wasmtime/security/advisories/GHSA-hpqh-2wqx-7qp5>


Summary: Soundness issue in `iced-x86` versions <= 1.10.3

Versions of iced-x86 <= 1.10.3 invoke undefined behavior which may cause soundness
issues in crates using the `iced_x86::Decoder` struct. The `Decoder::new()` function
made a call to `slice.get_unchecked(slice.length())` to get the end position of
the input buffer. The flaw was fixed with safe logic that does not invoke undefined
behavior.

More details can be found at <https://github.com/icedland/iced/issues/168>.


Summary: SMTP command injection in body

Affected versions of lettre allowed SMTP command injection through an attacker's controlled message body. The module for escaping lines starting with a period wouldn't catch a period that was placed after a double CRLF sequence, allowing the attacker to end the current message and write arbitrary SMTP commands after it.

The flaw is fixed by correctly handling consecutive CRLF sequences.


Summary: VecStorage Deserialize Allows Violation of Length Invariant

The `Deserialize` implementation for `VecStorage` did not maintain the invariant that the number of elements must equal `nrows * ncols`. Deserialization of specially crafted inputs could allow memory access beyond allocation of the vector.

This flaw was introduced in v0.11.0 ([`086e6e`](https://github.com/dimforge/nalgebra/commit/086e6e719f53fecba6dadad2e953a487976387f5)) due to the addition of an automatically derived implementation of `Deserialize` for `MatrixVec`. `MatrixVec` was later renamed to `VecStorage` in v0.16.13 ([`0f66403`](https://github.com/dimforge/nalgebra/commit/0f66403cbbe9eeac15cedd8a906c0d6a3d8841f2)) and continued to use the automatically derived implementation of `Deserialize`.

This flaw was corrected in commit [`5bff536`](https://github.com/dimforge/nalgebra/commit/5bff5368bf38ddfa31416e4ae9897b163031a513) by returning an error during deserialization if the number of elements does not exactly match the expected size.


Summary: `grep-cli` may run arbitrary executables on Windows

On Windows in versions of `grep-cli` prior to `0.1.6`, it's possible for some
of the routines to execute arbitrary executables. In particular, a quirk of
the Windows process execution API is that it will automatically consider the
current directory before other directories when resolving relative binary
names. Therefore, if you use `grep-cli` to read decompressed files in an
untrusted directory with that directory as the CWD, a malicious actor to could
put, e.g., a `gz.exe` binary in that directory and `grep-cli` will use the
malicious actor's version of `gz.exe` instead of the system's.

This is also technically possible on Unix as well, but only if the `PATH`
variable contains `.`. Conventionally, they do not.

A `DecompressionReader` has been fixed to automatically resolve binary names
using `PATH`, instead of relying on the Windows API to do it.

If you use `grep-cli`'s `CommandReader` with a `std::process::Command` value
on Windows, then it is recommended to either construct the `Command` with an
absolute binary name, or use `grep-cli`'s new
[`resolve_binary`](https://docs.rs/grep-cli/0.1.6/grep_cli/fn.resolve_binary.html)
helper function.

To be clear, `grep-cli 0.1.6` mitigates this issue in two ways:

* A `DecompressionReader` will resolve decompression programs to absolute
paths automatically using the `PATH` environment variable, instead of relying
on Windows APIs to do it (which would result in the undesirable behavior of
checking the CWD for a program first).
* A new function, `resolve_binary`, was added to help users of this crate
mitigate this behavior when they need to create their own
`std::process::Command`. For example,
[ripgrep uses `grep_cli::resolve_binary`](https://github.com/BurntSushi/ripgrep/blob/7ce66f73cf7e76e9f2557922ac8e650eb02cf4ed/crates/core/search.rs#L119-L122)
on the argument given to its `--pre` flag.

While the first mitigation fixes this issue for sensible values of `PATH`
when doing decompression search, the second mitigation is imperfect. The more
fundamental issue is that `std::process::Command` is itself vulnerable to this.


Summary: Task dropped in wrong thread when aborting `LocalSet` task

When aborting a task with `JoinHandle::abort`, the future is dropped in the
thread calling abort if the task is not currently being executed. This is
incorrect for tasks spawned on a `LocalSet`.

This can easily result in race conditions as many projects use `Rc` or `RefCell`
in their Tokio tasks for better performance.

See [tokio#3929][issue] for more details.

[issue]: https://github.com/tokio-rs/tokio/issues/3929


Summary: Conversion from `prost_types::Timestamp` to `SystemTime` can cause an overflow and panic

Affected versions of this crate contained a bug in which untrusted input could cause an overflow and panic when converting a `Timestamp` to `SystemTime`.

It is recommended to upgrade to `prost-types` v0.8 and switch the usage of `From<Timestamp> for SystemTime` to `TryFrom<Timestamp> for SystemTime`.

See [#438] for more information.

[#438]: https://github.com/tokio-rs/prost/issues/438


Summary: Incorrect handling of embedded SVG and MathML leads to mutation XSS

Affected versions of this crate did not account for namespace-related parsing
differences between HTML, SVG, and MathML. Even if the `svg` and `math` elements
are not allowed, the underlying HTML parser still treats them differently.
Running cleanup without accounting for these differing namespaces resulted in an "impossible"
DOM, which appeared "safe" when examining the DOM tree, but when serialized and deserialized,
could be exploited to inject arbitrary markup.

To exploit this, the application using this library must allow a tag that is parsed as raw text in HTML.
These [elements] are:

* title
* textarea
* xmp
* iframe
* noembed
* noframes
* plaintext
* noscript
* style
* script

Applications that do not explicitly allow any of these tags should not be affected, since none are allowed by default.

[elements]: https://github.com/servo/html5ever/blob/57eb334c0ffccc6f88d563419f0fbeef6ff5741c/html5ever/src/tree_builder/rules.rs


Summary: Flaw in `FieldVar::mul_by_inverse` allows unsound R1CS constraint systems

Versions `0.2.0` to `0.3.0` of ark-r1cs-std did not enforce any constraints in the `FieldVar::mul_by_inverse` method, allowing a malicious prover to produce an unsound proof that passes all verifier checks.
This method was used primarily in scalar multiplication for [`short_weierstrass::ProjectiveVar`](https://docs.rs/ark-r1cs-std/0.3.0/ark_r1cs_std/groups/curves/short_weierstrass/struct.ProjectiveVar.html).

This bug was fixed in commit `47ddbaa`, and was released as part of version `0.3.1` on `crates.io`.


Summary: libsecp256k1 allows overflowing signatures

libsecp256k1 accepts signatures whose R or S parameter is larger than the
secp256k1 curve order, which differs from other implementations. This could
lead to invalid signatures being verified.

The error is resolved in 0.5.0 by adding a `check_overflow` flag.


Summary: `better-macro` has deliberate RCE to prove a point

[better-macro](https://crates.io/crates/better-macro) is a fake crate which is
"Proving A Point" that proc-macros can run arbitrary code. This is not a particularly
novel or interesting observation.

It currently opens `https://github.com/raycar5/better-macro/blob/master/doc/hi.md`
which doesn't appear to have any malicious content, but there's no guarantee that
will remain the case.

This crate has no useful functionality, and should not be used.


Summary: Lenient `hyper` header parsing of `Content-Length` could allow request smuggling

`hyper`'s HTTP header parser accepted, according to RFC 7230, illegal contents inside `Content-Length` headers.
Due to this, upstream HTTP proxies that ignore the header may still forward them along if it chooses to ignore the error.

To be vulnerable, `hyper` must be used as an HTTP/1 server and using an HTTP proxy upstream that ignores the header's contents
but still forwards it. Due to all the factors that must line up, an attack exploiting this vulnerability is unlikely.


Summary: Integer overflow in `hyper`'s parsing of the `Transfer-Encoding` header leads to data loss

When decoding chunk sizes that are too large, `hyper`'s code would encounter an integer overflow. Depending on the situation,
this could lead to data loss from an incorrect total size, or in rarer cases, a request smuggling attack.

To be vulnerable, you must be using `hyper` for any HTTP/1 purpose, including as a client or server, and consumers must send
requests or responses that specify a chunk size greater than 18 exabytes. For a possible request smuggling attack to be possible,
any upstream proxies must accept a chunk size greater than 64 bits.


Summary: Links in archive can create arbitrary directories

When unpacking a tarball that contains a symlink the `tar` crate may create
directories outside of the directory it's supposed to unpack into.

The function errors when it's trying to create a file, but the folders are
already created at this point.

```rust
use std::{io, io::Result};
use tar::{Archive, Builder, EntryType, Header};

fn main() -> Result<()> {
    let mut buf = Vec::new();

    {
        let mut builder = Builder::new(&mut buf);

        // symlink: parent -> ..
        let mut header = Header::new_gnu();
        header.set_path("symlink")?;
        header.set_link_name("..")?;
        header.set_entry_type(EntryType::Symlink);
        header.set_size(0);
        header.set_cksum();
        builder.append(&header, io::empty())?;

        // file: symlink/exploit/foo/bar
        let mut header = Header::new_gnu();
        header.set_path("symlink/exploit/foo/bar")?;
        header.set_size(0);
        header.set_cksum();
        builder.append(&header, io::empty())?;

        builder.finish()?;
    };

    Archive::new(&*buf).unpack("demo")
}
```

This has been fixed in https://github.com/alexcrichton/tar-rs/pull/259 and is
published as `tar` 0.4.36. Thanks to Martin Michaelis (@mgjm) for discovering
and reporting this, and Nikhil Benesch (@benesch) for the fix!


Summary: Potential request smuggling capabilities due to lack of input validation

Affected versions of this crate did not properly detect invalid requests that could allow HTTP/1 request smuggling (HRS) attacks when running alongside a vulnerable front-end proxy server. This can result in leaked internal and/or user data, including credentials, when the front-end proxy is also vulnerable.

Popular front-end proxies and load balancers already mitigate HRS attacks so it is recommended that they are also kept up to date; check your specific set up. You should upgrade even if the front-end proxy receives exclusively HTTP/2 traffic and connects to the back-end using HTTP/1; several downgrade attacks are known that can also expose HRS vulnerabilities.


Summary: vec-const attempts to construct a Vec from a pointer to a const slice

Affected versions of this crate claimed to construct a const `Vec` with nonzero length and capacity, but that cannot be done because such a `Vec` requires a pointer from an allocator.

The implementation was later changed to just construct a `std::borrow::Cow`.


Summary: QueryInterface should call AddRef before returning pointer

Affected version of this crate, which is a required dependency in com-impl,
provides a faulty implementation of the `IUnknown::QueryInterface` method.

`QueryInterface` implementation must call `IUnknown::AddRef` before returning the pointer,
as describe in this documentation:
<https://docs.microsoft.com/en-us/windows/win32/api/unknwn/nf-unknwn-iunknown-queryinterface(refiid_void)>

As it is not incrementing the refcount as expected, the following calls to `IUnknown::Release` method
will cause WMI to drop reference to the interface, and can lead to invalid reference.

This is documented in <https://docs.microsoft.com/en-us/windows/win32/learnwin32/managing-the-lifetime-of-an-object#reference-counting>

There is no simple workaround, as you can't know how many time QueryInterface will be called.
The only way to quick fix this is to use the macro expanded version of the code and modify
the QueryInterface method to add the AddRef call yourself.

The issue was corrected in commit `9803f31fbd1717d482d848f041044d061fca6da7`.


Summary: `Read` on uninitialized buffer can cause UB (impl of `ReadKVExt`)

Affected versions of this crate passes an uninitialized buffer to a user-provided `Read` implementation.

Arbitrary `Read` implementations can read from the uninitialized buffer (memory exposure) and also can return incorrect number of bytes written to the buffer.
Reading from uninitialized memory produces undefined values that can quickly invoke undefined behavior.


Summary: 'Read' on uninitialized memory may cause UB

Affected versions of this crate passes an uninitialized buffer to a user-provided `Read` implementation. The crate currently contains 4 occurrences of such cases.

Arbitrary `Read` implementations can read from the uninitialized buffer (memory exposure) and also can return incorrect number of bytes written to the buffer.
Reading from uninitialized memory produces undefined values that can quickly invoke undefined behavior.


Summary: `Read` on uninitialized buffer may cause UB ( `read_entry()` )

Affected versions of this crate passes an uninitialized buffer to a user-provided `Read` implementation.
There are two of such cases (`go_offset_log::read_entry()` & `offset_log::read_entry()`).

Arbitrary `Read` implementations can read from the uninitialized buffer (memory exposure) and also can return incorrect number of bytes written to the buffer.
Reading from uninitialized memory produces undefined values that can quickly invoke undefined behavior.


Summary: columnar: `Read` on uninitialized buffer may cause UB (ColumnarReadExt::read_typed_vec())

Affected versions of this crate passes an uninitialized buffer to a user-provided `Read` implementation (`ColumnarReadExt::read_typed_vec()`).

Arbitrary `Read` implementations can read from the uninitialized buffer (memory exposure) and also can return incorrect number of bytes written to the buffer.
Reading from uninitialized memory produces undefined values that can quickly invoke undefined behavior.


Summary: `Read` on uninitialized memory may cause UB (fn preamble_skipcount())

Affected versions of this crate passes an uninitialized buffer to a user-provided `Read` implementation (within `fn preamble_skipcount()`).

Arbitrary `Read` implementations can read from the uninitialized buffer (memory exposure) and also can return incorrect number of bytes written to the buffer.
Reading from uninitialized memory produces undefined values that can quickly invoke undefined behavior.


Summary: Optional `Deserialize` implementations lacking validation

When activating the non-default feature `serialize`, most structs implement
`serde::Deserialize` without sufficient validation. This allows breaking
invariants in safe code, leading to:

* Undefined behavior in `as_string()` methods (which use
  `std::str::from_utf8_unchecked()` internally).
* Panics due to failed assertions.

See https://github.com/gz/rust-cpuid/issues/43.


Summary: Reading on uninitialized memory may cause UB ( `util::read_spv()` )


Summary: Reading on uninitialized buffer may cause UB ( `gfx_auxil::read_spirv()` )


Summary: Deserialization functions pass uninitialized memory to user-provided Read

Affected versions of this crate passed an uninitialized buffer to a
user-provided `Read` instance in:

* `deserialize_binary`
* `deserialize_string`
* `deserialize_extension_others`
* `deserialize_string_primitive`

This can result in safe `Read` implementations reading from the uninitialized
buffer leading to undefined behavior.


Summary: Data race in crossbeam-deque

In the affected version of this crate, the result of the race condition is that one or more tasks in the worker queue can be popped twice instead of other tasks that are forgotten and never popped. If tasks are allocated on the heap, this can cause double free and a memory leak. If not, this still can cause a logical bug.

Crates using `Stealer::steal`, `Stealer::steal_batch`, or `Stealer::steal_batch_and_pop` are affected by this issue.

Credits to @kmaork for discovering, reporting and fixing the bug.


Summary: Window can read out of bounds if Read instance returns more bytes than buffer size

`rdiff` performs a diff of two provided strings or files. As part of its reading
code it uses the return value of a `Read` instance to set the length of
its internal character vector.

If the `Read` implementation claims that it has read more bytes than the length
of the provided buffer, the length of the vector will be set to longer than its
capacity. This causes `rdiff` APIs to return uninitialized memory in its API
methods.


Summary: `mopa` is technically unsound

The `mopa` crate redefines the deprecated `TraitObject` struct from `core::raw` like so:
```rust
#[repr(C)]
#[derive(Copy, Clone)]
#[doc(hidden)]
pub struct TraitObject {
    pub data: *mut (),
    pub vtable: *mut (),
}
```
This is done to then transmute a reference to a trait object (`&dyn Trait` for any trait `Trait`) into this struct and retrieve the `data` field for the purpose of downcasting. This is used to implement `downcast_ref_unchecked()`, in terms of which `downcast_ref()` is also implemented. Same goes for mutable reference downcasting and `Box` downcasting.

The Rust compiler explicitly reserves the right to change the memory layout of `&dyn Trait` for any trait `Trait`. The worst case scenario is that it swaps `data` and `vtable`, making an executable location breach and compromisation of ASLR possible, since reads from `data` would read `vtable` instead. Likewise, arbitrary code execution is also theoretically possible if reads of `vtable` generated by the compiler read `data` instead.

While, as of Rust 1.52, this unsound assumption still holds true, updating the compiler may silently create UB in a crate which previously compiled and run without issues, compromising the security of builds which are believed to be reproducible.

A potential strategy to resolve this has already been suggested in an issue on the GitHub repository of the crate.


Summary: spirv_headers is unmaintained, use spirv instead

Because of versioning issues; the `spirv_headers` crate is unmaintained. Use [spirv](https://crates.io/crates/spirv)
for parsing spirv files.


Summary: SM2 Decryption Buffer Overflow

In order to decrypt SM2 encrypted data an application is expected to call the
API function `EVP_PKEY_decrypt()`. Typically an application will call this
function twice. The first time, on entry, the "out" parameter can be NULL and,
on exit, the "outlen" parameter is populated with the buffer size required to
hold the decrypted plaintext. The application can then allocate a sufficiently
sized buffer and call `EVP_PKEY_decrypt()` again, but this time passing a non-NULL
value for the "out" parameter.

A bug in the implementation of the SM2 decryption code means that the
calculation of the buffer size required to hold the plaintext returned by the
first call to `EVP_PKEY_decrypt()` can be smaller than the actual size required by
the second call. This can lead to a buffer overflow when `EVP_PKEY_decrypt()` is
called by the application a second time with a buffer that is too small.

A malicious attacker who is able present SM2 content for decryption to an
application could cause attacker chosen data to overflow the buffer by up to a
maximum of 62 bytes altering the contents of other data held after the
buffer, possibly changing application behaviour or causing the application to
crash. The location of the buffer is application dependent but is typically
heap allocated.


Summary: Read buffer overruns processing ASN.1 strings

ASN.1 strings are represented internally within OpenSSL as an ASN1_STRING
structure which contains a buffer holding the string data and a field holding
the buffer length. This contrasts with normal C strings which are represented as
a buffer for the string data which is terminated with a NUL (0) byte.

Although not a strict requirement, ASN.1 strings that are parsed using OpenSSL's
own "d2i" functions (and other similar parsing functions) as well as any string
whose value has been set with the ASN1_STRING_set() function will additionally
NUL terminate the byte array in the ASN1_STRING structure.

However, it is possible for applications to directly construct valid ASN1_STRING
structures which do not NUL terminate the byte array by directly setting the
"data" and "length" fields in the ASN1_STRING array. This can also happen by
using the `ASN1_STRING_set0()` function.

Numerous OpenSSL functions that print ASN.1 data have been found to assume that
the ASN1_STRING byte array will be NUL terminated, even though this is not
guaranteed for strings that have been directly constructed. Where an application
requests an ASN.1 structure to be printed, and where that ASN.1 structure
contains ASN1_STRINGs that have been directly constructed by the application
without NUL terminating the "data" field, then a read buffer overrun can occur.

The same thing can also occur during name constraints processing of certificates
(for example if a certificate has been directly constructed by the application
instead of loading it via the OpenSSL parsing functions, and the certificate
contains non NUL terminated ASN1_STRING structures). It can also occur in the
`X509_get1_email()`, `X509_REQ_get1_email()` and `X509_get1_ocsp()` functions.

If a malicious actor can cause an application to directly construct an
ASN1_STRING and then process it through one of the affected OpenSSL functions
then this issue could be hit. This might result in a crash (causing a Denial of
Service attack). It could also result in the disclosure of private memory
contents (such as private keys, or sensitive plaintext).


Summary: Crate has been renamed to `cosmrs`

The `cosmos_sdk` crate, which provides a basic Rust SDK for the Cosmos ecosystem,
has rebranded to “CosmRS” in the spirit of other projects like CosmJS and CosmWasm.

You can find the new home here:

https://github.com/cosmos/cosmos-rust/tree/main/cosmrs

The new crate name is `cosmrs`:

https://crates.io/crates/cosmrs


Summary: Miscomputed results when using AVX2 backend

The v0.9.7 release of the `sha2` crate introduced a new AVX2-accelerated
backend which was automatically enabled for all x86/x86_64 CPUs where AVX2
support was autodetected at runtime.

This backend was buggy and would miscompute results for long messages
(i.e. messages spanning multiple SHA blocks).

The crate has since been yanked, but any users who upgraded to v0.9.7 should
immediately upgrade to v0.9.8 and recompute any hashes which were previously
computed by v0.9.7.


Summary: Permissions bypass in pleaser

Failure to normalize the umask in pleaser before 0.4 allows a local attacker to gain full root privileges if they are allowed to execute at least one command.


Summary: Permissions bypass in pleaser

pleaseedit in pleaser before 0.4 uses predictable temporary filenames in /tmp and the target directory. This allows a local attacker to gain full root privileges by staging a symlink attack.


Summary: Partial read is incorrect in molecule

Anyone who uses total_size(..) function to partial read the length of any FixVec will get an incorrect result, due to an incorrect implementation. This has been resolved in the 0.7.2 release.


Summary: File exposure in pleaser

pleaser before 0.4 allows a local unprivileged attacker to gain knowledge about the existence of files or directories in privileged locations via the search_path function, the --check option, or the -d option.


Summary: Relative Path Traversal in git-delta

git-delta before 0.8.3 on Windows resolves an executable's pathname as a relative path from the current directory.


Summary: Uncontrolled Search Path Element in sharkdp/bat

bat on windows before 0.18.2 executes programs named less.exe from the current working directory. This can lead to unintended code execution.


Summary: Miner fails to get block template when a cell used as a cell dep has been destroyed.

## Impact

The RPC get_block_template fails when a cell has been used as a cell dep and an input in the different transactions.

Say cell C is used as a dep group in the transaction A, and is destroyed in the transaction B.

The node adds transaction A first, then B into the transaction pool. They are both valid. But when generating the block template, if the fee rate of B is higher, it comes before A, which will invalidate A. Currently the RPC get_block_template will fail instead of dropping A.

## Patch

First, the get_block_template should not fail but dropping the conflict transactions.

Then we can propose solution to this issue. Here is an example. When a transaction is added to the pool, the pool must consider it depending on all the transactions which dep cell (direct or indirect via dep group) has been destroyed in this transaction. Because future transactions using the destroyed cells as dep will be rejected, the spending transaction only need to wait for all the existing dep transactions on chain.

## Workaround

    Submit transaction B when A is already on chain.
    Let B depend on A explicitly, there are several solutions:
        a. Add any output cell on A as a dep cell or input in B.
        b. Merge A and B. CKB allows using the same cell as both dep and input in the same transaction.
    Ensure the fee rate of B is less than A so A always has higher priority.


Summary: Remote memory exhaustion in ckb

In the ckb sync protocol, SyncState maintains a HashMap called 'misbehavior' that keeps a score of a peer's violations of the protocol. This HashMap is keyed to PeerIndex (an alias for SessionId), and entries are never removed from it. SessionId is an integer that increases monotonically with every new connection.

A remote attacker can manipulate this HashMap to grow forever, resulting in degraded performance and ultimately a panic on allocation failure or being killed by the OS, depending on the platform.

This is a critical severity security bug. It could be exploited to create a targeted or network-wide denial of service, to reduce the hash power of the network as part of a 51% attack, and perhaps in other creative ways.


Summary: Process crashes when the cell used as DepGroup is not alive

It's easy to create a malign transaction which uses the dead cell as the DepGroup in the DepCells. The transaction can crash all the receiving nodes.


Summary: Multiple Vulnerabilities in Wasmtime

* [Use after free passing `externref`s to Wasm in
  Wasmtime](https://github.com/bytecodealliance/wasmtime/security/advisories/GHSA-v4cp-h94r-m7xf)

* [Out-of-bounds read/write and invalid free with `externref`s and GC safepoints
  in
  Wasmtime](https://github.com/bytecodealliance/wasmtime/security/advisories/GHSA-4873-36h9-wv49)

* [Wrong type for `Linker`-define functions when used across two
  `Engine`s](https://github.com/bytecodealliance/wasmtime/security/advisories/GHSA-q879-9g95-56mx)


Summary: Memory Safety Issue when using `patch` or `merge` on `state` and assign the result back to `state`

Affected versions of this crate maintains references to memory that might have been freed already.
If affects the following two `tremor-script` language constructs:

* A [Merge](https://www.tremor.rs/docs/tremor-script/index#merge) where we assign the result back to the target expression
  and the expression to be merged needs to reference the `event`:

```
let state = merge state of event end;
```

* A [Patch](https://www.tremor.rs/docs/tremor-script/index#patch) where we assign the result back to the target expression
  and the patch operations used need to reference the `event`:

```
let state = patch state of insert event.key => event.value end;
```

For constructs like this (it doesnt matter what is references in the expression to be merged or the patch operations) an optimization
was applied to manipulate the target value in-place, instead of cloning it.

Our `Value` struct which underpins all event data in `tremor-script`, is representing as borrowed strings `beef::Cow<'lifetime, str>`
that reference the actual `Vec<u8>` the event is based upon. We keep the raw byte-array next to the event structure inside our `Event` struct as a self-referential struct,
so we make sure that the structured `Value` and its references are valid across its whole lifetime.

The optimization was considered safe as long as it was only possible to merge or patche `event` data or static data.
When `state` was introduced to `tremor-script` a new possibility existed, to keep `Value` data around for longer than the lifetime of an event.
If `event` data is merged or patched into `state` without cloning `state` first, it can still reference keys or values from
the previous event, which will now be invalid. This allows access to those already freed regions of memory and to get their content out over the wire.

## Workaround

If an upgrade is not possible, a possible workaround is to avoid the optimization
by introducing a temporary variable and not immediately reassigning to `state`:

```
let tmp = merge state of event end;
let state = tmp
```

## Fix

The flaw was corrected in `tremor-script` version 0.11.6 via commit [1a2efcd](https://github.com/tremor-rs/tremor-runtime/commit/1a2efcdbe68e5e7fd0a05836ac32d2cde78a0b2e) by removing the optimization
and always clone the target expression of a [Merge](https://www.tremor.rs/docs/tremor-script/index#merge) or [Patch](https://www.tremor.rs/docs/tremor-script/index#patch.


Summary: `Read` on uninitialized buffer may cause UB ('tectonic_xdv' crate)

Affected versions of this crate passes an uninitialized buffer to a user-provided `Read` implementation.

Arbitrary `Read` implementations can read from the uninitialized buffer (memory exposure) and also can return incorrect number of bytes written to the buffer. Reading from uninitialized memory produces undefined values that can quickly invoke undefined behavior.

The problem was fixed in commit `cdff034` by zero-initializing the buffer before passing it to a user-provided `Read` implementation.


Summary: AtomicBucket<T> unconditionally implements Send/Sync

In the affected versions of the crate, `AtomicBucket<T>` unconditionally implements `Send`/`Sync` traits. Therefore, users can create a data race to the inner
`T: !Sync` by using the `AtomicBucket::data_with()` API.
Such data races can potentially cause memory corruption or other undefined behavior.

The flaw was fixed in commit 8e6daab by adding appropriate Send/Sync bounds to the Send/Sync impl of struct `Block<T>` (which is a data type contained inside `AtomicBucket<T>`).


Summary: Aliased mutable references from `tls_rand` & `TlsWyRand`

`TlsWyRand`'s implementation of `Deref` unconditionally dereferences a raw pointer, and returns
multiple mutable references to the same object, which is undefined behavior.


Summary: `#[zeroize(drop)]` doesn't implement `Drop` for `enum`s

Affected versions of this crate did not implement `Drop` when `#[zeroize(drop)]` was used on an `enum`.

This can result in memory not being zeroed out after dropping it, which is exactly what is intended when adding this attribute.

The flaw was corrected in version 1.2 and `#[zeroize(drop)]` on `enum`s now properly implements `Drop`.


Summary: `BinaryArray` does not perform bound checks on reading values and offsets

`BinaryArray` performs insufficient validation on creation, which allows out-of-bounds reads in safe code.


Summary: `DecimalArray` does not perform bound checks on accessing values and offsets

`DecimalArray` performs insufficient bounds checks,
which allows out-of-bounds reads in safe code
if the length of the backing buffer is not a multiple of 16.


Summary: `FixedSizeBinaryArray` does not perform bound checks on accessing values and offsets

`FixedSizeBinaryArray` performs insufficient bounds checks, which allows out-of-bounds reads in safe code.


Summary: Out-of-bounds write in nix::unistd::getgrouplist

On certain platforms, if a user has more than 16 groups, the
`nix::unistd::getgrouplist` function will call the libc `getgrouplist`
function with a length parameter greater than the size of the buffer it
provides, resulting in an out-of-bounds write and memory corruption.

The libc `getgrouplist` function takes an in/out parameter `ngroups`
specifying the size of the group buffer. When the buffer is too small to
hold all of the requested user's group memberships, some libc
implementations, including glibc and Solaris libc, will modify `ngroups`
to indicate the actual number of groups for the user, in addition to
returning an error. The version of `nix::unistd::getgrouplist` in nix
0.16.0 and up will resize the buffer to twice its size, but will not
read or modify the `ngroups` variable. Thus, if the user has more than
twice as many groups as the initial buffer size of 8, the next call to
`getgrouplist` will then write past the end of the buffer.

The issue would require editing /etc/groups to exploit, which is usually
only editable by the root user.

linux freebsd android netbsd dragonfly openbsd fuchsia


Summary: abomonation transmutes &T to and from &[u8] without sufficient constraints

This transmute is at the core of the abomonation crates. It's so easy to use it to violate alignment requirements that no test in the crate's test suite passes under miri.
The use of this transmute in serialization/deserialization also incorrectly assumes that the layout of a repr(Rust) type is stable.
This transmute can also disclose both the contents of padding bytes which may be an information leak and the contents of pointers, which may be used to defeat ASLR.


Summary: Non-aligned u32 read in Chacha20 encryption and decryption

The implementation does not enforce alignment requirements on input slices while incorrectly assuming 4-byte alignment through an unsafe call to `std::slice::from_raw_parts_mut`, which breaks the contract and introduces undefined behavior.

This affects Chacha20 encryption and decryption in crypto2.


Summary: Generated code can read and write out of bounds in safe code

Code generated by flatbuffers' compiler is `unsafe` but not marked as such.
See https://github.com/google/flatbuffers/issues/6627 for details.

For example, if generated code is used to decode malformed or untrusted input,
undefined behavior (and thus security vulnerabilities) is possible even without
the use of the `unsafe` keyword, [violating the the meaning of "safe"](https://doc.rust-lang.org/std/keyword.unsafe.html#the-different-meanings-of-unsafe) code;

All users that use generated code by `flatbuffers` compiler are recommended to:
1. not expose flatbuffer generated code as part of their public APIs
2. audit their code and look for any usage of `follow`, `push`, or any method that uses them
   (e.g. `self_follow`).
3. Carefully go through the crates' documentation to understand which "safe" APIs are not
   intended to be used.


Summary: Converting `NSString` to a String Truncates at Null Bytes

Methods of [`NSString`] for conversion to a string may return a partial result.
Since they call [`CStr::from_ptr`] on a pointer to the string buffer, the
string is terminated at the first null byte, which might not be the end of the
string.

In addition to the vulnerable functions listed for this issue, the
implementations of [`Display`], [`PartialEq`], [`PartialOrd`], and [`ToString`]
for [`NSString`] are also affected, since they call those functions.

## Impact

Since [`NSString`] is commonly used as the type for paths by the [Foundation]
framework, null byte truncation might allow for easily bypassing file extension
checks. For example, if a file name is provided by a user and validated to have
one of a specific set of extensions, with validation taking place before
truncation, an attacker can add an accepted extension after a null byte (e.g.,
`file.exe\0.txt`). After truncation, the file name used by the application
would be `file.exe`.

It would be better to generate unique names for files, instead of using
user-provided names, but not all applications take this approach.

## Example:

```rust
let string = NSString::from_str("null\0byte");
println!("{}", string);
```

That example only prints the string "null".

[`CStr::from_ptr`]: https://doc.rust-lang.org/std/ffi/struct.CStr.html#method.from_ptr
[`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
[Foundation]: https://developer.apple.com/documentation/foundation
[`NSString`]: https://docs.rs/fruity/0.2.0/fruity/foundation/struct.NSString.html
[`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
[`PartialOrd`]: https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html
[`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html


Summary: Data race when sending and receiving after closing a `oneshot` channel

If a `tokio::sync::oneshot` channel is closed (via the
[`oneshot::Receiver::close`] method), a data race may occur if the
`oneshot::Sender::send` method is called while the corresponding
`oneshot::Receiver` is `await`ed or calling `try_recv`.

When these methods are called concurrently on a closed channel, the two halves
of the channel can concurrently access a shared memory location, resulting in a
data race. This has been observed to [cause memory corruption][corruption].

Note that the race only occurs when **both** halves of the channel are used
after the `Receiver` half has called `close`. Code where `close` is not used, or where the
`Receiver` is not `await`ed and `try_recv` is not called after calling `close`,
is not affected.

See [tokio#4225][issue] for more details.

[corruption]: https://github.com/tokio-rs/tokio/issues/4225#issuecomment-967434847
[issue]: https://github.com/tokio-rs/tokio/issues/4225
[`oneshot::Receiver::close`]: https://docs.rs/tokio/1.14.0/tokio/sync/oneshot/struct.Receiver.html#method.close


Summary: Panic on incorrect date input to `simple_asn1`

Version 0.6.0 of the `simple_asn1` crate panics on certain malformed
inputs to its parsing functions, including `from_der` and `der_decode`.
Because this crate is frequently used with inputs from the network, this
should be considered a security vulnerability.

The issue occurs when parsing the old ASN.1 "UTCTime" time format.  If an
attacker provides a UTCTime where the first character is ASCII but the
second character is above 0x7f, a string slice operation in the
`from_der_` function will try to slice into the middle of a UTF-8
character, and cause a panic.

This error was introduced in commit
[`d7d39d709577710e9dc8`](https://github.com/acw/simple_asn1/commit/d7d39d709577710e9dc8833ee57d200eef366db8),
which updated `simple_asn1` to use `time` instead of `chrono` because of
[`RUSTSEC-2020-159`](https://rustsec.org/advisories/RUSTSEC-2020-0159).
Versions of `simple_asn1` before 0.6.0 are not affected by this issue.

The [patch](https://github.com/acw/simple_asn1/pull/28) was applied in
`simple_asn1` version 0.6.1.


Summary: RustEmbed generated `get` method allows for directory traversal when reading files from disk

When running in debug mode and the `debug-embed` (off by default) feature is
not enabled, the generated `get` method does not check that the input path is
a child of the folder given.

This allows attackers to read arbitrary files in the file system if they have
control over the filename given. The following code will print the contents of
your `/etc/passwd` if adjusted with a correct number of `../`s depending on
where it is run from.

```rust
#[derive(rust_embed::RustEmbed)]
#[folder = "src/"]
pub struct Asset;

fn main() {
    let d = Asset::get("../../../etc/passwd").unwrap().data;
    println!("{}", String::from_utf8_lossy(&d));
}
```

The flaw was corrected by canonicalizing the input filename and ensuring that
it starts with the canonicalized folder path.


Summary: serde_cbor is unmaintained

The `serde_cbor` crate is unmaintained. The author has archived the github repository.

Alternatives proposed by the author:

 * [`ciborium`](https://crates.io/crates/ciborium)
 * [`minicbor`](https://crates.io/crates/minicbor)


Summary: Incorrect Lifetime Bounds on Closures in `rusqlite`

The lifetime bound on several closure-accepting `rusqlite` functions (specifically, functions which register a callback to be later invoked by SQLite) was too relaxed. If a closure referencing borrowed values on the stack is was passed to one of these functions, it could allow Rust code to access objects on the stack after they have been dropped.

The impacted functions are:

- Under `cfg(feature = "functions")`: `Connection::create_scalar_function`, `Connection::create_aggregate_function` and `Connection::create_window_function`.
- Under `cfg(feature = "hooks")`: `Connection::commit_hook`, `Connection::rollback_hook` and `Connection::update_hook`.
- Under `cfg(feature = "collation")`: `Connection::create_collation`.

The issue exists in all `0.25.*` versions prior to `0.25.4`, and all `0.26.*` versions prior to 0.26.2 (specifically: `0.25.0`, `0.25.1`, `0.25.2`, `0.25.3`, `0.26.0`, and `0.26.1`).

The fix is available in versions `0.26.2` and newer, and also has been back-ported to `0.25.4`. As it does not exist in `0.24.*`, all affected versions should have an upgrade path to a semver-compatible release.


Summary: Invalid handling of `X509_verify_cert()` internal errors in libssl

Internally libssl in OpenSSL calls `X509_verify_cert()` on the client side to
verify a certificate supplied by a server. That function may return a negative
return value to indicate an internal error (for example out of memory). Such a
negative return value is mishandled by OpenSSL and will cause an IO function
(such as `SSL_connect()` or `SSL_do_handshake()`) to not indicate success and a
subsequent call to `SSL_get_error()` to return the value
`SSL_ERROR_WANT_RETRY_VERIFY`. This return value is only supposed to be returned
by OpenSSL if the application has previously called
`SSL_CTX_set_cert_verify_callback()`. Since most applications do not do this the
`SSL_ERROR_WANT_RETRY_VERIFY` return value from `SSL_get_error()` will be totally
unexpected and applications may not behave correctly as a result. The exact
behaviour will depend on the application but it could result in crashes,
infinite loops or other similar incorrect responses.

This issue is made more serious in combination with a separate bug in OpenSSL
3.0 that will cause `X509_verify_cert()` to indicate an internal error when
processing a certificate chain. This will occur where a certificate does not
include the Subject Alternative Name extension but where a Certificate Authority
has enforced name constraints. This issue can occur even with valid chains.


Summary: Use after free in lru crate

Lru crate has use after free vulnerability.

Lru crate has two functions for getting an iterator. Both iterators give
references to key and value. Calling specific functions, like pop(), will remove
and free the value, and but it's still possible to access the reference of value
which is already dropped causing use after free.


Summary: Integer overflow in the bundled Brotli C library

A buffer overflow exists in the Brotli library versions prior to 1.0.8 where an attacker controlling the input length of a "one-shot" decompression request to a script can trigger a crash, which happens when copying over chunks of data larger than 2 GiB.

An updated version of `brotli-sys` has not been released. If one cannot update the C library, its authors recommend to use the "streaming" API as opposed to the "one-shot" API, and impose chunk size limits.

In Rust the issue can be mitigated by migrating to the `brotli` crate, which provides a Rust implementation of Brotli compression and decompression that is not affected by this issue.