Yoreh Deah Siman 267 Seif 67
סז עֶבֶד שֶׁנִּשְׁבָּה, אִם נִתְיָאֵשׁ מִמֶּנּוּ רַבּוֹ רִאשׁוֹן, כָּל הַפּוֹדֶה אוֹתוֹ לְשֵׁם עֶבֶד יִשְׁתַּעְבֵּד בּוֹ וַהֲרֵי הוּא שֶׁלּוֹ, וְאִם פָּדָהוּ לְשֵׁם בֶּן חוֹרִין, הֲרֵי זֶה בֶּן חוֹרִין. וְאִם לֹא נִתְיָאֵשׁ מִמֶּנּוּ רַבּוֹ רִאשׁוֹן, הַפּוֹדֶה אוֹתוֹ לְשֵׁם עֶבֶד נוֹטֵל פִּדְיוֹנוֹ מֵרַבּוֹ וְחוֹזֵר לְרַבּוֹ, וְאִם פָּדָהוּ לְשֵׁם בֶּן חוֹרִין, חוֹזֵר לְרַבּוֹ רִאשׁוֹן בְּלֹא כְּלוּם.
A slave that is captured and his first master despaired of regaining ownership of him, anyone who redeems him with the intent that he remain a slave may subjugate him, and he becomes his property. If he redeemed him with the intent that he become free, he is granted his freedom.
If the slave’s first owner did not despair of regaining ownership, one who redeems the slave with the intent that he remain a slave should take back the money he spent to redeem him from his owner, and the slave is returned to his original owner. If he redeemed him with the intent of freeing him, he is returned to his original owner without any owing anything.