But when I try to push to master I get
fatal: You are not currently on a branch.
To push the history leading to the current (detached HEAD)
Which is to be expected
Working in a detached state is not to be expected, unless you deliberately want to be doing this, which I doubt is the case for you. Instead of checking out commit #5, you should have either reverted the master branch to that commit, or do a git rebase in interactive mode where you can rehash the commits as you want.
That being said, if you are certain that the version of master in the detached state is what you really want to keep, then you can get around the non-fast-forward error, by force pushing the branch to the remote:
git push origin HEAD:master --force
However, if you force push you run the risk of causing problems for all other users who have that branch checked out. A less risky solution would be to create a temporary branch from the detached HEAD, and then merge that branch into master:
git branch temp-branch
git checkout master
git merge temp-branch
git push origin master