204

I found an error log from Apache 2 that is fatal:

unsafe repository ('/home/repon' is owned by someone else)

It happens because I have git rev-parse --symbolic-full-name --abbrev-ref HEAD' in PHP code, and it looks like the new Git safety change no longer allows www-data to run this Git command.

Running the following command does not work:

git config --global --add safe.directory /homerepon

Is there a workaround to solve this issue?

Git version: 2.35.3
PHP version: 7.4
Apache2 version: 2.4.41

5
  • 4
    This is closely related to Q1 and Q2; see both questions and all the answers there.
    – torek
    Apr 17, 2022 at 12:34
  • Also for an educated decision, read the URL you referenced in your question and study the git documentation for the parts it references. You're just having a configuration issue due to recently introduced constraints to not easily get trapped in a security issue.
    – hakre
    Apr 17, 2022 at 12:40
  • Related (more Windows oriented): I cannot add the parent directory to safe.directory in Git Jun 4, 2022 at 14:05
  • the bug is also reproduced on: Git version 2.36.1.windows.1; Windows 11(22H2 Build 22621.160) Jun 19, 2022 at 10:29
  • Possibly related to running Visual Studio with LOCAL ADMIN RIGHTS? I found that this error resulted when selecting to run Visual Studio 2019 and open my solution by right-clicking on the Visual Studio icon in Taskbar and selecting the solution (from the recently opened list that appears). On the other hand, if I first opened VS2019 (running as Local Admin - my default) and selected my solution from the splash-screen's "Open Recent"/"Pinned", everything was fine - and git was recognised and VS connected to the repository.
    – Jonno
    Jul 6, 2022 at 10:04

26 Answers 26

157

This started appearing with the release of the Git 2.35.2 security update which fixes vulnerabilities described here. Credits @Juan-Kabbali

Here are four possible solutions:

  • trust the Git directory (do it if you know the directory contents are safe)
git config --global --add safe.directory /home/repon

This adds the safe group to file ~/.gitconfig as shown in this example:

[safe]
    directory = /home/repon
  • run the command as the correct user, for example:
sudo -u ubuntu -- git status

Note: This requires user www-data to have permission to execute the Git command as user ubuntu (assuming ubuntu is the repository owner). For this to work, you will need to add a new file inside /etc/sudoers.d/ with the following contents:

www-data ALL=(ubuntu) NOPASSWD: /usr/bin/git

This may have security implications, so refer to your security person first.

  • change the Git repository owner to www-data
sudo chown -R www-data:www-data /home/repon
  • downgrade Git as a temporary solution. For example, in Ubuntu:
apt install git-man=1:2.17.0-1ubuntu1 git=1:2.17.0-1ubuntu1

Note: At least on Windows, it appears that all Git repositories on ejectable drives are considered unsafe and changing the ownership does not seem to work.

4
  • 13
    This is a pretty bad error message. I wish it would tell me both, who this is owned and who git think it should be owned. Right now it seems that this is outright a bug, because as far as I can see the message is wrong, it is not owned by someone else. (windows) Jun 10, 2022 at 7:48
  • 2
    On Windows add a full path to the folder like D:/Folder/SubFolder. It works for me. Jun 19, 2022 at 10:26
  • All the solutions dont work for me. I'm working on a Windows machine, all my files are on a diskstation. I'm adding a folder fromt the DS as a drive to windows. I cant change the ownership of the files, because they belong to the DS Users. I've added the save.directory all over the place, no result. All my repos have the same issue, local or github
    – DBR
    Aug 10, 2022 at 9:46
  • I don't know, maybe you should consider asking the question on stackoverflow.
    – 8ctopus
    Aug 10, 2022 at 11:12
149

This is because of the Git safe update.

To make Git trust any directory you can run this in PowerShell:

git config --global --add safe.directory *

In Bash, you should escape the * to avoid expansion:

git config --global --add safe.directory '*'

Support for * was only added in Git 2.36 as mentioned at: Highlights from Git 2.36 and by genonymous in the comments.

If you just trust one directory, you can run this command

