كتاب الإمارة
33  
The Book on Government
(16)
Chapter: The obligation to denounce rulers for that in which they go against Shari'ah, but they should not be fought so long as they pray regularly, etc
(16)
باب وُجُوبِ الإِنْكَارِ عَلَى الأُمَرَاءِ فِيمَا يُخَالِفُ الشَّرْعَ وَتَرْكِ قِتَالِهِمْ مَا صَلَّوْا وَنَحْوِ ذَلِكَ
Sahih Muslim 1854 c

Another version of the tradition narrated on the same authority attributes the same words to the Messenger of Allah (ﷺ) except that it replaces kariha with ankhara and vice versa.

وَحَدَّثَنِي أَبُو الرَّبِيعِ الْعَتَكِيُّ، حَدَّثَنَا حَمَّادٌ، - يَعْنِي ابْنَ زَيْدٍ - حَدَّثَنَا الْمُعَلَّى بْنُ، زِيَادٍ وَهِشَامٌ عَنِ الْحَسَنِ، عَنْ ضَبَّةَ بْنِ مِحْصَنٍ، عَنْ أُمِّ سَلَمَةَ، قَالَتْ قَالَ رَسُولُ اللَّهِ صلى الله عليه وسلم ‏.‏ بِنَحْوِ ذَلِكَ غَيْرَ أَنَّهُ قَالَ ‏ "‏ فَمَنْ أَنْكَرَ فَقَدْ بَرِئَ وَمَنْ كَرِهَ فَقَدْ سَلِمَ ‏"‏ ‏.‏
Reference : Sahih Muslim 1854c
In-book reference : Book 33, Hadith 99
USC-MSA web (English) reference : Book 20, Hadith 4571
  (deprecated numbering scheme)