# SELinux and MAC Implementation Guide

## Overview

This document consolidates all information related to SELinux and Mandatory Access Control (MAC) implementation for the Debian bootc-image-builder project. It covers the transition from SELinux to AppArmor, implementation strategies, and compatibility considerations.

## Background

### Original SELinux Implementation (Red Hat/Fedora)

The original `bootc-image-builder` project was designed for Red Hat/Fedora systems and included SELinux as the primary Mandatory Access Control system. SELinux provides:

- **Type Enforcement**: Controls access between processes and objects
- **Role-Based Access Control**: Manages user roles and permissions
- **Multi-Level Security**: Supports hierarchical security classifications
- **Policy Management**: Centralized security policy configuration

### Debian's Approach: AppArmor

Debian systems use **AppArmor** instead of SELinux for Mandatory Access Control. AppArmor provides:

- **Path-Based Access Control**: Controls access to files and directories
- **Profile-Based Security**: Defines security profiles for applications
- **Learning Mode**: Automatic profile generation and refinement
- **Integration**: Native Debian package management support

## Strategic Decision: AppArmor-First Foundation

### Why AppArmor Over SELinux?

1. **Native Debian Support**: AppArmor is the default MAC system in Debian
2. **Simpler Integration**: Easier to integrate with existing Debian workflows
3. **Community Familiarity**: Debian developers are more familiar with AppArmor
4. **Package Availability**: AppArmor packages are readily available in Debian repositories

### Compatibility Considerations

- **Red Hat Compatibility**: Maintain compatibility with existing Red Hat workflows
- **Policy Translation**: Convert SELinux policies to AppArmor profiles where possible
- **Fallback Support**: Provide SELinux bypass mechanisms for compatibility

## Implementation Strategy

### Phase 1: AppArmor Foundation

#### 1.1 AppArmor Research and Planning
- Study Debian AppArmor documentation and implementation
- Research AppArmor profile management tools
- Analyze existing AppArmor stages in osbuild (if any)
- Research Debian AppArmor integration and configuration

#### 1.2 AppArmor Architecture Design
- Design enhanced AppArmor configuration schema
- Plan osbuild stage integration for AppArmor
- Design profile compilation and installation pipeline
- Plan Red Hat compatibility layer
- Design Debian-specific AppArmor configuration options

#### 1.3 AppArmor Implementation
- Implement enhanced AppArmor configuration system
- Create AppArmor profile manager
- Implement profile compilation pipeline
- Add configuration validation
- Create debian-apparmor-stage for osbuild

### Phase 2: Red Hat Compatibility (SELinux Bypass)

#### 2.1 SELinux Requirement Bypass
- Implement SELinux requirement bypass mechanisms
- Maintain Red Hat compatibility without SELinux
- Add enhanced AppArmor configuration options
- Ensure backward compatibility

#### 2.2 Testing and Validation
- Test builds work without SELinux
- Validate Red Hat compatibility
- Test AppArmor functionality
- Performance benchmarking

## Technical Implementation

### AppArmor Integration

#### Package Dependencies
```bash
# Core AppArmor packages
apparmor                    # Core AppArmor functionality
apparmor-utils             # Command-line tools
apparmor-profiles          # Default security profiles
apparmor-profiles-extra    # Additional profiles
```

#### Profile Management
```bash
# Profile status
aa-status                  # Check AppArmor status
aa-enforce /path/to/profile  # Enforce profile
aa-complain /path/to/profile # Complain mode (learning)
aa-disable /path/to/profile  # Disable profile
```

#### Profile Development
```bash
# Profile generation
aa-genprof /path/to/application  # Generate profile
aa-logprof                       # Refine profile based on logs
aa-mergeprof profile1 profile2   # Merge profiles
```

### SELinux Bypass Mechanisms

#### Configuration Options
```yaml
# Example configuration
apparmor:
  enabled: true
  profiles:
    - name: "bootc-builder"
      mode: "enforce"
      path: "/etc/apparmor.d/bootc-builder"
  
selinux:
  bypass: true
  compatibility_mode: "apparmor"
  fallback_policies: true
```

#### Runtime Behavior
- **SELinux Checks**: Automatically bypassed when SELinux is not available
- **AppArmor Enforcement**: Active when AppArmor is available
- **Fallback Policies**: Basic security policies when neither is available

## Integration with debos Backend

### AppArmor Actions in debos