git config --global --add safe.directory your-directory
5
  • 4
    it's because CVE-2022-24765 secutiry vulnerability Apr 20, 2022 at 13:38
  • 2
    This would make sense since this is what git itself says to do, but running the command gives an error: error: wrong number of arguments, should be 2 Apr 20, 2022 at 17:26
  • @StevenGann Make sure you are providing the directory argument at the end.
    – genonymous
    Apr 20, 2022 at 19:10
  • @StevenGann Also, * is supported from Git 2.36, so you might need to update it.
    – genonymous
    Apr 20, 2022 at 19:33
  • 2
    What do you mean by "the Git safe update"? May 12, 2022 at 15:44
114

For Windows I had to do the following:

  1. Right click on the Git repository folder on which the error occurs and select Properties

  2. Select the security tab, and then choose "Advanced" (left picture: press "Erweitert")

  3. Check the owner properties (right picture: "Besitzer") in the top area of the new opened window and adapt it (right picture: press "Ändern"). This must be your working Windows account

  4. Press OK and wait until rights have been set, and then the Git error message should be history

    Enter image description here

This solution also works if you move or rename the directory afterwards. In my opinion you should prefer this solution over

git config --global --add safe.directory <repo-path>

which you have to do each time where you perform changes on the directory name. You can also manually adapt the .gitconfig file in

C:\Users\<username>\.gitconfig

once you added to the safe list.

13
  • 7
    This solution worked for me, because the repository folder was owned by a different user.
    – natenho
    Apr 23, 2022 at 6:36
  • 18
    This should be the defacto solution on Windows.
    – LunicLynx
    Apr 25, 2022 at 10:15
  • 4
    While this works, this is less than ideal. For me, these repos were owned by Administrators, not m specific account (but which is an Administrator). Furthermore, I am the only real user on this PC. I have close to a hundred repos, changing each manually will be very tedious. May 26, 2022 at 7:08
  • 4
    In my case folders that had been restored in 2021 after reformatting and reinstalling Windows did not belong to my user account anymore. Apparently checking ownership is a new feature of GIT stating with version 2.35.2.windows.1. Projects created since the restore continued to work normally. Reclaiming ownership of the top level of the project folders and including "subcontainers and objects" took care of it.. It took a minute or two to process, but it was just one time. May 26, 2022 at 14:35
  • 2
    To expand on this, it seems I ran git init in an admin terminal, which set the owner of everything in and including the .git folder to the administrator user. In the second window you show, I clicked the 'Change' button, 'Advanced' on the bottom left to open up user search, 'Find now' on the right to populate the list, then selected the account that matches the user of a fresh .git folder made with a non-admin terminal. I ticked the new option that appears to apply it to all subcontainers and objects and git stopped complaining.
    – Tom
    Jul 8, 2022 at 3:13
11

