Four human rights groups had argued that it was against British law and the European Convention on Human Rights for the MI5 domestic spy agency to permit agents, those who are informants or provide intelligence but do not work directly for the government, to commit crimes including murder and torture.
In its submissions, the government said it would be impossible for MI5 to operate, gather intelligence and prevent terrorist attacks without using agents and it was necessary for agents to be allowed to be involved in criminality.
However, it said that did not give them immunity from prosecution.
The Investigatory Powers Tribunal (IPT), which deals with complaints about the intelligence services, backed that view, making reference to recent deadly attacks by militants. However, two of its five members disagreed with the decision.
"This case raises one of the most profound issues which can face a democratic society governed by the rule of law," the IPT said in its ruling.
"The events of recent years, for example in Manchester and London in 2017, serve vividly to underline the need for such intelligence-gathering and other activities in order to protect the public from serious terrorist threats."
Privacy International, Reprieve, the Committee on the Administration of Justice and the Pat Finucane Centre said the once-secret MI5 policy had been in operation at least since the early 1990s and had only come to light when former Prime Minister Theresa May acknowledged its existence in 2018.
They referred to a 2012 report into the murder of Irish lawyer Pat Finucane at his home in Belfast in 1989 which concluded it was carried out by pro-British militants in collusion with the security forces.
The report found that Finucane would not have been murdered without the involvement of state actors.
"Today, the Investigatory Powers Tribunal decided that MI5 can secretly give informants permission to commit grave crimes in the UK, including violence," said Ilia Siatitsa, Legal Officer for Privacy International.
Maya Foa, Reprieve’s Director, said the "knife-edge judgment" showed how dubious the policy was. The civil rights groups said they would seek permission to appeal against the ruling.
While the IPT upheld the lawfulness of the policy, it said it did not give carte blanche to MI5.
"It is important to appreciate that this does not mean that it has any power to confer immunity from liability under either the criminal law or the civil law ... on either its own officers or on agents handled by them," the IPT said.