```yaml
# debos template with AppArmor
actions:
  - action: run
    description: Install and configure AppArmor
    script: |
      #!/bin/bash
      set -e
      apt-get install -y apparmor apparmor-utils apparmor-profiles
      
      # Enable AppArmor
      systemctl enable apparmor
      
      # Create custom profile for bootc
      cat > /etc/apparmor.d/usr.sbin.bootc-builder << 'EOF'
      #include <tunables/global>
      /usr/sbin/bootc-builder {
        #include <abstractions/base>
        #include <abstractions/nameservice>
        
        # Allow access to container images
        /var/lib/containers/** r,
        /tmp/** rw,
        
        # Network access for package downloads
        network inet tcp,
        network inet udp,
      }
      EOF
      
      # Load and enforce profile
      apparmor_parser -r /etc/apparmor.d/usr.sbin.bootc-builder
      aa-enforce /usr/sbin/bootc-builder

  - action: run
    description: Configure SELinux bypass
    script: |
      #!/bin/bash
      set -e
      
      # Create compatibility layer
      mkdir -p /etc/selinux
      echo "SELINUX=disabled" > /etc/selinux/config
      
      # Log bypass for debugging
      echo "SELinux bypass configured - using AppArmor for MAC" >> /var/log/bootc-builder.log
```

## Testing and Validation

### AppArmor Testing

#### Profile Validation
```bash
# Test profile syntax
apparmor_parser -T /etc/apparmor.d/profile

# Test profile loading
apparmor_parser -r /etc/apparmor.d/profile

# Check profile status
aa-status | grep profile-name
```

#### Runtime Testing
```bash
# Test profile enforcement
aa-enforce /path/to/profile
# Run application and verify restrictions

# Test profile learning
aa-complain /path/to/profile
# Run application and check logs
```

### SELinux Compatibility Testing

#### Bypass Verification
```bash
# Verify SELinux is bypassed
getenforce 2>/dev/null || echo "SELinux not available"

# Check AppArmor is active
aa-status | grep -q "profiles are loaded" && echo "AppArmor active"
```

#### Cross-Platform Testing
- Test on Red Hat/Fedora systems
- Verify AppArmor fallback works
- Test SELinux bypass mechanisms
- Validate security policies

## Security Considerations

### AppArmor Security Model

1. **Profile Isolation**: Each application has its own security profile
2. **Path-Based Control**: Access control based on file system paths
3. **Network Control**: Network access can be restricted per profile
4. **Capability Control**: Linux capabilities can be restricted

### SELinux Bypass Security

1. **No Security Degradation**: AppArmor provides equivalent or better security
2. **Compatibility Mode**: Maintains security while ensuring compatibility
3. **Fallback Policies**: Basic security when advanced MAC is not available

## Future Enhancements

### Advanced AppArmor Features

1. **Profile Templates**: Reusable profile components
2. **Dynamic Profile Generation**: Automatic profile creation based on application behavior
3. **Integration with Container Security**: AppArmor profiles for containerized applications
4. **Policy Management**: Centralized profile management and distribution

### SELinux Integration (Optional)

1. **Hybrid Mode**: Support both AppArmor and SELinux simultaneously
2. **Policy Translation**: Convert SELinux policies to AppArmor profiles
3. **Runtime Switching**: Switch between MAC systems based on environment

## Troubleshooting

### Common AppArmor Issues

#### Profile Loading Failures
```bash
# Check profile syntax
apparmor_parser -T /etc/apparmor.d/profile

# Check system logs
journalctl -u apparmor

# Verify profile file permissions
ls -la /etc/apparmor.d/
```

#### Runtime Enforcement Issues
```bash
# Check profile status
aa-status

# Check specific profile
aa-status | grep profile-name

# View profile details
cat /etc/apparmor.d/profile-name
```

### SELinux Bypass Issues

#### Compatibility Problems
```bash
# Check system SELinux status
getenforce 2>/dev/null || echo "SELinux not available"

# Verify bypass configuration
cat /etc/selinux/config

# Check application logs for SELinux errors
journalctl | grep -i selinux
```

## Resources

### Documentation

- [AppArmor Documentation](https://wiki.ubuntu.com/AppArmor)
- [Debian AppArmor Package](https://packages.debian.org/apparmor)
- [AppArmor Security Profiles](https://gitlab.com/apparmor/apparmor-profiles)

### Community

- [AppArmor Mailing List](https://lists.ubuntu.com/mailman/listinfo/apparmor)
- [Debian Security Team](https://www.debian.org/security/)
- [Ubuntu AppArmor Team](https://launchpad.net/~apparmor)

---

**Status**: Implementation in Progress  
**Last Updated**: August 2025  
**Maintainer**: Debian Bootc Image Builder Team
