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