]> git.sesse.net Git - vlc/blob - modules/demux/mp4/drms.c
* drms: support for getting user key from firewire connected iPod under
[vlc] / modules / demux / mp4 / drms.c
1 /*****************************************************************************
2  * drms.c: DRMS
3  *****************************************************************************
4  * Copyright (C) 2004 VideoLAN
5  * $Id: drms.c,v 1.10 2004/01/22 01:20:39 jlj Exp $
6  *
7  * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8  *          Sam Hocevar <sam@zoy.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 #include <stdlib.h>                                      /* malloc(), free() */
26
27 #ifdef WIN32
28 #   include <io.h>
29 #else
30 #   include <stdio.h>
31 #endif
32
33 #include <vlc/vlc.h>
34
35 #ifdef HAVE_ERRNO_H
36 #   include <errno.h>
37 #endif
38
39 #ifdef WIN32
40 #   include <tchar.h>
41 #   include <shlobj.h>
42 #   include <windows.h>
43 #endif
44
45 #ifdef HAVE_SYS_STAT_H
46 #   include <sys/stat.h>
47 #endif
48 #ifdef HAVE_SYS_TYPES_H
49 #   include <sys/types.h>
50 #endif
51
52 /* In Solaris (and perhaps others) PATH_MAX is in limits.h. */
53 #ifdef HAVE_LIMITS_H
54 #   include <limits.h>
55 #endif
56
57 #ifdef HAVE_SYSFS_LIBSYSFS_H
58 #    include <sysfs/libsysfs.h>
59 #endif
60
61 #include "drms.h"
62 #include "drmstables.h"
63
64 #include "libmp4.h"
65
66 /*****************************************************************************
67  * aes_s: AES keys structure
68  *****************************************************************************
69  * This structure stores a set of keys usable for encryption and decryption
70  * with the AES/Rijndael algorithm.
71  *****************************************************************************/
72 struct aes_s
73 {
74     uint32_t pp_enc_keys[ AES_KEY_COUNT + 1 ][ 4 ];
75     uint32_t pp_dec_keys[ AES_KEY_COUNT + 1 ][ 4 ];
76 };
77
78 /*****************************************************************************
79  * md5_s: MD5 message structure
80  *****************************************************************************
81  * This structure stores the static information needed to compute an MD5
82  * hash. It has an extra data buffer to allow non-aligned writes.
83  *****************************************************************************/
84 struct md5_s
85 {
86     uint64_t i_bits;      /* Total written bits */
87     uint32_t p_digest[4]; /* The MD5 digest */
88     uint32_t p_data[16];  /* Buffer to cache non-aligned writes */
89 };
90
91 /*****************************************************************************
92  * shuffle_s: shuffle structure
93  *****************************************************************************
94  * This structure stores the static information needed to shuffle data using
95  * a custom algorithm.
96  *****************************************************************************/
97 struct shuffle_s
98 {
99     uint32_t p_commands[ 20 ];
100     uint32_t p_bordel[ 16 ];
101 };
102
103 /*****************************************************************************
104  * drms_s: DRMS structure
105  *****************************************************************************
106  * This structure stores the static information needed to decrypt DRMS data.
107  *****************************************************************************/
108 struct drms_s
109 {
110     uint32_t i_user;
111     uint32_t i_key;
112     uint8_t  p_iviv[ 16 ];
113     uint8_t *p_name;
114
115     uint32_t p_key[ 4 ];
116     struct aes_s aes;
117
118     char     psz_homedir[ PATH_MAX ];
119 };
120
121 /*****************************************************************************
122  * Local prototypes
123  *****************************************************************************/
124 static void InitAES       ( struct aes_s *, uint32_t * );
125 static void DecryptAES    ( struct aes_s *, uint32_t *, const uint32_t * );
126
127 static void InitMD5       ( struct md5_s * );
128 static void AddMD5        ( struct md5_s *, const uint8_t *, uint32_t );
129 static void EndMD5        ( struct md5_s * );
130 static void Digest        ( struct md5_s *, uint32_t * );
131
132 static void InitShuffle   ( struct shuffle_s *, uint32_t * );
133 static void DoShuffle     ( struct shuffle_s *, uint8_t *, uint32_t );
134
135 static int GetSystemKey   ( uint32_t *, vlc_bool_t );
136 static int WriteUserKey   ( void *, uint32_t * );
137 static int ReadUserKey    ( void *, uint32_t * );
138 static int GetUserKey     ( void *, uint32_t * );
139
140 static int GetSCIData     ( char *, uint32_t **, uint32_t * );
141 static int HashSystemInfo ( uint32_t * );
142 static int GetiPodID      ( long long * );
143
144 #ifdef WORDS_BIGENDIAN
145 /*****************************************************************************
146  * Reverse: reverse byte order
147  *****************************************************************************/
148 static inline void Reverse( uint32_t *p_buffer, int n )
149 {
150     int i;
151
152     for( i = 0; i < n; i++ )
153     {
154         p_buffer[ i ] = GetDWLE(&p_buffer[ i ]);
155     }
156 }
157 #    define REVERSE( p, n ) Reverse( p, n )
158 #else
159 #    define REVERSE( p, n )
160 #endif
161
162 /*****************************************************************************
163  * BlockXOR: XOR two 128 bit blocks
164  *****************************************************************************/
165 static inline void BlockXOR( uint32_t *p_dest, uint32_t *p_s1, uint32_t *p_s2 )
166 {
167     int i;
168
169     for( i = 0; i < 4; i++ )
170     {
171         p_dest[ i ] = p_s1[ i ] ^ p_s2[ i ];
172     }
173 }
174
175 /*****************************************************************************
176  * drms_alloc: allocate a DRMS structure
177  *****************************************************************************/
178 void *drms_alloc( char *psz_homedir )
179 {
180     struct drms_s *p_drms;
181
182     p_drms = malloc( sizeof(struct drms_s) );
183
184     if( p_drms == NULL )
185     {
186         return NULL;
187     }
188
189     memset( p_drms, 0, sizeof(struct drms_s) );
190
191     strncpy( p_drms->psz_homedir, psz_homedir, PATH_MAX );
192     p_drms->psz_homedir[ PATH_MAX - 1 ] = '\0';
193
194     return (void *)p_drms;
195 }
196
197 /*****************************************************************************
198  * drms_free: free a previously allocated DRMS structure
199  *****************************************************************************/
200 void drms_free( void *_p_drms )
201 {
202     struct drms_s *p_drms = (struct drms_s *)_p_drms;
203
204     if( p_drms->p_name != NULL )
205     {
206         free( (void *)p_drms->p_name );
207     }
208
209     free( p_drms );
210 }
211
212 /*****************************************************************************
213  * drms_decrypt: unscramble a chunk of data
214  *****************************************************************************/
215 void drms_decrypt( void *_p_drms, uint32_t *p_buffer, uint32_t i_bytes )
216 {
217     struct drms_s *p_drms = (struct drms_s *)_p_drms;
218     uint32_t p_key[ 4 ];
219     unsigned int i_blocks;
220
221     /* AES is a block cypher, round down the byte count */
222     i_blocks = i_bytes / 16;
223     i_bytes = i_blocks * 16;
224
225     /* Initialise the key */
226     memcpy( p_key, p_drms->p_key, 16 );
227
228     /* Unscramble */
229     while( i_blocks-- )
230     {
231         uint32_t p_tmp[ 4 ];
232
233         REVERSE( p_buffer, 4 );
234         DecryptAES( &p_drms->aes, p_tmp, p_buffer );
235         BlockXOR( p_tmp, p_key, p_tmp );
236
237         /* Use the previous scrambled data as the key for next block */
238         memcpy( p_key, p_buffer, 16 );
239
240         /* Copy unscrambled data back to the buffer */
241         memcpy( p_buffer, p_tmp, 16 );
242         REVERSE( p_buffer, 4 );
243
244         p_buffer += 4;
245     }
246 }
247
248 /*****************************************************************************
249  * drms_init: initialise a DRMS structure
250  *****************************************************************************/
251 int drms_init( void *_p_drms, uint32_t i_type,
252                uint8_t *p_info, uint32_t i_len )
253 {
254     struct drms_s *p_drms = (struct drms_s *)_p_drms;
255     int i_ret = 0;
256
257     switch( i_type )
258     {
259         case FOURCC_user:
260             if( i_len < sizeof(p_drms->i_user) )
261             {
262                 i_ret = -1;
263                 break;
264             }
265
266             p_drms->i_user = U32_AT( p_info );
267             break;
268
269         case FOURCC_key:
270             if( i_len < sizeof(p_drms->i_key) )
271             {
272                 i_ret = -1;
273                 break;
274             }
275
276             p_drms->i_key = U32_AT( p_info );
277             break;
278
279         case FOURCC_iviv:
280             if( i_len < sizeof(p_drms->p_key) )
281             {
282                 i_ret = -1;
283                 break;
284             }
285
286             memcpy( p_drms->p_iviv, p_info, 16 );
287             break;
288
289         case FOURCC_name:
290             p_drms->p_name = strdup( p_info );
291
292             if( p_drms->p_name == NULL )
293             {
294                 i_ret = -1;
295             }
296             break;
297
298         case FOURCC_priv:
299         {
300             uint32_t p_priv[ 64 ];
301             struct md5_s md5;
302
303             if( i_len < 64 )
304             {
305                 i_ret = -1;
306                 break;
307             }
308
309             InitMD5( &md5 );
310             AddMD5( &md5, p_drms->p_name, strlen( p_drms->p_name ) );
311             AddMD5( &md5, p_drms->p_iviv, 16 );
312             EndMD5( &md5 );
313
314             if( GetUserKey( p_drms, p_drms->p_key ) )
315             {
316                 i_ret = -1;
317                 break;
318             }
319
320             InitAES( &p_drms->aes, p_drms->p_key );
321
322             memcpy( p_priv, p_info, 64 );
323             memcpy( p_drms->p_key, md5.p_digest, 16 );
324             drms_decrypt( p_drms, p_priv, 64 );
325             REVERSE( p_priv, 64 );
326
327             if( p_priv[ 0 ] != 0x6e757469 ) /* itun */
328             {
329                 i_ret = -1;
330                 break;
331             }
332
333             InitAES( &p_drms->aes, p_priv + 6 );
334             memcpy( p_drms->p_key, p_priv + 12, 16 );
335
336             free( (void *)p_drms->p_name );
337             p_drms->p_name = NULL;
338         }
339         break;
340     }
341
342     return i_ret;
343 }
344
345 /* The following functions are local */
346
347 /*****************************************************************************
348  * InitAES: initialise AES/Rijndael encryption/decryption tables
349  *****************************************************************************
350  * The Advanced Encryption Standard (AES) is described in RFC 3268
351  *****************************************************************************/
352 static void InitAES( struct aes_s *p_aes, uint32_t *p_key )
353 {
354     unsigned int i, t;
355     uint32_t i_key, i_seed;
356
357     memset( p_aes->pp_enc_keys[1], 0, 16 );
358     memcpy( p_aes->pp_enc_keys[0], p_key, 16 );
359
360     /* Generate the key tables */
361     i_seed = p_aes->pp_enc_keys[ 0 ][ 3 ];
362
363     for( i_key = 0; i_key < AES_KEY_COUNT; i_key++ )
364     {
365         uint32_t j;
366
367         i_seed = AES_ROR( i_seed, 8 );
368
369         j = p_aes_table[ i_key ];
370
371         j ^= p_aes_encrypt[ (i_seed >> 24) & 0xff ]
372               ^ AES_ROR( p_aes_encrypt[ (i_seed >> 16) & 0xff ], 8 )
373               ^ AES_ROR( p_aes_encrypt[ (i_seed >> 8) & 0xff ], 16 )
374               ^ AES_ROR( p_aes_encrypt[ i_seed & 0xff ], 24 );
375
376         j ^= p_aes->pp_enc_keys[ i_key ][ 0 ];
377         p_aes->pp_enc_keys[ i_key + 1 ][ 0 ] = j;
378         j ^= p_aes->pp_enc_keys[ i_key ][ 1 ];
379         p_aes->pp_enc_keys[ i_key + 1 ][ 1 ] = j;
380         j ^= p_aes->pp_enc_keys[ i_key ][ 2 ];
381         p_aes->pp_enc_keys[ i_key + 1 ][ 2 ] = j;
382         j ^= p_aes->pp_enc_keys[ i_key ][ 3 ];
383         p_aes->pp_enc_keys[ i_key + 1 ][ 3 ] = j;
384
385         i_seed = j;
386     }
387
388     memcpy( p_aes->pp_dec_keys[ 0 ],
389             p_aes->pp_enc_keys[ 0 ], 16 );
390
391     for( i = 1; i < AES_KEY_COUNT; i++ )
392     {
393         for( t = 0; t < 4; t++ )
394         {
395             uint32_t j, k, l, m, n;
396
397             j = p_aes->pp_enc_keys[ i ][ t ];
398
399             k = (((j >> 7) & 0x01010101) * 27) ^ ((j & 0xff7f7f7f) << 1);
400             l = (((k >> 7) & 0x01010101) * 27) ^ ((k & 0xff7f7f7f) << 1);
401             m = (((l >> 7) & 0x01010101) * 27) ^ ((l & 0xff7f7f7f) << 1);
402
403             j ^= m;
404
405             n = AES_ROR( l ^ j, 16 ) ^ AES_ROR( k ^ j, 8 ) ^ AES_ROR( j, 24 );
406
407             p_aes->pp_dec_keys[ i ][ t ] = k ^ l ^ m ^ n;
408         }
409     }
410 }
411
412 /*****************************************************************************
413  * DecryptAES: decrypt an AES/Rijndael 128 bit block
414  *****************************************************************************/
415 static void DecryptAES( struct aes_s *p_aes,
416                         uint32_t *p_dest, const uint32_t *p_src )
417 {
418     uint32_t p_wtxt[ 4 ]; /* Working cyphertext */
419     uint32_t p_tmp[ 4 ];
420     unsigned int i_round, t;
421
422     for( t = 0; t < 4; t++ )
423     {
424         /* FIXME: are there any endianness issues here? */
425         p_wtxt[ t ] = p_src[ t ] ^ p_aes->pp_enc_keys[ AES_KEY_COUNT ][ t ];
426     }
427
428     /* Rounds 0 - 8 */
429     for( i_round = 0; i_round < (AES_KEY_COUNT - 1); i_round++ )
430     {
431         for( t = 0; t < 4; t++ )
432         {
433             p_tmp[ t ] = AES_XOR_ROR( p_aes_itable, p_wtxt );
434         }
435
436         for( t = 0; t < 4; t++ )
437         {
438             p_wtxt[ t ] = p_tmp[ t ]
439                     ^ p_aes->pp_dec_keys[ (AES_KEY_COUNT - 1) - i_round ][ t ];
440         }
441     }
442
443     /* Final round (9) */
444     for( t = 0; t < 4; t++ )
445     {
446         p_dest[ t ] = AES_XOR_ROR( p_aes_decrypt, p_wtxt );
447         p_dest[ t ] ^= p_aes->pp_dec_keys[ 0 ][ t ];
448     }
449 }
450
451 /*****************************************************************************
452  * InitMD5: initialise an MD5 message
453  *****************************************************************************
454  * The MD5 message-digest algorithm is described in RFC 1321
455  *****************************************************************************/
456 static void InitMD5( struct md5_s *p_md5 )
457 {
458     p_md5->p_digest[ 0 ] = 0x67452301;
459     p_md5->p_digest[ 1 ] = 0xefcdab89;
460     p_md5->p_digest[ 2 ] = 0x98badcfe;
461     p_md5->p_digest[ 3 ] = 0x10325476;
462
463     memset( p_md5->p_data, 0, 64 );
464     p_md5->i_bits = 0;
465 }
466
467 /*****************************************************************************
468  * AddMD5: add i_len bytes to an MD5 message
469  *****************************************************************************/
470 static void AddMD5( struct md5_s *p_md5, const uint8_t *p_src, uint32_t i_len )
471 {
472     unsigned int i_current; /* Current bytes in the spare buffer */
473     unsigned int i_offset = 0;
474
475     i_current = (p_md5->i_bits / 8) & 63;
476
477     p_md5->i_bits += 8 * i_len;
478
479     /* If we can complete our spare buffer to 64 bytes, do it and add the
480      * resulting buffer to the MD5 message */
481     if( i_len >= (64 - i_current) )
482     {
483         memcpy( ((uint8_t *)p_md5->p_data) + i_current, p_src,
484                 (64 - i_current) );
485         Digest( p_md5, p_md5->p_data );
486
487         i_offset += (64 - i_current);
488         i_len -= (64 - i_current);
489         i_current = 0;
490     }
491
492     /* Add as many entire 64 bytes blocks as we can to the MD5 message */
493     while( i_len >= 64 )
494     {
495         uint32_t p_tmp[ 16 ];
496         memcpy( p_tmp, p_src + i_offset, 64 );
497         Digest( p_md5, p_tmp );
498         i_offset += 64;
499         i_len -= 64;
500     }
501
502     /* Copy our remaining data to the message's spare buffer */
503     memcpy( ((uint8_t *)p_md5->p_data) + i_current, p_src + i_offset, i_len );
504 }
505
506 /*****************************************************************************
507  * EndMD5: finish an MD5 message
508  *****************************************************************************
509  * This function adds adequate padding to the end of the message, and appends
510  * the bit count so that we end at a block boundary.
511  *****************************************************************************/
512 static void EndMD5( struct md5_s *p_md5 )
513 {
514     unsigned int i_current;
515
516     i_current = (p_md5->i_bits / 8) & 63;
517
518     /* Append 0x80 to our buffer. No boundary check because the temporary
519      * buffer cannot be full, otherwise AddMD5 would have emptied it. */
520     ((uint8_t *)p_md5->p_data)[ i_current++ ] = 0x80;
521
522     /* If less than 8 bytes are available at the end of the block, complete
523      * this 64 bytes block with zeros and add it to the message. We'll add
524      * our length at the end of the next block. */
525     if( i_current > 56 )
526     {
527         memset( ((uint8_t *)p_md5->p_data) + i_current, 0, (64 - i_current) );
528         Digest( p_md5, p_md5->p_data );
529         i_current = 0;
530     }
531
532     /* Fill the unused space in our last block with zeroes and put the
533      * message length at the end. */
534     memset( ((uint8_t *)p_md5->p_data) + i_current, 0, (56 - i_current) );
535     p_md5->p_data[ 14 ] = p_md5->i_bits & 0xffffffff;
536     p_md5->p_data[ 15 ] = (p_md5->i_bits >> 32);
537     REVERSE( &p_md5->p_data[ 14 ], 2 );
538
539     Digest( p_md5, p_md5->p_data );
540 }
541
542 #define F1( x, y, z ) ((z) ^ ((x) & ((y) ^ (z))))
543 #define F2( x, y, z ) F1((z), (x), (y))
544 #define F3( x, y, z ) ((x) ^ (y) ^ (z))
545 #define F4( x, y, z ) ((y) ^ ((x) | ~(z)))
546
547 #define MD5_DO( f, w, x, y, z, data, s ) \
548     ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
549
550 /*****************************************************************************
551  * Digest: update the MD5 digest with 64 bytes of data
552  *****************************************************************************/
553 static void Digest( struct md5_s *p_md5, uint32_t *p_input )
554 {
555     uint32_t a, b, c, d;
556
557     REVERSE( p_input, 16 );
558
559     a = p_md5->p_digest[ 0 ];
560     b = p_md5->p_digest[ 1 ];
561     c = p_md5->p_digest[ 2 ];
562     d = p_md5->p_digest[ 3 ];
563
564     MD5_DO( F1, a, b, c, d, p_input[  0 ] + 0xd76aa478,  7 );
565     MD5_DO( F1, d, a, b, c, p_input[  1 ] + 0xe8c7b756, 12 );
566     MD5_DO( F1, c, d, a, b, p_input[  2 ] + 0x242070db, 17 );
567     MD5_DO( F1, b, c, d, a, p_input[  3 ] + 0xc1bdceee, 22 );
568     MD5_DO( F1, a, b, c, d, p_input[  4 ] + 0xf57c0faf,  7 );
569     MD5_DO( F1, d, a, b, c, p_input[  5 ] + 0x4787c62a, 12 );
570     MD5_DO( F1, c, d, a, b, p_input[  6 ] + 0xa8304613, 17 );
571     MD5_DO( F1, b, c, d, a, p_input[  7 ] + 0xfd469501, 22 );
572     MD5_DO( F1, a, b, c, d, p_input[  8 ] + 0x698098d8,  7 );
573     MD5_DO( F1, d, a, b, c, p_input[  9 ] + 0x8b44f7af, 12 );
574     MD5_DO( F1, c, d, a, b, p_input[ 10 ] + 0xffff5bb1, 17 );
575     MD5_DO( F1, b, c, d, a, p_input[ 11 ] + 0x895cd7be, 22 );
576     MD5_DO( F1, a, b, c, d, p_input[ 12 ] + 0x6b901122,  7 );
577     MD5_DO( F1, d, a, b, c, p_input[ 13 ] + 0xfd987193, 12 );
578     MD5_DO( F1, c, d, a, b, p_input[ 14 ] + 0xa679438e, 17 );
579     MD5_DO( F1, b, c, d, a, p_input[ 15 ] + 0x49b40821, 22 );
580
581     MD5_DO( F2, a, b, c, d, p_input[  1 ] + 0xf61e2562,  5 );
582     MD5_DO( F2, d, a, b, c, p_input[  6 ] + 0xc040b340,  9 );
583     MD5_DO( F2, c, d, a, b, p_input[ 11 ] + 0x265e5a51, 14 );
584     MD5_DO( F2, b, c, d, a, p_input[  0 ] + 0xe9b6c7aa, 20 );
585     MD5_DO( F2, a, b, c, d, p_input[  5 ] + 0xd62f105d,  5 );
586     MD5_DO( F2, d, a, b, c, p_input[ 10 ] + 0x02441453,  9 );
587     MD5_DO( F2, c, d, a, b, p_input[ 15 ] + 0xd8a1e681, 14 );
588     MD5_DO( F2, b, c, d, a, p_input[  4 ] + 0xe7d3fbc8, 20 );
589     MD5_DO( F2, a, b, c, d, p_input[  9 ] + 0x21e1cde6,  5 );
590     MD5_DO( F2, d, a, b, c, p_input[ 14 ] + 0xc33707d6,  9 );
591     MD5_DO( F2, c, d, a, b, p_input[  3 ] + 0xf4d50d87, 14 );
592     MD5_DO( F2, b, c, d, a, p_input[  8 ] + 0x455a14ed, 20 );
593     MD5_DO( F2, a, b, c, d, p_input[ 13 ] + 0xa9e3e905,  5 );
594     MD5_DO( F2, d, a, b, c, p_input[  2 ] + 0xfcefa3f8,  9 );
595     MD5_DO( F2, c, d, a, b, p_input[  7 ] + 0x676f02d9, 14 );
596     MD5_DO( F2, b, c, d, a, p_input[ 12 ] + 0x8d2a4c8a, 20 );
597
598     MD5_DO( F3, a, b, c, d, p_input[  5 ] + 0xfffa3942,  4 );
599     MD5_DO( F3, d, a, b, c, p_input[  8 ] + 0x8771f681, 11 );
600     MD5_DO( F3, c, d, a, b, p_input[ 11 ] + 0x6d9d6122, 16 );
601     MD5_DO( F3, b, c, d, a, p_input[ 14 ] + 0xfde5380c, 23 );
602     MD5_DO( F3, a, b, c, d, p_input[  1 ] + 0xa4beea44,  4 );
603     MD5_DO( F3, d, a, b, c, p_input[  4 ] + 0x4bdecfa9, 11 );
604     MD5_DO( F3, c, d, a, b, p_input[  7 ] + 0xf6bb4b60, 16 );
605     MD5_DO( F3, b, c, d, a, p_input[ 10 ] + 0xbebfbc70, 23 );
606     MD5_DO( F3, a, b, c, d, p_input[ 13 ] + 0x289b7ec6,  4 );
607     MD5_DO( F3, d, a, b, c, p_input[  0 ] + 0xeaa127fa, 11 );
608     MD5_DO( F3, c, d, a, b, p_input[  3 ] + 0xd4ef3085, 16 );
609     MD5_DO( F3, b, c, d, a, p_input[  6 ] + 0x04881d05, 23 );
610     MD5_DO( F3, a, b, c, d, p_input[  9 ] + 0xd9d4d039,  4 );
611     MD5_DO( F3, d, a, b, c, p_input[ 12 ] + 0xe6db99e5, 11 );
612     MD5_DO( F3, c, d, a, b, p_input[ 15 ] + 0x1fa27cf8, 16 );
613     MD5_DO( F3, b, c, d, a, p_input[  2 ] + 0xc4ac5665, 23 );
614
615     MD5_DO( F4, a, b, c, d, p_input[  0 ] + 0xf4292244,  6 );
616     MD5_DO( F4, d, a, b, c, p_input[  7 ] + 0x432aff97, 10 );
617     MD5_DO( F4, c, d, a, b, p_input[ 14 ] + 0xab9423a7, 15 );
618     MD5_DO( F4, b, c, d, a, p_input[  5 ] + 0xfc93a039, 21 );
619     MD5_DO( F4, a, b, c, d, p_input[ 12 ] + 0x655b59c3,  6 );
620     MD5_DO( F4, d, a, b, c, p_input[  3 ] + 0x8f0ccc92, 10 );
621     MD5_DO( F4, c, d, a, b, p_input[ 10 ] + 0xffeff47d, 15 );
622     MD5_DO( F4, b, c, d, a, p_input[  1 ] + 0x85845dd1, 21 );
623     MD5_DO( F4, a, b, c, d, p_input[  8 ] + 0x6fa87e4f,  6 );
624     MD5_DO( F4, d, a, b, c, p_input[ 15 ] + 0xfe2ce6e0, 10 );
625     MD5_DO( F4, c, d, a, b, p_input[  6 ] + 0xa3014314, 15 );
626     MD5_DO( F4, b, c, d, a, p_input[ 13 ] + 0x4e0811a1, 21 );
627     MD5_DO( F4, a, b, c, d, p_input[  4 ] + 0xf7537e82,  6 );
628     MD5_DO( F4, d, a, b, c, p_input[ 11 ] + 0xbd3af235, 10 );
629     MD5_DO( F4, c, d, a, b, p_input[  2 ] + 0x2ad7d2bb, 15 );
630     MD5_DO( F4, b, c, d, a, p_input[  9 ] + 0xeb86d391, 21 );
631
632     p_md5->p_digest[ 0 ] += a;
633     p_md5->p_digest[ 1 ] += b;
634     p_md5->p_digest[ 2 ] += c;
635     p_md5->p_digest[ 3 ] += d;
636 }
637
638 /*****************************************************************************
639  * InitShuffle: initialise a shuffle structure
640  *****************************************************************************
641  * This function initialises tables in the p_shuffle structure that will be
642  * used later by DoShuffle. The only external parameter is p_sys_key.
643  *****************************************************************************/
644 static void InitShuffle( struct shuffle_s *p_shuffle, uint32_t *p_sys_key )
645 {
646     char p_secret1[] = "*!vT";
647     static char const p_secret2[] = "v8rhvsaAvOKMFfUH%798=[;."
648                                     "f8677680a634ba87fnOIf)(*";
649     unsigned int i;
650
651     /* Fill p_commands using the key and a secret seed */
652     for( i = 0; i < 20; i++ )
653     {
654         struct md5_s md5;
655         /* Convert the secret to big endian */
656         uint32_t i_big_secret = U32_AT(p_secret1);
657         int32_t i_hash;
658
659         InitMD5( &md5 );
660         AddMD5( &md5, (uint8_t *)p_sys_key, 16 );
661         AddMD5( &md5, (uint8_t *)&i_big_secret, 4 );
662         EndMD5( &md5 );
663
664         p_secret1[ 0 ]++;
665
666         i_hash = ((int32_t)U32_AT(md5.p_digest)) % 1024;
667
668         p_shuffle->p_commands[ i ] = i_hash < 0 ? i_hash * -1 : i_hash;
669     }
670
671     /* Fill p_bordel with completely meaningless initial values. */
672     for( i = 0; i < 4; i++ )
673     {
674         p_shuffle->p_bordel[ 4 * i ] = U32_AT(p_sys_key + i);
675         memcpy( p_shuffle->p_bordel + 4 * i + 1, p_secret2 + 12 * i, 12 );
676     }
677 }
678
679 /*****************************************************************************
680  * DoShuffle: shuffle i_len bytes of a buffer
681  *****************************************************************************
682  * This is so ugly and uses so many MD5 checksums that it is most certainly
683  * one-way, though why it needs to be so complicated is beyond me.
684  *****************************************************************************/
685 static void DoShuffle( struct shuffle_s *p_shuffle,
686                        uint8_t *p_buffer, uint32_t i_len )
687 {
688     struct md5_s md5;
689     uint32_t p_big_bordel[ 16 ];
690     uint32_t *p_bordel = p_shuffle->p_bordel;
691     unsigned int i;
692
693     /* Using the MD5 hash of a memory block is probably not one-way enough
694      * for the iTunes people. This function randomises p_bordel depending on
695      * the values in p_commands to make things even more messy in p_bordel. */
696     for( i = 0; i < 20; i++ )
697     {
698         uint8_t i_command, i_index;
699
700         if( !p_shuffle->p_commands[ i ] )
701         {
702             continue;
703         }
704
705         i_command = (p_shuffle->p_commands[ i ] & 0x300) >> 8;
706         i_index = p_shuffle->p_commands[ i ] & 0xff;
707
708         switch( i_command )
709         {
710         case 0x3:
711             p_bordel[ i_index & 0xf ] = p_bordel[ i_index >> 4 ]
712                                       + p_bordel[ ((i_index + 0x10) >> 4) & 0xf ];
713             break;
714         case 0x2:
715             p_bordel[ i_index >> 4 ] ^= p_shuffle_xor[ 0xff - i_index ];
716             break;
717         case 0x1:
718             p_bordel[ i_index >> 4 ] -= p_shuffle_sub[ 0xff - i_index ];
719             break;
720         default:
721             p_bordel[ i_index >> 4 ] += p_shuffle_add[ 0xff - i_index ];
722             break;
723         }
724     }
725
726     /* Convert our newly randomised p_bordel to big endianness and take
727      * its MD5 hash. */
728     InitMD5( &md5 );
729     for( i = 0; i < 16; i++ )
730     {
731         p_big_bordel[ i ] = U32_AT(p_bordel + i);
732     }
733     AddMD5( &md5, (uint8_t *)p_big_bordel, 64 );
734     EndMD5( &md5 );
735
736     /* There are only 16 bytes in an MD5 hash */
737     if( i_len > 16 )
738     {
739         i_len = 16;
740     }
741
742     /* XOR our buffer with the computed checksum */
743     for( i = 0; i < i_len; i++ )
744     {
745         p_buffer[ i ] ^= ((uint8_t *)&md5.p_digest)[ i ];
746     }
747 }
748
749 /*****************************************************************************
750  * GetSystemKey: get the system key
751  *****************************************************************************
752  * Compute the system key from various system information, see HashSystemInfo.
753  *****************************************************************************/
754 static int GetSystemKey( uint32_t *p_sys_key, vlc_bool_t b_ipod )
755 {
756     static char const p_secret1[ 8 ] = "YuaFlafu";
757     static char const p_secret2[ 8 ] = "zPif98ga";
758     struct md5_s md5;
759     long long i_ipod_id;
760     uint32_t p_system_hash[ 4 ];
761
762     /* Compute the MD5 hash of our system info */
763     if( ( !b_ipod && HashSystemInfo( p_system_hash ) ) ||
764         (  b_ipod && GetiPodID( &i_ipod_id ) ) )
765     {
766         return -1;
767     }
768
769     /* Combine our system info hash with additional secret data. The resulting
770      * MD5 hash will be our system key. */
771     InitMD5( &md5 );
772     AddMD5( &md5, p_secret1, 8 );
773
774     if( !b_ipod )
775     {
776         AddMD5( &md5, (uint8_t *)p_system_hash, 6 );
777         AddMD5( &md5, (uint8_t *)p_system_hash, 6 );
778         AddMD5( &md5, (uint8_t *)p_system_hash, 6 );
779         AddMD5( &md5, p_secret2, 8 );
780     }
781     else
782     {
783         i_ipod_id = U64_AT(&i_ipod_id);
784         AddMD5( &md5, (uint8_t *)&i_ipod_id, sizeof(i_ipod_id) );
785         AddMD5( &md5, (uint8_t *)&i_ipod_id, sizeof(i_ipod_id) );
786         AddMD5( &md5, (uint8_t *)&i_ipod_id, sizeof(i_ipod_id) );
787     }
788
789     EndMD5( &md5 );
790
791     memcpy( p_sys_key, md5.p_digest, 16 );
792
793     return 0;
794 }
795
796 #ifdef WIN32
797 #   define DRMS_DIRNAME "drms"
798 #else
799 #   define DRMS_DIRNAME ".drms"
800 #endif
801
802 /*****************************************************************************
803  * WriteUserKey: write the user key to hard disk
804  *****************************************************************************
805  * Write the user key to the hard disk so that it can be reused later or used
806  * on operating systems other than Win32.
807  *****************************************************************************/
808 static int WriteUserKey( void *_p_drms, uint32_t *p_user_key )
809 {
810     struct drms_s *p_drms = (struct drms_s *)_p_drms;
811     FILE *file;
812     int i_ret = -1;
813     char psz_path[ PATH_MAX ];
814
815     snprintf( psz_path, PATH_MAX - 1,
816               "%s/" DRMS_DIRNAME, p_drms->psz_homedir );
817
818 #if defined( HAVE_ERRNO_H )
819 #   if defined( WIN32 )
820     if( !mkdir( psz_path ) || errno == EEXIST )
821 #   else
822     if( !mkdir( psz_path, 0755 ) || errno == EEXIST )
823 #   endif
824 #else
825     if( !mkdir( psz_path ) )
826 #endif
827     {
828         snprintf( psz_path, PATH_MAX - 1, "%s/" DRMS_DIRNAME "/%08X.%03d",
829                   p_drms->psz_homedir, p_drms->i_user, p_drms->i_key );
830
831         file = fopen( psz_path, "w" );
832         if( file != NULL )
833         {
834             i_ret = fwrite( p_user_key, sizeof(uint32_t),
835                             4, file ) == 4 ? 0 : -1;
836             fclose( file );
837         }
838     }
839
840     return i_ret;
841 }
842
843 /*****************************************************************************
844  * ReadUserKey: read the user key from hard disk
845  *****************************************************************************
846  * Retrieve the user key from the hard disk if available.
847  *****************************************************************************/
848 static int ReadUserKey( void *_p_drms, uint32_t *p_user_key )
849 {
850     struct drms_s *p_drms = (struct drms_s *)_p_drms;
851     FILE *file;
852     int i_ret = -1;
853     char psz_path[ PATH_MAX ];
854
855     snprintf( psz_path, PATH_MAX - 1,
856               "%s/" DRMS_DIRNAME "/%08X.%03d", p_drms->psz_homedir,
857               p_drms->i_user, p_drms->i_key );
858
859     file = fopen( psz_path, "r" );
860     if( file != NULL )
861     {
862         i_ret = fread( p_user_key, sizeof(uint32_t),
863                        4, file ) == 4 ? 0 : -1;
864         fclose( file );
865     }
866
867     return i_ret;
868 }
869
870 /*****************************************************************************
871  * GetUserKey: get the user key
872  *****************************************************************************
873  * Retrieve the user key from the hard disk if available, otherwise generate
874  * it from the system key. If the key could be successfully generated, write
875  * it to the hard disk for future use.
876  *****************************************************************************/
877 static int GetUserKey( void *_p_drms, uint32_t *p_user_key )
878 {
879     static char const p_secret[] = "mUfnpognadfgf873";
880     struct drms_s *p_drms = (struct drms_s *)_p_drms;
881     struct aes_s aes;
882     struct shuffle_s shuffle;
883     uint32_t i, y;
884     uint32_t *p_sci_data;
885     uint32_t p_sys_key[ 4 ];
886     uint32_t i_sci_size, i_blocks;
887     uint32_t *p_sci0, *p_sci1, *p_buffer;
888     uint32_t p_sci_key[ 4 ];
889     char *psz_ipod;
890     int i_ret = -1;
891
892     if( !ReadUserKey( p_drms, p_user_key ) )
893     {
894         REVERSE( p_user_key, 4 );
895         return 0;
896     }
897
898     psz_ipod = getenv( "IPOD" );
899
900     if( GetSystemKey( p_sys_key, psz_ipod ? VLC_TRUE : VLC_FALSE ) )
901     {
902         return -1;
903     }
904
905     if( GetSCIData( psz_ipod, &p_sci_data, &i_sci_size ) )
906     {
907         return -1;
908     }
909
910     /* Phase 1: unscramble the SCI data using the system key and shuffle
911      *          it using DoShuffle(). */
912
913     /* Skip the first 4 bytes (some sort of header). Decrypt the rest. */
914     i_blocks = (i_sci_size - 4) / 16;
915     p_buffer = p_sci_data + 1;
916
917     /* Decrypt and shuffle our data at the same time */
918     InitAES( &aes, p_sys_key );
919     InitShuffle( &shuffle, p_sys_key );
920
921     /* FIXME: check for endianness */
922     memcpy( p_sci_key, p_secret, 16 );
923
924     while( i_blocks-- )
925     {
926         uint32_t p_tmp[ 4 ];
927
928         REVERSE( p_buffer, 4 );
929         DecryptAES( &aes, p_tmp, p_buffer );
930         BlockXOR( p_tmp, p_sci_key, p_tmp );
931
932         /* Use the previous scrambled data as the key for next block */
933         memcpy( p_sci_key, p_buffer, 16 );
934
935         /* Shuffle the decrypted data using a custom routine */
936         DoShuffle( &shuffle, (uint8_t *)p_tmp, 16 );
937
938         /* Copy this block back to p_buffer */
939         memcpy( p_buffer, p_tmp, 16 );
940
941         p_buffer += 4;
942     }
943
944     /* Phase 2: look for the user key in the generated data. I must admit I
945      *          do not understand what is going on here, because it almost
946      *          looks like we are browsing data that makes sense, even though
947      *          the DoShuffle() part made it completely meaningless. */
948
949     y = 0;
950     i = U32_AT( p_sci_data + 5 );
951     i_sci_size -= 22 * sizeof(uint32_t);
952     p_sci1 = p_sci_data + 22;
953     p_sci0 = NULL;
954
955     while( i_sci_size >= 20 && i > 0 )
956     {
957         if( p_sci0 == NULL )
958         {
959             i_sci_size -= 18 * sizeof(uint32_t);
960             if( i_sci_size < 20 )
961             {
962                 break;
963             }
964
965             p_sci0 = p_sci1;
966             y = U32_AT( p_sci1 + 17 );
967             p_sci1 += 18;
968         }
969
970         if( !y )
971         {
972             i--;
973             p_sci0 = NULL;
974             continue;
975         }
976
977         if( U32_AT( p_sci0 ) == p_drms->i_user &&
978             ( ( U32_AT( p_sci1 ) == p_drms->i_key ) ||
979               ( !p_drms->i_key ) || ( p_sci1 == (p_sci0 + 18) ) ) )
980         {
981             memcpy( p_user_key, p_sci1 + 1, 16 );
982             WriteUserKey( p_drms, p_user_key );
983             i_ret = 0;
984             break;
985         }
986
987         y--;
988         p_sci1 += 5;
989         i_sci_size -= 5 * sizeof(uint32_t);
990     }
991
992     free( p_sci_data );
993
994     return i_ret;
995 }
996
997 /*****************************************************************************
998  * GetSCIData: get SCI data from "SC Info.sidb"
999  *****************************************************************************
1000  * Read SCI data from "\Apple Computer\iTunes\SC Info\SC Info.sidb"
1001  *****************************************************************************/
1002 static int GetSCIData( char *psz_ipod, uint32_t **pp_sci,
1003                        uint32_t *pi_sci_size )
1004 {
1005     FILE *file;
1006     char *psz_path = NULL;
1007     char p_tmp[ PATH_MAX ];
1008     int i_ret = -1;
1009
1010     if( psz_ipod == NULL )
1011     {
1012 #ifdef WIN32
1013         char *p_filename = "\\Apple Computer\\iTunes\\SC Info\\SC Info.sidb";
1014         typedef HRESULT (WINAPI *SHGETFOLDERPATH)( HWND, int, HANDLE, DWORD,
1015                                                    LPSTR );
1016         HINSTANCE shfolder_dll = NULL;
1017         SHGETFOLDERPATH dSHGetFolderPath = NULL;
1018
1019         if( ( shfolder_dll = LoadLibrary( _T("SHFolder.dll") ) ) != NULL )
1020         {
1021             dSHGetFolderPath =
1022                 (SHGETFOLDERPATH)GetProcAddress( shfolder_dll,
1023                                                  _T("SHGetFolderPathA") );
1024         }
1025
1026         if( dSHGetFolderPath != NULL &&
1027             SUCCEEDED( dSHGetFolderPath( NULL, CSIDL_COMMON_APPDATA,
1028                                          NULL, 0, p_tmp ) ) )
1029         {
1030             strncat( p_tmp, p_filename, min( strlen( p_filename ),
1031                       (sizeof(p_tmp) - 1) - strlen( p_tmp ) ) );
1032             psz_path = p_tmp;
1033         }
1034
1035         if( shfolder_dll != NULL )
1036         {
1037             FreeLibrary( shfolder_dll );
1038         }
1039 #endif
1040     }
1041     else
1042     {
1043         char *p_filename = "/iPod_Control/iTunes/iSCInfo";
1044         snprintf( p_tmp, sizeof(p_tmp) - 1, "%s%s",
1045                   psz_ipod, p_filename );
1046         psz_path = p_tmp;
1047     }
1048
1049     if( psz_path == NULL )
1050     {
1051         return -1;
1052     }
1053
1054     file = fopen( psz_path, "r" );
1055     if( file != NULL )
1056     {
1057         struct stat st;
1058
1059         if( !fstat( fileno( file ), &st ) )
1060         {
1061             *pp_sci = malloc( st.st_size );
1062             if( *pp_sci != NULL )
1063             {
1064                 if( fread( *pp_sci, 1, st.st_size,
1065                            file ) == (size_t)st.st_size )
1066                 {
1067                     *pi_sci_size = st.st_size;
1068                     i_ret = 0;
1069                 }
1070                 else
1071                 {
1072                     free( (void *)*pp_sci );
1073                     *pp_sci = NULL;
1074                 }
1075             }
1076         }
1077
1078         fclose( file );
1079     }
1080
1081     return i_ret;
1082 }
1083
1084 /*****************************************************************************
1085  * HashSystemInfo: hash system information
1086  *****************************************************************************
1087  * This function computes the MD5 hash of the C: hard drive serial number,
1088  * BIOS version, CPU type and Windows version.
1089  *****************************************************************************/
1090 static int HashSystemInfo( uint32_t *p_system_hash )
1091 {
1092     struct md5_s md5;
1093     int i_ret = 0;
1094
1095     InitMD5( &md5 );
1096
1097 #ifdef WIN32
1098     HKEY i_key;
1099     unsigned int i;
1100     DWORD i_size;
1101     DWORD i_serial;
1102     LPBYTE p_reg_buf;
1103
1104     static LPCTSTR p_reg_keys[ 3 ][ 2 ] =
1105     {
1106         {
1107             _T("HARDWARE\\DESCRIPTION\\System"),
1108             _T("SystemBiosVersion")
1109         },
1110
1111         {
1112             _T("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"),
1113             _T("ProcessorNameString")
1114         },
1115
1116         {
1117             _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion"),
1118             _T("ProductId")
1119         }
1120     };
1121
1122     AddMD5( &md5, "cache-control", 13 );
1123     AddMD5( &md5, "Ethernet", 8 );
1124
1125     GetVolumeInformation( _T("C:\\"), NULL, 0, &i_serial,
1126                           NULL, NULL, NULL, 0 );
1127     AddMD5( &md5, (uint8_t *)&i_serial, 4 );
1128
1129     for( i = 0; i < sizeof(p_reg_keys) / sizeof(p_reg_keys[ 0 ]); i++ )
1130     {
1131         if( RegOpenKeyEx( HKEY_LOCAL_MACHINE, p_reg_keys[ i ][ 0 ],
1132                           0, KEY_READ, &i_key ) != ERROR_SUCCESS )
1133         {
1134             continue;
1135         }
1136
1137         if( RegQueryValueEx( i_key, p_reg_keys[ i ][ 1 ],
1138                              NULL, NULL, NULL, &i_size ) != ERROR_SUCCESS )
1139         {
1140             RegCloseKey( i_key );
1141             continue;
1142         }
1143
1144         p_reg_buf = malloc( i_size );
1145
1146         if( p_reg_buf != NULL )
1147         {
1148             if( RegQueryValueEx( i_key, p_reg_keys[ i ][ 1 ],
1149                                  NULL, NULL, p_reg_buf,
1150                                  &i_size ) == ERROR_SUCCESS )
1151             {
1152                 AddMD5( &md5, (uint8_t *)p_reg_buf, i_size );
1153             }
1154
1155             free( p_reg_buf );
1156         }
1157
1158         RegCloseKey( i_key );
1159     }
1160
1161 #else
1162     i_ret = -1;
1163 #endif
1164
1165     EndMD5( &md5 );
1166     memcpy( p_system_hash, md5.p_digest, 16 );
1167
1168     return i_ret;
1169 }
1170
1171 /*****************************************************************************
1172  * GetiPodID: Get iPod ID
1173  *****************************************************************************
1174  * This function gets the iPod ID.
1175  *****************************************************************************/
1176 static int GetiPodID( long long *p_ipod_id )
1177 {
1178     int i_ret = -1;
1179
1180 #ifdef HAVE_SYSFS_LIBSYSFS_H
1181     struct sysfs_bus *bus = NULL;
1182     struct dlist *devlist = NULL;
1183     struct dlist *attributes = NULL;
1184     struct sysfs_device *curdev = NULL;
1185     struct sysfs_attribute *curattr = NULL;
1186
1187     bus = sysfs_open_bus( "ieee1394" );
1188     if( bus != NULL )
1189     {
1190         devlist = sysfs_get_bus_devices( bus );
1191         if( devlist != NULL )
1192         {
1193             dlist_for_each_data( devlist, curdev, struct sysfs_device )
1194             {
1195                 attributes = sysfs_get_device_attributes( curdev );
1196                 if( attributes != NULL )
1197                 {
1198                     dlist_for_each_data( attributes, curattr,
1199                                          struct sysfs_attribute )
1200                     {
1201                         if( ( strcmp( curattr->name, "model_name" ) == 0 ) &&
1202                             ( strncmp( curattr->value, "iPod", 4 ) == 0 ) )
1203                         {
1204                             *p_ipod_id = strtoll( curdev->name, NULL, 16 );
1205                             i_ret = 0;
1206                             break;
1207                         }
1208                     }
1209                 }
1210
1211                 if( !i_ret ) break;
1212             }
1213         }
1214
1215         sysfs_close_bus( bus );
1216     }
1217 #endif
1218
1219     return i_ret;
1220 }
1221