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