]> git.sesse.net Git - vlc/blob - plugins/dvd/dvd_css.c
* XVideo window now has a black background, thanks to Shane Harper.
[vlc] / plugins / dvd / dvd_css.c
1 /*****************************************************************************
2  * dvd_css.c: Functions for DVD authentification and unscrambling
3  *****************************************************************************
4  * Copyright (C) 1999-2001 VideoLAN
5  * $Id: dvd_css.c,v 1.22 2001/04/08 16:57:47 sam Exp $
6  *
7  * Author: Stéphane Borel <stef@via.ecp.fr>
8  *
9  * based on:
10  *  - css-auth by Derek Fawcus <derek@spider.com>
11  *  - DVD CSS ioctls example program by Andrew T. Veliath <andrewtv@usa.net>
12  *  - The Divide and conquer attack by Frank A. Stevenson <frank@funcom.com>
13  *  - DeCSSPlus by Ethan Hawke
14  *  - DecVOB
15  *  see http://www.lemuria.org/DeCSS/ by Tom Vogt for more information.
16  * 
17  * This program is free software; you can redistribute it and/or modify
18  * it under the terms of the GNU General Public License as published by
19  * the Free Software Foundation; either version 2 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU General Public License for more details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with this program; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
30  *****************************************************************************/
31
32 /*****************************************************************************
33  * Preamble
34  *****************************************************************************/
35 #include "defs.h"
36
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <unistd.h>
40 #include <string.h>
41
42 #include "common.h"
43
44 #include "intf_msg.h"
45
46 #include "dvd_css.h"
47 #ifdef HAVE_CSS
48 #include "dvd_csstables.h"
49 #endif /* HAVE_CSS */
50 #include "dvd_ioctl.h"
51 #include "dvd_ifo.h"
52
53 #include "input_dvd.h"
54
55 /*****************************************************************************
56  * Local prototypes
57  *****************************************************************************/
58 #ifdef HAVE_CSS
59 static int  CSSGetASF    ( css_t *p_css );
60 static void CSSCryptKey  ( int i_key_type, int i_varient,
61                            u8 const * pi_challenge, u8* pi_key );
62 static int  CSSCracker   ( int i_start, unsigned char * p_crypted,
63                            unsigned char * p_decrypted,
64                            dvd_key_t * p_sector_key, dvd_key_t * p_key );
65 #endif /* HAVE_CSS */
66
67 /*****************************************************************************
68  * CSSTest : check if the disc is encrypted or not
69  *****************************************************************************/
70 int CSSTest( int i_fd )
71 {
72     int i_ret, i_copyright;
73
74     i_ret = ioctl_ReadCopyright( i_fd, 0 /* i_layer */, &i_copyright );
75
76     if( i_ret < 0 )
77     {
78         /* Since it's the first ioctl we try to issue, we add a notice */
79         intf_ErrMsg( "css error: ioctl_ReadCopyright failed, "
80                      "make sure DVD ioctls were compiled in" );
81
82         return i_ret;
83     }
84
85     return i_copyright;
86 }
87
88 /*****************************************************************************
89  * CSSInit : CSS Structure initialisation and DVD authentication.
90  *****************************************************************************
91  * It simulates the mutual authentication between logical unit and host.
92  * Since we don't need the disc key to find the title key, we just run the
93  * basic unavoidable commands to authenticate device and disc.
94  *****************************************************************************/
95 int CSSInit( css_t * p_css )
96 {
97 #ifdef HAVE_CSS
98     /* structures defined in cdrom.h or dvdio.h */
99     char p_buffer[2048 + 4 + 1];
100     int  i_ret = -1;
101     int  i;
102
103     p_css->i_agid = 0;
104
105     /* Test authentication success */
106     switch( CSSGetASF( p_css ) )
107     {
108         case -1:
109             return -1;
110
111         case 1:
112             intf_WarnMsg( 3, "css info: already authenticated" );
113             return 0;
114
115         case 0:
116             intf_WarnMsg( 3, "css info: need to authenticate" );
117     }
118
119     /* Init sequence, request AGID */
120     for( i = 1; i < 4 ; ++i )
121     {
122         intf_WarnMsg( 3, "css info: requesting AGID %d", i );
123
124         i_ret = ioctl_LUSendAgid( p_css );
125
126         if( i_ret != -1 )
127         {
128             /* No error during ioctl: we know the device is authenticated */
129             break;
130         }
131
132         intf_ErrMsg( "css error: ioctl_LUSendAgid failed, invalidating" );
133
134         p_css->i_agid = 0;
135         ioctl_InvalidateAgid( p_css );
136     }
137
138     /* Unable to authenticate without AGID */
139     if( i_ret == -1 )
140     {
141         intf_ErrMsg( "css error: ioctl_LUSendAgid failed, fatal" );
142         return -1;
143     }
144
145     for( i = 0 ; i < 10; ++i )
146     {
147         p_css->disc.pi_challenge[i] = i;
148     }
149
150     /* Get challenge from host */
151     for( i = 0 ; i < 10 ; ++i )
152     {
153         p_buffer[9-i] = p_css->disc.pi_challenge[i];
154     }
155
156     /* Send challenge to LU */
157     if( ioctl_HostSendChallenge( p_css, p_buffer ) < 0 )
158     {
159         intf_ErrMsg( "css error: ioctl_HostSendChallenge failed" );
160         return -1;
161     }
162
163     /* Get key1 from LU */
164     if( ioctl_LUSendKey1( p_css, p_buffer ) < 0)
165     {
166         intf_ErrMsg( "css error: ioctl_LUSendKey1 failed" );
167         return -1;
168     }
169
170     /* Send key1 to host */
171     for( i = 0 ; i < KEY_SIZE ; i++ )
172     {
173         p_css->disc.pi_key1[i] = p_buffer[4-i];
174     }
175
176     for( i = 0 ; i < 32 ; ++i )
177     {
178         CSSCryptKey( 0, i, p_css->disc.pi_challenge,
179                            p_css->disc.pi_key_check );
180
181         if( memcmp( p_css->disc.pi_key_check,
182                     p_css->disc.pi_key1, KEY_SIZE ) == 0 )
183         {
184             intf_WarnMsg( 3, "css info: drive authentic, using variant %d", i);
185             p_css->disc.i_varient = i;
186             break;
187         }
188     }
189
190     if( i == 32 )
191     {
192         intf_ErrMsg( "css error: drive would not authenticate" );
193         return -1;
194     }
195
196     /* Get challenge from LU */
197     if( ioctl_LUSendChallenge( p_css, p_buffer ) < 0 )
198     {
199         intf_ErrMsg( "css error: ioctl_LUSendKeyChallenge failed" );
200         return -1;
201     }
202
203     /* Send challenge to host */
204     for( i = 0 ; i < 10 ; ++i )
205     {
206         p_css->disc.pi_challenge[i] = p_buffer[9-i];
207     }
208
209     CSSCryptKey( 1, p_css->disc.i_varient, p_css->disc.pi_challenge,
210                                                p_css->disc.pi_key2 );
211
212     /* Get key2 from host */
213     for( i = 0 ; i < KEY_SIZE ; ++i )
214     {
215         p_buffer[4-i] = p_css->disc.pi_key2[i];
216     }
217
218     /* Send key2 to LU */
219     if( ioctl_HostSendKey2( p_css, p_buffer ) < 0 )
220     {
221         intf_ErrMsg( "css error: ioctl_HostSendKey2 failed" );
222         return -1;
223     }
224
225     intf_WarnMsg( 3, "css info: authentication established" );
226
227     memcpy( p_css->disc.pi_challenge, p_css->disc.pi_key1, KEY_SIZE );
228     memcpy( p_css->disc.pi_challenge+KEY_SIZE, p_css->disc.pi_key2, KEY_SIZE );
229     CSSCryptKey( 2, p_css->disc.i_varient, p_css->disc.pi_challenge,
230                                                p_css->disc.pi_key_check );
231
232     intf_WarnMsg( 1, "css info: received Session Key" );
233
234     if( p_css->i_agid < 0 )
235     {
236         return -1;
237     }
238
239     /* Test authentication success */
240     switch( CSSGetASF( p_css ) )
241     {
242         case -1:
243             return -1;
244
245         case 1:
246             intf_WarnMsg( 3, "css info: already authenticated" );
247             return 0;
248
249         case 0:
250             intf_WarnMsg( 3, "css info: need to get disc key" );
251     }
252
253     /* Get encrypted disc key */
254     if( ioctl_ReadKey( p_css, p_buffer ) < 0 )
255     {
256         intf_ErrMsg( "css error: ioctl_ReadKey failed" );
257         return -1;
258     }
259
260     /* Unencrypt disc key using bus key */
261     for( i = 0 ; i < 2048 ; i++ )
262     {
263         p_buffer[ i ] ^= p_css->disc.pi_key_check[ 4 - (i % KEY_SIZE) ];
264     }
265     memcpy( p_css->disc.pi_key_check, p_buffer, 2048 );
266
267     /* Test authentication success */
268     switch( CSSGetASF( p_css ) )
269     {
270         case -1:
271             return -1;
272
273         case 1:
274             intf_WarnMsg( 3, "css info: successfully authenticated" );
275             return 0;
276
277         case 0:
278             intf_WarnMsg( 3, "css info: no way to authenticate" );
279     }
280
281 #else /* HAVE_CSS */
282     intf_ErrMsg( "css error: CSS decryption is disabled in this module" );
283
284 #endif /* HAVE_CSS */
285     return -1;
286
287 }
288
289 /*****************************************************************************
290  * CSSGetKey : get title key.
291  *****************************************************************************
292  * The DVD should have been opened and authenticated before.
293  *****************************************************************************/
294 int CSSGetKey( css_t * p_css )
295 {
296 #ifdef HAVE_CSS
297     /*
298      * Title key cracking method from Ethan Hawke,
299      * with Frank A. Stevenson algorithm.
300      * Does not use any player key table and ioctls.
301      */
302     u8          pi_buf[0x800];
303     dvd_key_t   pi_key;
304     title_key_t p_title_key[10];
305     off_t       i_pos;
306     boolean_t   b_encrypted;
307     boolean_t   b_stop_scanning;
308     int         i_title;
309     int         i_bytes_read;
310     int         i_best_plen;
311     int         i_best_p;
312     int         i_registered_keys;
313     int         i_total_keys_found;
314     int         i_highest;
315     int         i,j,k;
316
317     memset( p_title_key, 0, 10 );
318     memset( &pi_key, 0, 10 );
319     b_encrypted = 0;
320     b_stop_scanning = 0;
321     i_registered_keys = 0 ;
322     i_total_keys_found = 0 ;
323     i_highest = 0;
324
325     /* Position of the title on the disc */
326     i_title = p_css->i_title;
327     i_pos = p_css->i_title_pos;
328
329 //fprintf( stderr, "CSS %d start pos: %lld\n", i_title, i_pos );
330
331     do {
332     i_pos = lseek( p_css->i_fd, i_pos, SEEK_SET );
333     i_bytes_read = read( p_css->i_fd, pi_buf, 0x800 );
334
335     /* PES_scrambling_control */
336     if( pi_buf[0x14] & 0x30 )
337     {
338         b_encrypted = 1;
339         i_best_plen = 0;
340         i_best_p = 0;
341
342         for( i = 2 ; i < 0x30 ; i++ )
343         {
344             for( j = i ; ( j < 0x80 ) &&
345                    ( pi_buf[0x7F - (j%i)] == pi_buf[0x7F-j] ) ; j++ );
346             {
347                 if( ( j > i_best_plen ) && ( j > i ) )
348                 {
349                     i_best_plen = j;
350                     i_best_p = i;
351                 }
352             }
353         }
354
355         if( ( i_best_plen > 20 ) && ( i_best_plen / i_best_p >= 2) )
356         {
357             i = CSSCracker( 0,  &pi_buf[0x80],
358                     &pi_buf[0x80 - ( i_best_plen / i_best_p) *i_best_p],
359                     (dvd_key_t*)&pi_buf[0x54],
360                     &pi_key );
361             while( i>=0 )
362             {
363                 k = 0;
364                 for( j=0 ; j<i_registered_keys ; j++ )
365                 {
366                     if( memcmp( &(p_title_key[j].pi_key),
367                                 &pi_key, sizeof(dvd_key_t) ) == 0 )
368                     {
369                         p_title_key[j].i_occ++;
370                         i_total_keys_found++;
371                         k = 1;
372                     }
373                 }
374
375                 if( k == 0 )
376                 {
377                     memcpy( &(p_title_key[i_registered_keys].pi_key),
378                                             &pi_key, sizeof(dvd_key_t) );
379                     p_title_key[i_registered_keys++].i_occ = 1;
380                     i_total_keys_found++;
381                 }
382                 i = CSSCracker( i, &pi_buf[0x80],
383                     &pi_buf[0x80 - ( i_best_plen / i_best_p) *i_best_p],
384                     (dvd_key_t*)&pi_buf[0x54], &pi_key);
385             }
386
387             /* Stop search if we find one occurence of the key 
388              * I have never found a DVD for which it is not enough
389              * but we should take care of that */
390             if( i_registered_keys == 1 && p_title_key[0].i_occ >= 1 )
391             {
392                 b_stop_scanning = 1;
393             }
394         }
395     }
396
397     i_pos += i_bytes_read;
398     } while( i_bytes_read == 0x800 && !b_stop_scanning);
399
400     if( b_stop_scanning)
401     {
402         intf_WarnMsg( 1,
403             "css info: found enough occurencies of the same key." );
404     }
405
406     if( !b_encrypted )
407     {
408         intf_WarnMsg( 3, "css warning: this file was _NOT_ encrypted!" );
409         return(0);
410     }
411
412     if( b_encrypted && i_registered_keys == 0 )
413     {
414         intf_ErrMsg( "css error: unable to determine keys from file" );
415         return(1);
416     }
417
418     for( i = 0 ; i < i_registered_keys - 1 ; i++ )
419     {
420         for( j = i + 1 ; j < i_registered_keys ; j++ )
421         {
422             if( p_title_key[j].i_occ > p_title_key[i].i_occ )
423             {
424                 memcpy( &pi_key, &(p_title_key[j].pi_key), sizeof(dvd_key_t) );
425                 k = p_title_key[j].i_occ;
426
427                 memcpy( &(p_title_key[j].pi_key),
428                         &(p_title_key[i].pi_key), sizeof(dvd_key_t) );
429                 p_title_key[j].i_occ = p_title_key[i].i_occ;
430
431                 memcpy( &(p_title_key[i].pi_key),&pi_key, sizeof(dvd_key_t) );
432                 p_title_key[i].i_occ = k;
433             }
434         }
435     }
436
437 #ifdef STATS
438     intf_WarnMsg( 1, "css info: key(s) & key probability" );
439     intf_WarnMsg( 1, "----------------------------------" );
440 #endif
441     for( i=0 ; i<i_registered_keys ; i++ )
442     {
443 #ifdef STATS
444         intf_WarnMsg( 1, "%d) %02X %02X %02X %02X %02X - %3.2f%%", i,
445                       p_title_key[i].pi_key[0], p_title_key[i].pi_key[1],
446                       p_title_key[i].pi_key[2], p_title_key[i].pi_key[3],
447                       p_title_key[i].pi_key[4],
448                       p_title_key[i].i_occ * 100.0 / i_total_keys_found );
449 #endif
450         if( p_title_key[i_highest].i_occ * 100.0 / i_total_keys_found
451                            <= p_title_key[i].i_occ*100.0 / i_total_keys_found )
452         {
453             i_highest = i;
454         }
455     }
456
457
458     /* The "find the key with the highest probability" code
459      * is untested, as I haven't been able to find a VOB that
460      * produces multiple keys (RT)
461      */
462     intf_WarnMsg( 3, "css info: title %d, key %02X %02X %02X %02X %02X",
463                   i_title, p_title_key[i_highest].pi_key[0],
464                            p_title_key[i_highest].pi_key[1],
465                            p_title_key[i_highest].pi_key[2],
466                            p_title_key[i_highest].pi_key[3],
467                            p_title_key[i_highest].pi_key[4] );
468
469     memcpy( p_css->pi_title_key,
470             p_title_key[i_highest].pi_key, KEY_SIZE );
471
472     return 0;
473
474 #else /* HAVE_CSS */
475     return 1;
476
477 #endif /* HAVE_CSS */
478 }
479
480 /*****************************************************************************
481  * CSSDescrambleSector
482  *****************************************************************************
483  * sec : sector to descramble
484  * key : title key for this sector
485  *****************************************************************************/
486 int CSSDescrambleSector( dvd_key_t pi_key, u8* pi_sec )
487 {
488 #ifdef HAVE_CSS
489     unsigned int    i_t1, i_t2, i_t3, i_t4, i_t5, i_t6;
490     u8*             pi_end = pi_sec + 0x800;
491
492     /* PES_scrambling_control */
493     if( pi_sec[0x14] & 0x30)
494     {
495         i_t1 = ((pi_key)[0] ^ pi_sec[0x54]) | 0x100;
496         i_t2 = (pi_key)[1] ^ pi_sec[0x55];
497         i_t3 = (((pi_key)[2]) | ((pi_key)[3] << 8) |
498                ((pi_key)[4] << 16)) ^ ((pi_sec[0x56]) |
499                (pi_sec[0x57] << 8) | (pi_sec[0x58] << 16));
500         i_t4 = i_t3 & 7;
501         i_t3 = i_t3 * 2 + 8 - i_t4;
502         pi_sec += 0x80;
503         i_t5 = 0;
504
505         while( pi_sec != pi_end )
506         {
507             i_t4 = pi_css_tab2[i_t2] ^ pi_css_tab3[i_t1];
508             i_t2 = i_t1>>1;
509             i_t1 = ( ( i_t1 & 1 ) << 8 ) ^ i_t4;
510             i_t4 = pi_css_tab5[i_t4];
511             i_t6 = ((((((( i_t3 >> 3 ) ^ i_t3 ) >> 1 ) ^
512                                          i_t3 ) >> 8 ) ^ i_t3 ) >> 5) & 0xff;
513             i_t3 = (i_t3 << 8 ) | i_t6;
514             i_t6 = pi_css_tab4[i_t6];
515             i_t5 += i_t6 + i_t4;
516             *pi_sec = pi_css_tab1[*pi_sec] ^( i_t5 & 0xff );
517             pi_sec++;
518             i_t5 >>= 8;
519         }
520     }
521
522     return 0;
523
524 #else /* HAVE_CSS */
525     return 1;
526
527 #endif /* HAVE_CSS */
528 }
529
530 #ifdef HAVE_CSS
531
532 /* Following functions are local */
533
534 /*****************************************************************************
535  * CSSGetASF : Get Authentification success flag
536  *****************************************************************************
537  * Returns :
538  *  -1 on ioctl error,
539  *  0 if the device needs to be authenticated,
540  *  1 either.
541  *****************************************************************************/
542 static int CSSGetASF( css_t *p_css )
543 {
544     int i_oldagid = p_css->i_agid, i_asf = 0;
545
546     for( p_css->i_agid = 0 ; p_css->i_agid < 4 ; p_css->i_agid++ )
547     {
548         if( ioctl_LUSendASF( p_css, &i_asf ) == 0 )
549         {
550             intf_WarnMsg( 3, "css info: %sauthenticated", i_asf ? "":"not " );
551
552             p_css->i_agid = i_oldagid;
553             return i_asf;
554         }
555     }
556
557     /* The ioctl process has failed */
558     intf_ErrMsg( "css error: GetASF fatal error" );
559
560     p_css->i_agid = i_oldagid;
561     return -1;
562 }
563
564 /*****************************************************************************
565  * CSSCryptKey : shuffles bits and unencrypt keys.
566  *****************************************************************************
567  * Used during authentication and disc key negociation in CSSInit.
568  * i_key_type : 0->key1, 1->key2, 2->buskey.
569  * i_varient : between 0 and 31.
570  *****************************************************************************/
571 static void CSSCryptKey( int i_key_type, int i_varient,
572                          u8 const * pi_challenge, u8* pi_key )
573 {
574     /* Permutation table for challenge */
575     u8      ppi_perm_challenge[3][10] =
576             { { 1, 3, 0, 7, 5, 2, 9, 6, 4, 8 },
577               { 6, 1, 9, 3, 8, 5, 7, 4, 0, 2 },
578               { 4, 0, 3, 5, 7, 2, 8, 6, 1, 9 } };
579
580     /* Permutation table for varient table for key2 and buskey */
581     u8      ppi_perm_varient[2][32] =
582             { { 0x0a, 0x08, 0x0e, 0x0c, 0x0b, 0x09, 0x0f, 0x0d,
583                 0x1a, 0x18, 0x1e, 0x1c, 0x1b, 0x19, 0x1f, 0x1d,
584                 0x02, 0x00, 0x06, 0x04, 0x03, 0x01, 0x07, 0x05,
585                 0x12, 0x10, 0x16, 0x14, 0x13, 0x11, 0x17, 0x15 },
586               { 0x12, 0x1a, 0x16, 0x1e, 0x02, 0x0a, 0x06, 0x0e,
587                 0x10, 0x18, 0x14, 0x1c, 0x00, 0x08, 0x04, 0x0c,
588                 0x13, 0x1b, 0x17, 0x1f, 0x03, 0x0b, 0x07, 0x0f,
589                 0x11, 0x19, 0x15, 0x1d, 0x01, 0x09, 0x05, 0x0d } };
590
591     u8      pi_varients[32] =
592             {   0xB7, 0x74, 0x85, 0xD0, 0xCC, 0xDB, 0xCA, 0x73,
593                 0x03, 0xFE, 0x31, 0x03, 0x52, 0xE0, 0xB7, 0x42,
594                 0x63, 0x16, 0xF2, 0x2A, 0x79, 0x52, 0xFF, 0x1B,
595                 0x7A, 0x11, 0xCA, 0x1A, 0x9B, 0x40, 0xAD, 0x01 };
596
597     /* The "secret" key */
598     u8      pi_secret[5] = { 0x55, 0xD6, 0xC4, 0xC5, 0x28 };
599
600     u8      pi_bits[30];
601     u8      pi_scratch[10];
602     u8      pi_tmp1[5];
603     u8      pi_tmp2[5];
604     u8      i_lfsr0_o;  /* 1 bit used */
605     u8      i_lfsr1_o;  /* 1 bit used */
606     u32     i_lfsr0;
607     u32     i_lfsr1;
608     u8      i_css_varient;
609     u8      i_cse;
610     u8      i_index;
611     u8      i_combined;
612     u8      i_carry;
613     u8      i_val = 0;
614     int     i_term = 0;
615     int     i_bit;
616     int     i;
617
618     for (i = 9; i >= 0; --i)
619         pi_scratch[i] = pi_challenge[ppi_perm_challenge[i_key_type][i]];
620
621     i_css_varient = ( i_key_type == 0 ) ? i_varient :
622                     ppi_perm_varient[i_key_type-1][i_varient];
623
624     /*
625      * This encryption engine implements one of 32 variations
626      * one the same theme depending upon the choice in the
627      * varient parameter (0 - 31).
628      *
629      * The algorithm itself manipulates a 40 bit input into
630      * a 40 bit output.
631      * The parameter 'input' is 80 bits.  It consists of
632      * the 40 bit input value that is to be encrypted followed
633      * by a 40 bit seed value for the pseudo random number
634      * generators.
635      */
636
637     /* Feed the secret into the input values such that
638      * we alter the seed to the LFSR's used above,  then
639      * generate the bits to play with.
640      */
641     for( i = 5 ; --i >= 0 ; )
642     {
643         pi_tmp1[i] = pi_scratch[5 + i] ^ pi_secret[i] ^ pi_crypt_tab2[i];
644     }
645
646     /*
647      * We use two LFSR's (seeded from some of the input data bytes) to
648      * generate two streams of pseudo-random bits.  These two bit streams
649      * are then combined by simply adding with carry to generate a final
650      * sequence of pseudo-random bits which is stored in the buffer that
651      * 'output' points to the end of - len is the size of this buffer.
652      *
653      * The first LFSR is of degree 25,  and has a polynomial of:
654      * x^13 + x^5 + x^4 + x^1 + 1
655      *
656      * The second LSFR is of degree 17,  and has a (primitive) polynomial of:
657      * x^15 + x^1 + 1
658      *
659      * I don't know if these polynomials are primitive modulo 2,  and thus
660      * represent maximal-period LFSR's.
661      *
662      *
663      * Note that we take the output of each LFSR from the new shifted in
664      * bit,  not the old shifted out bit.  Thus for ease of use the LFSR's
665      * are implemented in bit reversed order.
666      *
667      */
668     
669     /* In order to ensure that the LFSR works we need to ensure that the
670      * initial values are non-zero.  Thus when we initialise them from
671      * the seed,  we ensure that a bit is set.
672      */
673     i_lfsr0 = ( pi_tmp1[0] << 17 ) | ( pi_tmp1[1] << 9 ) |
674               (( pi_tmp1[2] & ~7 ) << 1 ) | 8 | ( pi_tmp1[2] & 7 );
675     i_lfsr1 = ( pi_tmp1[3] << 9 ) | 0x100 | pi_tmp1[4];
676
677     i_index = sizeof(pi_bits);
678     i_carry = 0;
679
680     do
681     {
682         for( i_bit = 0, i_val = 0 ; i_bit < 8 ; ++i_bit )
683         {
684
685             i_lfsr0_o = ( ( i_lfsr0 >> 24 ) ^ ( i_lfsr0 >> 21 ) ^
686                         ( i_lfsr0 >> 20 ) ^ ( i_lfsr0 >> 12 ) ) & 1;
687             i_lfsr0 = ( i_lfsr0 << 1 ) | i_lfsr0_o;
688
689             i_lfsr1_o = ( ( i_lfsr1 >> 16 ) ^ ( i_lfsr1 >> 2 ) ) & 1;
690             i_lfsr1 = ( i_lfsr1 << 1 ) | i_lfsr1_o;
691
692             i_combined = !i_lfsr1_o + i_carry + !i_lfsr0_o;
693             /* taking bit 1 */
694             i_carry = ( i_combined >> 1 ) & 1;
695             i_val |= ( i_combined & 1 ) << i_bit;
696         }
697     
698         pi_bits[--i_index] = i_val;
699     } while( i_index > 0 );
700
701     /* This term is used throughout the following to
702      * select one of 32 different variations on the
703      * algorithm.
704      */
705     i_cse = pi_varients[i_css_varient] ^ pi_crypt_tab2[i_css_varient];
706
707     /* Now the actual blocks doing the encryption.  Each
708      * of these works on 40 bits at a time and are quite
709      * similar.
710      */
711     i_index = 0;
712     for( i = 5, i_term = 0 ; --i >= 0 ; i_term = pi_scratch[i] )
713     {
714         i_index = pi_bits[25 + i] ^ pi_scratch[i];
715         i_index = pi_crypt_tab1[i_index] ^ ~pi_crypt_tab2[i_index] ^ i_cse;
716
717         pi_tmp1[i] = pi_crypt_tab2[i_index] ^ pi_crypt_tab3[i_index] ^ i_term;
718     }
719     pi_tmp1[4] ^= pi_tmp1[0];
720
721     for( i = 5, i_term = 0 ; --i >= 0 ; i_term = pi_tmp1[i] )
722     {
723         i_index = pi_bits[20 + i] ^ pi_tmp1[i];
724         i_index = pi_crypt_tab1[i_index] ^ ~pi_crypt_tab2[i_index] ^ i_cse;
725
726         pi_tmp2[i] = pi_crypt_tab2[i_index] ^ pi_crypt_tab3[i_index] ^ i_term;
727     }
728     pi_tmp2[4] ^= pi_tmp2[0];
729
730     for( i = 5, i_term = 0 ; --i >= 0 ; i_term = pi_tmp2[i] )
731     {
732         i_index = pi_bits[15 + i] ^ pi_tmp2[i];
733         i_index = pi_crypt_tab1[i_index] ^ ~pi_crypt_tab2[i_index] ^ i_cse;
734         i_index = pi_crypt_tab2[i_index] ^ pi_crypt_tab3[i_index] ^ i_term;
735
736         pi_tmp1[i] = pi_crypt_tab0[i_index] ^ pi_crypt_tab2[i_index];
737     }
738     pi_tmp1[4] ^= pi_tmp1[0];
739
740     for( i = 5, i_term = 0 ; --i >= 0 ; i_term = pi_tmp1[i] )
741     {
742         i_index = pi_bits[10 + i] ^ pi_tmp1[i];
743         i_index = pi_crypt_tab1[i_index] ^ ~pi_crypt_tab2[i_index] ^ i_cse;
744
745         i_index = pi_crypt_tab2[i_index] ^ pi_crypt_tab3[i_index] ^ i_term;
746
747         pi_tmp2[i] = pi_crypt_tab0[i_index] ^ pi_crypt_tab2[i_index];
748     }
749     pi_tmp2[4] ^= pi_tmp2[0];
750
751     for( i = 5, i_term = 0 ; --i >= 0 ; i_term = pi_tmp2[i] )
752     {
753         i_index = pi_bits[5 + i] ^ pi_tmp2[i];
754         i_index = pi_crypt_tab1[i_index] ^ ~pi_crypt_tab2[i_index] ^ i_cse;
755
756         pi_tmp1[i] = pi_crypt_tab2[i_index] ^ pi_crypt_tab3[i_index] ^ i_term;
757     }
758     pi_tmp1[4] ^= pi_tmp1[0];
759
760     for(i = 5, i_term = 0 ; --i >= 0 ; i_term = pi_tmp1[i] )
761     {
762         i_index = pi_bits[i] ^ pi_tmp1[i];
763         i_index = pi_crypt_tab1[i_index] ^ ~pi_crypt_tab2[i_index] ^ i_cse;
764
765         pi_key[i] = pi_crypt_tab2[i_index] ^ pi_crypt_tab3[i_index] ^ i_term;
766     }
767
768     return;
769 }
770
771 /*****************************************************************************
772  * CSSCracker : title key decryption by cracking
773  *****************************************************************************
774  * This function is called by CSSGetKeys to find a key
775  *****************************************************************************/
776 static int CSSCracker( int i_start,
777                        unsigned char * p_crypted,
778                        unsigned char * p_decrypted,
779                        dvd_key_t * p_sector_key,
780                        dvd_key_t * p_key )
781 {
782     unsigned char pi_buffer[10];
783     unsigned int i_t1, i_t2, i_t3, i_t4, i_t5, i_t6;
784     unsigned int i_try;
785     unsigned int i_candidate;
786     unsigned int i, j;
787     int i_exit = -1;
788
789
790     for( i = 0 ; i < 10 ; i++ )
791     {
792         pi_buffer[i] = pi_css_tab1[p_crypted[i]] ^ p_decrypted[i];
793     }
794
795     for( i_try = i_start ; i_try < 0x10000 ; i_try++ )
796     {
797         i_t1 = i_try >> 8 | 0x100;
798         i_t2 = i_try & 0xff;
799         i_t3 = 0;               /* not needed */
800         i_t5 = 0;
801
802         /* iterate cipher 4 times to reconstruct LFSR2 */
803         for( i = 0 ; i < 4 ; i++ )
804         {
805             /* advance LFSR1 normaly */
806             i_t4 = pi_css_tab2[i_t2] ^ pi_css_tab3[i_t1];
807             i_t2 = i_t1 >> 1;
808             i_t1 = ( ( i_t1 & 1 ) << 8 ) ^ i_t4;
809             i_t4 = pi_css_tab5[i_t4];
810             /* deduce i_t6 & i_t5 */
811             i_t6 = pi_buffer[i];
812             if( i_t5 )
813             {
814                 i_t6 = ( i_t6 + 0xff ) & 0x0ff;
815             }
816             if( i_t6 < i_t4 )
817             {
818                 i_t6 += 0x100;
819             }
820             i_t6 -= i_t4;
821             i_t5 += i_t6 + i_t4;
822             i_t6 = pi_css_tab4[ i_t6 ];
823             /* feed / advance i_t3 / i_t5 */
824             i_t3 = ( i_t3 << 8 ) | i_t6;
825             i_t5 >>= 8;
826         }
827
828         i_candidate = i_t3;
829
830         /* iterate 6 more times to validate candidate key */
831         for( ; i < 10 ; i++ )
832         {
833             i_t4 = pi_css_tab2[i_t2] ^ pi_css_tab3[i_t1];
834             i_t2 = i_t1 >> 1;
835             i_t1 = ( ( i_t1 & 1 ) << 8 ) ^ i_t4;
836             i_t4 = pi_css_tab5[i_t4];
837             i_t6 = ((((((( i_t3 >> 3 ) ^ i_t3 ) >> 1 ) ^
838                                          i_t3 ) >> 8 ) ^ i_t3 ) >> 5 ) & 0xff;
839             i_t3 = ( i_t3 << 8 ) | i_t6;
840             i_t6 = pi_css_tab4[i_t6];
841             i_t5 += i_t6 + i_t4;
842             if( ( i_t5 & 0xff ) != pi_buffer[i] )
843             {
844                 break;
845             }
846
847             i_t5 >>= 8;
848         }
849
850         if( i == 10 )
851         {
852             /* Do 4 backwards steps of iterating t3 to deduce initial state */
853             i_t3 = i_candidate;
854             for( i = 0 ; i < 4 ; i++ )
855             {
856                 i_t1 = i_t3 & 0xff;
857                 i_t3 = ( i_t3 >> 8 );
858                 /* easy to code, and fast enough bruteforce
859                  * search for byte shifted in */
860                 for( j = 0 ; j < 256 ; j++ )
861                 {
862                     i_t3 = ( i_t3 & 0x1ffff) | ( j << 17 );
863                     i_t6 = ((((((( i_t3 >> 3 ) ^ i_t3 ) >> 1 ) ^
864                                    i_t3 ) >> 8 ) ^ i_t3 ) >> 5 ) & 0xff;
865                     if( i_t6 == i_t1 )
866                     {
867                         break;
868                     }
869                 }
870             }
871
872             i_t4 = ( i_t3 >> 1 ) - 4;
873             for( i_t5 = 0 ; i_t5 < 8; i_t5++ )
874             {
875                 if( ( ( i_t4 + i_t5 ) * 2 + 8 - ( (i_t4 + i_t5 ) & 7 ) )
876                                                                       == i_t3 )
877                 {
878                     (*p_key)[0] = i_try>>8;
879                     (*p_key)[1] = i_try & 0xFF;
880                     (*p_key)[2] = ( ( i_t4 + i_t5 ) >> 0) & 0xFF;
881                     (*p_key)[3] = ( ( i_t4 + i_t5 ) >> 8) & 0xFF;
882                     (*p_key)[4] = ( ( i_t4 + i_t5 ) >> 16) & 0xFF;
883                     i_exit = i_try + 1;
884                 }
885             }
886         }
887     }
888
889     if( i_exit >= 0 )
890     {
891         (*p_key)[0] ^= (*p_sector_key)[0];
892         (*p_key)[1] ^= (*p_sector_key)[1];
893         (*p_key)[2] ^= (*p_sector_key)[2];
894         (*p_key)[3] ^= (*p_sector_key)[3];
895         (*p_key)[4] ^= (*p_sector_key)[4];
896     }
897
898     return i_exit;
899 }
900
901 #endif /* HAVE_CSS */
902