Alongside Huber Thomas's answer for Windows, I had to use PowerShell or CMD since I had a bunch of files in a source control management folder I'd moved from one location to another. The TAKEOWN command handled this well (if a little slowly).

  1. Open CMD as yourself (you don't need to be an administrator)
  2. Navigate to the repository folder (or parent if you have multiple)
  3. Run takeown /f . /r /d Y

This will recursively work through all folders in your current folder and set the ownership to the logged-in user (presumably you).

2
  • 1
    I needed to run CMD as an administrator in order for this to work. I think this was due to the fact that some of my repos were owned by the local administrators group for some reason. No idea why this was the case as I created all of my repos with the same user which is the only account on the machine. Jun 24, 2022 at 15:56
  • On Windows 10, it worked fine. I appreciate it. It is possible, however, that it may conflict with the terms and configurations of Git?
    – QMaster
    Aug 21, 2022 at 17:28
8

None of the solutions in previous answers worked for me, but changing the ownership of the repository did. I'm running Ubuntu 20.04.4 (Focal Fossa) LTS and I ran the following command:

sudo chown -R username:group directory
0
7

As a part of automation, our scenario involved invoking one script multiple times and we didn't know the workspace upfront.

So, in our case, git config --global --add safe.directory * created multiple entries in ~/.gitconfig.

git config --global --replace-all safe.directory '*' helped us ensuring no duplicate entries.

7
sudo git config --system --add safe.directory /homerepon

--system marks the repository as safe for all users, including www-data.

1
  • 1
    This worked for me using for gitlist on OpenSuse (which runs apache as user wwwrun). Tried every suggestion mentioned in other answers with no luck. Found this suggestion here as well: github.com/klaussilveira/gitlist/issues/903
    – XMAN
    Aug 14, 2022 at 7:34
4

I had a similar issue - a web application that used Git could not access the repository.

Running the suggested command (git config --global --add safe.directory /repo/path) didn't work either, because I ran it as 'me', not as the 'www-data' user.

The solution was in fact really simple - I created the .gitconfig file in the /var/www directory (which is home for www-data user in my case) and put

[safe]
        directory = /repo/path

there.

1
  • 1
    This should be the definitive answer for people running nginx on ubuntu. Note you should also ensure the ownership of the /var/www/.gitconfig is www-data by doing sudo chown www-data .gitconfig May 6, 2022 at 15:20
4

I may be stating the obvious, but I think it's worth mentioning that running git config --global --add safe.directory /home/repon needs to done for the www-data user.

Problem 1: www-data's HOME directory is /var/www, so having a .gitconfig file there may be a security risk (divulging server paths and configurations).

Problem 2: with Apache/Ubuntu 20.04 (Focal Fossa), the HOME environment variable is not defined by default (/etc/apache2/envvars unsets it), so the configuration is not getting picked-up (git config --global fails with fatal: $HOME not set).

I managed to fix the problem by adding the repository to Git's system configuration, i.e., git config --system --add safe.directory /home/repon.

1
  • This worked for me using for gitlist on OpenSuse (which runs apache as user wwwrun). Tried every suggestion mentioned in other answers with no luck. Found this suggestion here as well: github.com/klaussilveira/gitlist/issues/903
    – XMAN
    Aug 14, 2022 at 7:35
4

You can simply open Git bash and enter the following command

git config --global --add safe.directory '*'
2

In addition to the accepted answer, for those who are getting "error: wrong number of arguments, should be 2" under Windows, use double quotation marks instead of single quotes when providing the directory argument.

e.g.:

git config --global --add safe.directory "D:/Source/Repos/SampleProject"
2

Changing the owner of the top level directory fixed it.

Running Laravel on a local Ubuntu LAMP stack, my setup includes the command:

sudo chown -R www-data /var/www/dirname

But with www-data owning the dirname, Git gave the above error. To fix it, I only had to change the owner of the top level dirname, and the .git directory:

sudo chown myUserName /var/www/dirname

sudo chown -R myUserName /var/www/dirname/.git

2

Adding to the gitconfig worked, but who wants to do that seemingly to every directory?! Craziness!

For me, the answer is: → Don't use sudo!

For many cases, using sudo doesn't hurt, and it can be habitual if you are moving between things your user can touch, and things needing more access.

If my user created a repository and then I used "sudo git...", I got the error. I also had the "sudo git..." part in an alias, so it wasn't obvious that I was even using it.

1

I tried all the answers above but was still getting the error. Though the answers and steps were correct it didn't work for me on Windows Subsystem for Linux (WSL) with PyCharm.

So I put aside the WSL and PyCharm terminal to run the command in my Windows PowerShell. I navigated to the location of the .gitconfig folder which was \\wsl$\Ubuntu-20.04\home\user> and then typed .gitconfig to open it any my default text editor which is Visual Studio Code.

I updated the directory path as below without the quotes:

directory = %(prefix)///wsl$/Ubuntu-20.04/home/user/project/mysite

You can equally set the directory to * to mark all folders as safe. After that, I invalidated caches from PyCharm, and voila! no more errors.

Hope it helps someone.

0

I had a similar problem, with Phabricator not being able to display the content of my repositories (git log failed because of the same reason as yours).

I could not figure out which user was running the git command, so I could not come up with a proper solution, until I realized I could edit/create a global Git configuration file for all users.

I created the file with:

sudo vi /etc/gitconfig`

and put this inside:

[safe]
        directory = /home/opt/phabricator_repo/1
        directory = /home/opt/phabricator_repo/4
        directory = /home/opt/phabricator_repo/5

OS: Ubuntu 20.04 (Focal Fossa)

0

This happens if you have a different user who owned the directory. For example, your Git repository is located in /var/www which is owned by www-data. Now, when you are signed-in/using a non-sudo user account and you go to /var/www to perform Git actions such as

git branch

you will get this error, so make sure you have appropriate directory permission. You can change the directory ownership by running chown or add your current user to the group to which the directory owner belongs to.

0

If you are on Linux and prefer explicit allowlisting, you may achieve it manually by editing the Git configuration, (e.g., using nano or Vim). Just put the folders allowlist into the [safe] section of the configuration file:

nano ~/.gitconfig

And here is a Python script to prepare the allow-list:

from glob import glob

def println(my_list):
    print("\n".join(map(str, my_list)))

git_folders_list = sorted(glob("~/git/*", recursive=True))

println(["directory = " + d for d in git_folders_list])
0

I had this problem on Windows with Sublime Text Merge. I was trying to apply some solutions mentioned here, and they didn't work so I said:

if the problem is with the folder I must create a new one, so copy and paste the project folder, delete the old one, rename the copy by the old name and that was it!

I guess this should work on Linux too and when making the copy of the project folder it is created with the correct owner.

0
sudo chown -R [username]:[group directory]

That really works for me (MacBook Air M1).

0

As well as receiving the error/warning messages above, the issue was that the results of the exec() commands were not being furnished BECAUSE of the error warnings....[add 2>&1 to the end to see the errors]

These steps below fixed it for me: I added a config file to /etc, set it's permissions and added the safe directory to it....

touch /etc/gitconfig 
chown www-data:www-data /etc/gitconfig 
nano /etc/gitconfig

Content of the config file

[safe] 
      directory = /var/www/YOURPATH

That solved it....the original code could work

0

If you are running from a jenkinsfile declarative pipeline use below line in starting of the stage,

sh(label: 'Git config safedir', script: "git config --global --add safe.directory ${env.WORKSPACE}", returnStdout: true)?.trim()

env.WORKSPACE is the workspace dir where git checkout happening , avoid using .* for directory.

0

I got the same issue as mentioned in the question and below as well:

Error: fatal: unsafe repository (repository is owned by someone else) To add an exception for this directory, call:

git config --global --add safe.directory repo

But adding a repo as safe directory did not work in ubuntu 18.04

0

Tacking on to this answer with regards to Sourcetree in windows, I had to run takeown as admin from the command line.

I also needed to check the ownership of all the files and folders in my repo folder with DIR /Q to be sure I was changing to ownership to the right user.

I was checking by cloning a remote repo and checking ownership and permissions of that repo vs other repos that I had copied across from a dying PC, and while the security tab in Windows Explorer seemed to show that everything matched up, DIR /Q showed me that the repos I was not able to open had different ownership than the one I had cloned and could access.

0
0

All of the above solutions give me next error:

could not lock config file */etc/gitconfig: Permission denied

Solved with this solution: https://dirask.com/posts/Git-git-config-error-could-not-lock-config-file-Permission-denied-Kj825D

Follow the next step by step:

  • Open Git Bash as administrator
  • Go to your project directory: cd "C:\path\to\our\project\name"

Execute command:

git config --system --unset credential.helper

On linux run this command with sudo command:

sudo git config --system --unset credential.helper
0

In my case, I could not change the folder ownership, and the git config --global --add safe.directory didn't fix it. The issue turned out to be that the folder was created from console running as administrator (win 10) and git was running with regular user credentials. I just backed up the folder contents, deleted it and recreated it without running as administrator.

-1

This marks all directories as safe git config --global --add safe.directory *

1
  • What does this answer add to the already existing answers?
    – MrTux
    Dec 27, 2022 at 9:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.