Skip to content

Race condition with chmod when creating master.key file #48135

@hannob

Description

@hannob

The file railties/lib/rails/generators/rails/encryption_key_file/encryption_key_file_generator.rb contains this code:

      def add_key_file_silently(key_path, key = nil)
        create_file key_path, key || ActiveSupport::EncryptedFile.generate_key
        key_path.chmod 0600
      end

This code is used to create the master.key file. This is insecure, as it first creates the file with the key world readable and only afterwards changes the permissions.

An unprivileged user on the same system may exploit this to read the master.key during creation. I have created a proof of concept to attack such vulnerabilities, which can be found here: https://github.com/hannob/fpracer

To exploit / illustrate the issue:

  • As one user run something like:
    ./fpracer /tmp/test/blog/config/master.key
    
  • As another user run:
    mkdir /tmp/test
    cd /tmp/test
    rails new blog
    

The fpracer script will output the content of the newly generated master.key.

Exploiting this requires a user account on the same system and knowledge by the attacker about the directory structure, and read access to the upper directory. So there are a few conditions needed for this to be exploitable, which reduces impact. Anyway, this is still obviously not right and should be fixed.

I originally reported this via Hackerone, but was asked to put it on the public issue tracker. I had a first patch using chmod, but that is, as I learned, problematic, as it would affect the whole process, potentially interferring with other threads.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions