203

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

KyleMit
  • 30,350
  • 66
  • 462
  • 664
XiaoFangyu
  • 2,031
  • 2
  • 4
  • 4
  • 4
    This is closely related to [Q1](https://stackoverflow.com/q/71855882/1256452) and [Q2](https://stackoverflow.com/q/71849415/1256452); see both questions and all the answers there. – torek Apr 17 '22 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 '22 at 12:40
  • Related (more Windows oriented): *[I cannot add the parent directory to safe.directory in Git](https://stackoverflow.com/questions/71849415/)* – Peter Mortensen Jun 04 '22 at 14:05
  • the bug is also reproduced on: Git version 2.36.1.windows.1; Windows 11(22H2 Build 22621.160) – Dmytro Kryvoruchenko Jun 19 '22 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 06 '22 at 10:04

26 Answers26

156

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
8ctopus
  • 2,617
  • 2
  • 18
  • 25
  • 12
    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) – Andrew Savinykh Jun 10 '22 at 07:48
  • 2
    On Windows add a full path to the folder like D:/Folder/SubFolder. It works for me. – Dmytro Kryvoruchenko Jun 19 '22 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 '22 at 09:46
  • I don't know, maybe you should consider asking the question on stackoverflow. – 8ctopus Aug 10 '22 at 11:12
146

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
night
  • 1,477
  • 1
  • 2
  • 3
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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Huber Thomas
  • 1,577
  • 1
  • 5
  • 7
  • 7
    This solution worked for me, because the repository folder was owned by a different user. – natenho Apr 23 '22 at 06:36
  • That fixed some of my local repos. They were owned by a user group. I did not need to change any git config. – tobster Apr 25 '22 at 08:02
  • 18
    This should be the defacto solution on Windows. – LunicLynx Apr 25 '22 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. – James John McGuire 'Jahmic' May 26 '22 at 07: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. – Rich Shealer May 26 '22 at 14:35
  • "C:\Users\" is dependent on the Windows version and in which context Windows is used. Perhaps generalise your answer to use the appropriate environment variable, etc.? – Peter Mortensen Jun 05 '22 at 09:29
  • A lead may or may not [be `%USERPROFILE%`](https://stackoverflow.com/questions/58754860/). – Peter Mortensen Jun 05 '22 at 10:10
  • 1
    "_Check the owner properties in the top area of the new opened window and adapt it_". Adapt it to what? I've changed the owner user to the current user I'm using on my Windows but it's still not fixed. Also my Git user is different from my Windows user and I don't have my git user on my Windows to own this repository to it. So this might be the reason why it's not working for me? This is really vague. – aderchox Jul 02 '22 at 05:01
  • 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 08 '22 at 03:13
  • This worked for me, but it could definitely do with more explanation of what to do after clicking "Change" in "Advanced Security Settings". I had to follow Tom H's instructions to figure it out. – Glenster Jul 13 '22 at 05:28
  • Out of all solutions that were suggested, this was the one who did the trick for me – Markus Sabin Jul 26 '22 at 07:17
  • This solution did work for me. Tried the first solution using Git bash, but it didn't work. thanks. – Aadil Aug 01 '22 at 12:46
  • this worked for me after moving my 2nd hard drive from my old computer – Ninja Dev Aug 21 '22 at 10:12
10

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).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tlbignerd
  • 1,104
  • 9
  • 21
  • 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. – David Guerra Jun 24 '22 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 '22 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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ayush
  • 457
  • 8
  • 16
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
urug99
  • 101
  • 3
7
sudo git config --system --add safe.directory /homerepon

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

Jerome Jaglale
  • 1,863
  • 18
  • 22
  • 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: https://github.com/klaussilveira/gitlist/issues/903 – XMAN Aug 14 '22 at 07: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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 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 – Timothy C. Lethbridge May 06 '22 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dregad
  • 1,150
  • 8
  • 21
  • 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 '22 at 07:35
4

You can simply open Git bash and enter the following command

git config --global --add safe.directory '*'
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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Debbie V
  • 314
  • 3
  • 5
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"
KJH
  • 2,382
  • 16
  • 26
Pasha
  • 51
  • 4
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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Phreditor
  • 469
  • 4
  • 4
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)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PJ127
  • 986
  • 13
  • 23
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rex Bengil
  • 60
  • 3
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])
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mirekphd
  • 4,799
  • 3
  • 38
  • 59
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Leoalv
  • 25
  • 8
0
sudo chown -R [username]:[group directory]

That really works for me (MacBook Air M1).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mehmetakkus
  • 631
  • 1
  • 8
  • 25
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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Dennis
  • 11
  • 2
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.

TheFixer
  • 89
  • 1
  • 2
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

Prakash
  • 19
  • 4
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
Yaroslav
  • 486
  • 1
  • 4
  • 14
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.

Mihai Drebot
  • 434
  • 4
  • 5
-1

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