Habeas corpus is the legal remedy that allows an individual to challenge the legality of their detention or imprisonment.