cardano-base-rust

Security Best Practices for cardano-base-rust

This document outlines security best practices for contributing to cardano-base-rust.

Code Security Guidelines

1. Unsafe Code

When writing unsafe code, always add a SAFETY comment explaining:

Example:

// SAFETY: ptr is guaranteed non-null by the caller contract.
// We verified the allocation succeeded before reaching this point.
let non_null = unsafe { NonNull::new_unchecked(ptr) };

2. Error Handling

Good:

pub fn parse_key(bytes: &[u8]) -> Result<Key, KeyError> {
    if bytes.len() != KEY_SIZE {
        return Err(KeyError::InvalidLength {
            expected: KEY_SIZE,
            actual: bytes.len(),
        });
    }
    // ... safe parsing logic
}

Bad:

pub fn parse_key(bytes: &[u8]) -> Key {
    assert_eq!(bytes.len(), KEY_SIZE); // DON'T PANIC ON INPUT
    // ...
}

3. Memory Safety

4. Cryptographic Code

Example:

use subtle::ConstantTimeEq;

// Good: constant-time comparison
if key1.ct_eq(key2).into() {
    // ...
}

// Bad: timing attack vulnerable
if key1 == key2 {  // DON'T DO THIS
    // ...
}

5. Integer Overflow

6. Input Validation

7. Testing Security-Critical Code

Example test structure:

#[cfg(test)]
mod security_tests {
    use super::*;

    #[test]
    fn rejects_invalid_length() {
        let result = parse_key(&[0u8; 31]); // wrong size
        assert!(matches!(result, Err(KeyError::InvalidLength { .. })));
    }

    #[test]
    fn zeros_memory_on_drop() {
        let mut bytes = MLockedBytes::new(32).unwrap();
        bytes.as_mut_slice().fill(0xff);
        let ptr = bytes.as_ptr();
        drop(bytes);
        // Memory should be zeroed (requires careful testing)
    }
}

Code Review Checklist

Before submitting a PR with security-sensitive code, verify:

Reporting Security Issues

DO NOT open public issues for security vulnerabilities.

Instead, email: security@intersectmbo.org

Include:

See SECURITY.md for full details.

Dependencies

Adding New Dependencies

When adding dependencies:

  1. Check the crate’s security audit history
  2. Verify the license is compatible (see deny.toml)
  3. Review the crate’s use of unsafe code
  4. Check for active maintenance
  5. Run cargo audit after adding

Updating Dependencies

Tools

Required Tools

Install these tools for security checking:

# Security audit
cargo install cargo-audit

# License checking
cargo install cargo-deny

# Code coverage
cargo install cargo-tarpaulin

# Fuzzing (optional)
cargo install cargo-fuzz

Running Security Checks

# Run all checks
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
cargo audit
cargo deny check

# Generate coverage report
cargo tarpaulin --workspace --out Html

Resources

Contact

For security questions or concerns: