]> git.sesse.net Git - rdpsrv/blob - secure.c
Lots of changes: Fix Valgrind hits, send RESULT on license, try to send (encrypted...
[rdpsrv] / secure.c
1 /* -*- c-basic-offset: 8 -*-
2    rdesktop: A Remote Desktop Protocol client.
3    Protocol services - RDP encryption and licensing
4    Copyright (C) Matthew Chapman 1999-2002
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20
21 #include "rdesktop.h"
22
23 #include <openssl/rc4.h>
24 #include <openssl/md5.h>
25 #include <openssl/sha.h>
26 #include <openssl/bn.h>
27 #include <openssl/x509v3.h>
28
29 extern char hostname[16];
30 extern int g_width;
31 extern int g_height;
32 extern int keylayout;
33 extern BOOL g_encryption;
34 extern BOOL g_licence_issued;
35 extern BOOL g_use_rdp5;
36 extern BOOL g_console_session;
37 extern int g_server_bpp;
38 extern uint16 mcs_userid;
39 extern VCHANNEL g_channels[];
40 extern unsigned int g_num_channels;
41
42 static int rc4_key_len;
43 static RC4_KEY rc4_decrypt_key;
44 static RC4_KEY rc4_encrypt_key;
45 static RSA *server_public_key;
46
47 static uint8 sec_sign_key[16];
48 static uint8 sec_decrypt_key[16];
49 static uint8 sec_encrypt_key[16];
50 static uint8 sec_decrypt_update_key[16];
51 static uint8 sec_encrypt_update_key[16];
52 static uint8 sec_crypted_random[SEC_MODULUS_SIZE];
53
54 RSA *privkey;
55
56 uint16 g_server_rdp_version = 0;
57
58 /*
59  * General purpose 48-byte transformation, using two 32-byte salts (generally,
60  * a client and server salt) and a global salt value used for padding.
61  * Both SHA1 and MD5 algorithms are used.
62  */
63 void
64 sec_hash_48(uint8 * out, uint8 * in, uint8 * salt1, uint8 * salt2, uint8 salt)
65 {
66         uint8 shasig[20];
67         uint8 pad[4];
68         SHA_CTX sha;
69         MD5_CTX md5;
70         int i;
71
72         for (i = 0; i < 3; i++)
73         {
74                 memset(pad, salt + i, i + 1);
75
76                 SHA1_Init(&sha);
77                 SHA1_Update(&sha, pad, i + 1);
78                 SHA1_Update(&sha, in, 48);
79                 SHA1_Update(&sha, salt1, 32);
80                 SHA1_Update(&sha, salt2, 32);
81                 SHA1_Final(shasig, &sha);
82
83                 MD5_Init(&md5);
84                 MD5_Update(&md5, in, 48);
85                 MD5_Update(&md5, shasig, 20);
86                 MD5_Final(&out[i * 16], &md5);
87         }
88 }
89
90 /*
91  * Weaker 16-byte transformation, also using two 32-byte salts, but
92  * only using a single round of MD5.
93  */
94 void
95 sec_hash_16(uint8 * out, uint8 * in, uint8 * salt1, uint8 * salt2)
96 {
97         MD5_CTX md5;
98
99         MD5_Init(&md5);
100         MD5_Update(&md5, in, 16);
101         MD5_Update(&md5, salt1, 32);
102         MD5_Update(&md5, salt2, 32);
103         MD5_Final(out, &md5);
104 }
105
106 /* Reduce key entropy from 64 to 40 bits */
107 static void
108 sec_make_40bit(uint8 * key)
109 {
110         key[0] = 0xd1;
111         key[1] = 0x26;
112         key[2] = 0x9e;
113 }
114
115 /* Generate a session key and RC4 keys, given client and server randoms */
116 static void
117 sec_generate_keys(uint8 * client_key, uint8 * server_key, int rc4_key_size)
118 {
119         uint8 session_key[48];
120         uint8 temp_hash[48];
121         uint8 input[48];
122
123         /* Construct input data to hash */
124         memcpy(input, client_key, 24);
125         memcpy(input + 24, server_key, 24);
126
127         /* Generate session key - two rounds of sec_hash_48 */
128         sec_hash_48(temp_hash, input, client_key, server_key, 65);
129         sec_hash_48(session_key, temp_hash, client_key, server_key, 88);
130
131         /* Store first 16 bytes of session key, for generating signatures */
132         memcpy(sec_sign_key, session_key, 16);
133
134         /* Generate RC4 keys */
135         sec_hash_16(sec_decrypt_key, &session_key[16], client_key, server_key);
136         sec_hash_16(sec_encrypt_key, &session_key[32], client_key, server_key);
137
138         if (rc4_key_size == 1)
139         {
140                 DEBUG(("40-bit encryption enabled\n"));
141                 sec_make_40bit(sec_sign_key);
142                 sec_make_40bit(sec_decrypt_key);
143                 sec_make_40bit(sec_encrypt_key);
144                 rc4_key_len = 8;
145         }
146         else
147         {
148                 DEBUG(("rc_4_key_size == %d, 128-bit encryption enabled\n", rc4_key_size));
149                 rc4_key_len = 16;
150         }
151
152         /* Save initial RC4 keys as update keys */
153         memcpy(sec_decrypt_update_key, sec_decrypt_key, 16);
154         memcpy(sec_encrypt_update_key, sec_encrypt_key, 16);
155
156         /* Initialise RC4 state arrays */
157         RC4_set_key(&rc4_decrypt_key, rc4_key_len, sec_decrypt_key);
158         RC4_set_key(&rc4_encrypt_key, rc4_key_len, sec_encrypt_key);
159
160         {
161                 int i;
162                 printf("sec_decrypt_key: ");
163                 for (i = 0; i < 16; ++i)
164                         printf("0x%02x ", sec_decrypt_key[i]);
165                 printf("\n");
166                 
167                 printf("sec_encrypt_key: ");
168                 for (i = 0; i < 16; ++i)
169                         printf("0x%02x ", sec_encrypt_key[i]);
170                 printf("\n");
171         }
172 }
173
174 static uint8 pad_54[40] = {
175         54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54,
176         54, 54, 54,
177         54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54,
178         54, 54, 54
179 };
180
181 static uint8 pad_92[48] = {
182         92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92,
183         92, 92, 92, 92, 92, 92, 92,
184         92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92,
185         92, 92, 92, 92, 92, 92, 92
186 };
187
188 /* Output a uint32 into a buffer (little-endian) */
189 void
190 buf_out_uint32(uint8 * buffer, uint32 value)
191 {
192         buffer[0] = (value) & 0xff;
193         buffer[1] = (value >> 8) & 0xff;
194         buffer[2] = (value >> 16) & 0xff;
195         buffer[3] = (value >> 24) & 0xff;
196 }
197
198 /* Generate a signature hash, using a combination of SHA1 and MD5 */
199 void
200 sec_sign(uint8 * signature, int siglen, uint8 * session_key, int keylen, uint8 * data, int datalen)
201 {
202         uint8 shasig[20];
203         uint8 md5sig[16];
204         uint8 lenhdr[4];
205         SHA_CTX sha;
206         MD5_CTX md5;
207
208         buf_out_uint32(lenhdr, datalen);
209
210         SHA1_Init(&sha);
211         SHA1_Update(&sha, session_key, keylen);
212         SHA1_Update(&sha, pad_54, 40);
213         SHA1_Update(&sha, lenhdr, 4);
214         SHA1_Update(&sha, data, datalen);
215         SHA1_Final(shasig, &sha);
216
217         MD5_Init(&md5);
218         MD5_Update(&md5, session_key, keylen);
219         MD5_Update(&md5, pad_92, 48);
220         MD5_Update(&md5, shasig, 20);
221         MD5_Final(md5sig, &md5);
222
223         memcpy(signature, md5sig, siglen);
224 }
225
226 /* Update an encryption key - similar to the signing process */
227 static void
228 sec_update(uint8 * key, uint8 * update_key)
229 {
230         uint8 shasig[20];
231         SHA_CTX sha;
232         MD5_CTX md5;
233         RC4_KEY update;
234
235         SHA1_Init(&sha);
236         SHA1_Update(&sha, update_key, rc4_key_len);
237         SHA1_Update(&sha, pad_54, 40);
238         SHA1_Update(&sha, key, rc4_key_len);
239         SHA1_Final(shasig, &sha);
240
241         MD5_Init(&md5);
242         MD5_Update(&md5, update_key, rc4_key_len);
243         MD5_Update(&md5, pad_92, 48);
244         MD5_Update(&md5, shasig, 20);
245         MD5_Final(key, &md5);
246
247         RC4_set_key(&update, rc4_key_len, key);
248         RC4(&update, rc4_key_len, key, key);
249
250         if (rc4_key_len == 8)
251                 sec_make_40bit(key);
252 }
253
254 /* Encrypt data using RC4 */
255 static void
256 sec_encrypt(uint8 * data, int length)
257 {
258         static int use_count;
259
260         if (use_count == 4096)
261         {
262                 sec_update(sec_decrypt_key, sec_decrypt_update_key);
263                 RC4_set_key(&rc4_decrypt_key, rc4_key_len, sec_decrypt_key);
264                 use_count = 0;
265         }
266
267         RC4(&rc4_decrypt_key, length, data, data);
268         use_count++;
269 }
270
271 /* Decrypt data using RC4 */
272 void
273 sec_decrypt(uint8 * data, int length)
274 {
275         static int use_count;
276
277         if (use_count == 4096)
278         {
279                 sec_update(sec_encrypt_key, sec_encrypt_update_key);
280                 RC4_set_key(&rc4_encrypt_key, rc4_key_len, sec_encrypt_key);
281                 use_count = 0;
282         }
283
284         RC4(&rc4_encrypt_key, length, data, data);
285         use_count++;
286 }
287
288 static void
289 reverse(uint8 * p, int len)
290 {
291         int i, j;
292         uint8 temp;
293
294         for (i = 0, j = len - 1; i < j; i++, j--)
295         {
296                 temp = p[i];
297                 p[i] = p[j];
298                 p[j] = temp;
299         }
300 }
301
302 /* Perform an RSA public key encryption operation */
303 static void
304 sec_rsa_encrypt(uint8 * out, uint8 * in, int len, uint8 * modulus, uint8 * exponent)
305 {
306         BN_CTX *ctx;
307         BIGNUM mod, exp, x, y;
308         uint8 inr[SEC_MODULUS_SIZE];
309         int outlen;
310
311         reverse(modulus, SEC_MODULUS_SIZE);
312         reverse(exponent, SEC_EXPONENT_SIZE);
313         memcpy(inr, in, len);
314         reverse(inr, len);
315
316         ctx = BN_CTX_new();
317         BN_init(&mod);
318         BN_init(&exp);
319         BN_init(&x);
320         BN_init(&y);
321
322         BN_bin2bn(modulus, SEC_MODULUS_SIZE, &mod);
323         BN_bin2bn(exponent, SEC_EXPONENT_SIZE, &exp);
324         BN_bin2bn(inr, len, &x);
325         BN_mod_exp(&y, &x, &exp, &mod, ctx);
326         outlen = BN_bn2bin(&y, out);
327         reverse(out, outlen);
328         if (outlen < SEC_MODULUS_SIZE)
329                 memset(out + outlen, 0, SEC_MODULUS_SIZE - outlen);
330
331         BN_free(&y);
332         BN_clear_free(&x);
333         BN_free(&exp);
334         BN_free(&mod);
335         BN_CTX_free(ctx);
336 }
337
338 /* Initialise secure transport packet */
339 STREAM
340 sec_init(uint32 flags, int maxlen)
341 {
342         int hdrlen;
343         STREAM s;
344
345         if (!g_licence_issued) 
346                 hdrlen = (flags & SEC_ENCRYPT) ? 12 : 4;
347         else
348                 hdrlen = (flags & SEC_ENCRYPT) ? 12 : 0; 
349         s = mcs_init(maxlen + hdrlen);
350         s_push_layer(s, sec_hdr, hdrlen);
351
352         return s;
353 }
354
355 /* Transmit secure transport packet over specified channel */
356 void
357 sec_send_to_channel(STREAM s, uint32 flags, uint16 channel)
358 {
359         int datalen;
360
361 //      DEBUG(("sending packet to channel %u\n", channel));
362         
363         s_pop_layer(s, sec_hdr);
364         if (!g_licence_issued || (flags & SEC_ENCRYPT)) {
365                 out_uint32_le(s, flags);
366         }
367
368         if (flags & SEC_ENCRYPT)
369         {
370                 flags &= ~SEC_ENCRYPT;
371                 datalen = s->end - s->p - 8;
372
373 #if WITH_DEBUG
374                 DEBUG(("Sending encrypted packet:\n"));
375                 hexdump(s->p + 8, datalen);
376 #endif
377
378                 sec_sign(s->p, 8, sec_sign_key, rc4_key_len, s->p + 8, datalen);
379                 printf("First byte of signature is 0x%x, at %p\n", (s->p)[0], s->p);
380                 sec_encrypt(s->p + 8, datalen);
381         }
382
383         mcs_send_to_channel(s, channel);
384 }
385
386 /* Transmit secure transport packet */
387
388 void
389 sec_send(STREAM s, uint32 flags)
390 {
391         sec_send_to_channel(s, flags, MCS_GLOBAL_CHANNEL);
392 }
393
394
395 /* Transfer the client random to the server */
396 static void
397 sec_establish_key(void)
398 {
399         uint32 length = SEC_MODULUS_SIZE + SEC_PADDING_SIZE;
400         uint32 flags = SEC_CLIENT_RANDOM;
401         STREAM s;
402
403         s = sec_init(flags, 76);
404
405         out_uint32_le(s, length);
406         out_uint8p(s, sec_crypted_random, SEC_MODULUS_SIZE);
407         out_uint8s(s, SEC_PADDING_SIZE);
408
409         s_mark_end(s);
410         sec_send(s, flags);
411 }
412
413 /* Parse a public key structure */
414 static BOOL
415 sec_parse_public_key(STREAM s, uint8 ** modulus, uint8 ** exponent)
416 {
417         uint32 magic, modulus_len;
418
419         in_uint32_le(s, magic);
420         if (magic != SEC_RSA_MAGIC)
421         {
422                 error("RSA magic 0x%x\n", magic);
423                 return False;
424         }
425
426         in_uint32_le(s, modulus_len);
427         if (modulus_len != SEC_MODULUS_SIZE + SEC_PADDING_SIZE)
428         {
429                 error("modulus len 0x%x\n", modulus_len);
430                 return False;
431         }
432
433         in_uint8s(s, 8);        /* modulus_bits, unknown */
434         in_uint8p(s, *exponent, SEC_EXPONENT_SIZE);
435         in_uint8p(s, *modulus, SEC_MODULUS_SIZE);
436         in_uint8s(s, SEC_PADDING_SIZE);
437
438         return s_check(s);
439 }
440
441 static BOOL
442 sec_parse_x509_key(X509 * cert)
443 {
444         EVP_PKEY *epk = NULL;
445         /* By some reason, Microsoft sets the OID of the Public RSA key to
446            the oid for "MD5 with RSA Encryption" instead of "RSA Encryption"
447
448            Kudos to Richard Levitte for the following (. intiutive .) 
449            lines of code that resets the OID and let's us extract the key. */
450         if (OBJ_obj2nid(cert->cert_info->key->algor->algorithm) == NID_md5WithRSAEncryption)
451         {
452                 DEBUG_RDP5(("Re-setting algorithm type to RSA in server certificate\n"));
453                 cert->cert_info->key->algor->algorithm = OBJ_nid2obj(NID_rsaEncryption);
454         }
455         epk = X509_get_pubkey(cert);
456         if (NULL == epk)
457         {
458                 error("Failed to extract public key from certificate\n");
459                 return False;
460         }
461
462         server_public_key = (RSA *) epk->pkey.ptr;
463
464         return True;
465 }
466
467
468 /* Parse a crypto information structure */
469 static BOOL
470 sec_parse_crypt_info(STREAM s, uint32 * rc4_key_size,
471                      uint8 ** server_random, uint8 ** modulus, uint8 ** exponent)
472 {
473         uint32 crypt_level, random_len, rsa_info_len;
474         uint32 cacert_len, cert_len, flags;
475         X509 *cacert, *server_cert;
476         uint16 tag, length;
477         uint8 *next_tag, *end;
478
479         in_uint32_le(s, *rc4_key_size); /* 1 = 40-bit, 2 = 128-bit */
480         in_uint32_le(s, crypt_level);   /* 1 = low, 2 = medium, 3 = high */
481         if (crypt_level == 0)   /* no encryption */
482                 return False;
483         in_uint32_le(s, random_len);
484         in_uint32_le(s, rsa_info_len);
485
486         if (random_len != SEC_RANDOM_SIZE)
487         {
488                 error("random len %d, expected %d\n", random_len, SEC_RANDOM_SIZE);
489                 return False;
490         }
491
492         in_uint8p(s, *server_random, random_len);
493
494         /* RSA info */
495         end = s->p + rsa_info_len;
496         if (end > s->end)
497                 return False;
498
499         in_uint32_le(s, flags); /* 1 = RDP4-style, 0x80000002 = X.509 */
500         if (flags & 1)
501         {
502                 DEBUG_RDP5(("We're going for the RDP4-style encryption\n"));
503                 in_uint8s(s, 8);        /* unknown */
504
505                 while (s->p < end)
506                 {
507                         in_uint16_le(s, tag);
508                         in_uint16_le(s, length);
509
510                         next_tag = s->p + length;
511
512                         switch (tag)
513                         {
514                                 case SEC_TAG_PUBKEY:
515                                         if (!sec_parse_public_key(s, modulus, exponent))
516                                                 return False;
517                                         DEBUG_RDP5(("Got Public key, RDP4-style\n"));
518
519                                         break;
520
521                                 case SEC_TAG_KEYSIG:
522                                         /* Is this a Microsoft key that we just got? */
523                                         /* Care factor: zero! */
524                                         /* Actually, it would probably be a good idea to check if the public key is signed with this key, and then store this 
525                                            key as a known key of the hostname. This would prevent some MITM-attacks. */
526                                         break;
527
528                                 default:
529                                         unimpl("crypt tag 0x%x\n", tag);
530                         }
531
532                         s->p = next_tag;
533                 }
534         }
535         else
536         {
537                 uint32 certcount;
538
539                 DEBUG_RDP5(("We're going for the RDP5-style encryption\n"));
540                 in_uint32_le(s, certcount); /* Number of certificates */
541
542                 if(certcount < 2) 
543                 {
544                         error("Server didn't send enough X509 certificates\n");
545                         return False;
546                 }
547
548                 for(; certcount > 2; certcount--)
549                 { /* ignore all the certificates between the root and the signing CA */
550                         uint32 ignorelen;
551                         X509 *ignorecert;
552
553                         DEBUG_RDP5(("Ignored certs left: %d\n", certcount));
554
555                         in_uint32_le(s, ignorelen);
556                         DEBUG_RDP5(("Ignored Certificate length is %d\n", ignorelen));
557                         ignorecert = d2i_X509(NULL, &(s->p), ignorelen);
558
559                         if(ignorecert == NULL)
560                         { /* XXX: error out? */
561                                 DEBUG_RDP5(("got a bad cert: this will probably screw up the rest of the communication\n"));
562                         }
563
564 #ifdef WITH_DEBUG_RDP5
565                         DEBUG_RDP5(("cert #%d (ignored):\n",certcount));
566                         X509_print_fp(stdout, ignorecert);
567 #endif
568                 }
569
570                 /* Do da funky X.509 stuffy 
571
572                    "How did I find out about this?  I looked up and saw a
573                    bright light and when I came to I had a scar on my forehead
574                    and knew about X.500"
575                    - Peter Gutman in a early version of 
576                    http://www.cs.auckland.ac.nz/~pgut001/pubs/x509guide.txt
577                  */
578
579                 in_uint32_le(s, cacert_len);
580                 DEBUG_RDP5(("CA Certificate length is %d\n", cacert_len));
581                 cacert = d2i_X509(NULL, &(s->p), cacert_len);
582                 /* Note: We don't need to move s->p here - d2i_X509 is
583                    "kind" enough to do it for us */
584                 if (NULL == cacert)
585                 {
586                         error("Couldn't load CA Certificate from server\n");
587                         return False;
588                 }
589
590                 /* Currently, we don't use the CA Certificate. 
591                    FIXME: 
592                    *) Verify the server certificate (server_cert) with the 
593                    CA certificate.
594                    *) Store the CA Certificate with the hostname of the 
595                    server we are connecting to as key, and compare it
596                    when we connect the next time, in order to prevent
597                    MITM-attacks.
598                  */
599
600                 in_uint32_le(s, cert_len);
601                 DEBUG_RDP5(("Certificate length is %d\n", cert_len));
602                 server_cert = d2i_X509(NULL, &(s->p), cert_len);
603                 if (NULL == server_cert)
604                 {
605                         error("Couldn't load Certificate from server\n");
606                         return False;
607                 }
608
609                 in_uint8s(s, 16);       /* Padding */
610
611                 /* Note: Verifying the server certificate must be done here, 
612                    before sec_parse_public_key since we'll have to apply
613                    serious violence to the key after this */
614
615                 if (!sec_parse_x509_key(server_cert))
616                 {
617                         DEBUG_RDP5(("Didn't parse X509 correctly\n"));
618                         return False;
619                 }
620                 return True;    /* There's some garbage here we don't care about */
621         }
622         return s_check_end(s);
623 }
624
625 /* Process crypto information blob */
626 static void
627 sec_process_crypt_info(STREAM s)
628 {
629         uint8 *server_random, *modulus, *exponent;
630         uint8 client_random[SEC_RANDOM_SIZE];
631         uint32 rc4_key_size;
632         uint8 inr[SEC_MODULUS_SIZE];
633
634         if (!sec_parse_crypt_info(s, &rc4_key_size, &server_random, &modulus, &exponent))
635         {
636                 DEBUG(("Failed to parse crypt info\n"));
637                 return;
638         }
639
640         DEBUG(("Generating client random\n"));
641         /* Generate a client random, and hence determine encryption keys */
642         /* This is what the MS client do: */
643         memset(inr, 0, SEC_RANDOM_SIZE);
644         /*  *ARIGL!* Plaintext attack, anyone?
645            I tried doing:
646            generate_random(inr);
647            ..but that generates connection errors now and then (yes, 
648            "now and then". Something like 0 to 3 attempts needed before a 
649            successful connection. Nice. Not! 
650          */
651
652         generate_random(client_random);
653         if (NULL != server_public_key)
654         {                       /* Which means we should use 
655                                    RDP5-style encryption */
656
657                 memcpy(inr + SEC_RANDOM_SIZE, client_random, SEC_RANDOM_SIZE);
658                 reverse(inr + SEC_RANDOM_SIZE, SEC_RANDOM_SIZE);
659
660                 RSA_public_encrypt(SEC_MODULUS_SIZE,
661                                    inr, sec_crypted_random, server_public_key, RSA_NO_PADDING);
662
663                 reverse(sec_crypted_random, SEC_MODULUS_SIZE);
664
665         }
666         else
667         {                       /* RDP4-style encryption */
668                 sec_rsa_encrypt(sec_crypted_random,
669                                 client_random, SEC_RANDOM_SIZE, modulus, exponent);
670         }
671         sec_generate_keys(client_random, server_random, rc4_key_size);
672 }
673
674
675 /* Process SRV_INFO, find RDP version supported by server */
676 static void
677 sec_process_srv_info(STREAM s)
678 {
679         in_uint16_le(s, g_server_rdp_version);
680         DEBUG_RDP5(("Server RDP version is %d\n", g_server_rdp_version));
681 /*      if (1 == g_server_rdp_version)
682                 g_use_rdp5 = 0; */
683 }
684
685
686 /* Process connect response data blob */
687 void
688 sec_process_mcs_data(STREAM s)
689 {
690         uint16 tag, length;
691         uint8 *next_tag;
692         uint8 len;
693
694         in_uint8s(s, 21);       /* header (T.124 stuff, probably) */
695         in_uint8(s, len);
696         if (len & 0x80)
697                 in_uint8(s, len);
698
699         while (s->p < s->end)
700         {
701                 in_uint16_le(s, tag);
702                 in_uint16_le(s, length);
703
704                 if (length <= 4)
705                         return;
706
707                 next_tag = s->p + length - 4;
708
709                 switch (tag)
710                 {
711                         case SEC_TAG_SRV_INFO:
712                                 sec_process_srv_info(s);
713                                 break;
714
715                         case SEC_TAG_SRV_CRYPT:
716                                 sec_process_crypt_info(s);
717                                 break;
718
719                         case SEC_TAG_SRV_CHANNELS:
720                                 /* FIXME: We should parse this information and
721                                    use it to map RDP5 channels to MCS 
722                                    channels */
723                                 break;
724
725                         default:
726                                 unimpl("response tag 0x%x\n", tag);
727                 }
728
729                 s->p = next_tag;
730         }
731 }
732
733 extern unsigned char cacert[];
734 extern BOOL g_licence_issued;
735
736 unsigned char demand_license[] = {
737         0x01, 0x03, 0x86, 0x00, 0x9c, 0x6e, 0xef, 0x5a, 0x26, 0x45, 0x88, 0x86, 0x0e, 0xdf, 0xa4, 0x4a,
738         0x45, 0xc7, 0x5a, 0x4c, 0xec, 0x33, 0xff, 0x4c, 0xd8, 0x4b, 0xd2, 0x4e, 0xd2, 0x22, 0x16, 0xde,
739         0x1e, 0x5b, 0x06, 0x6e, 0x00, 0x00, 0x05, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x4d, 0x00, 0x69, 0x00,
740         0x63, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x73, 0x00, 0x6f, 0x00, 0x66, 0x00, 0x74, 0x00, 0x20, 0x00,
741         0x43, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x70, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x61, 0x00, 0x74, 0x00,
742         0x69, 0x00, 0x6f, 0x00, 0x6e, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x41, 0x00, 0x30, 0x00,
743         0x32, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0xf6, 0x00, 0x00,
744         0x01, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x0e, 0x00, 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x73, 0x6f, 0x66,
745         0x74, 0x2e, 0x63, 0x6f, 0x6d, 0x00 
746 };
747 unsigned char result_license[] = {
748         0xff, 0x03, 0x10, 0x00, 0x07, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0xa0, 0x5f, 0x00, 0x00
749 };
750
751 unsigned char demand_active[] = {
752         0x24, 0x01, 0x11, 0x00, 0xea, 0x03, 0xea, 0x03, 0x01, 0x00, 0x04, 0x00, 0x0e, 0x01, 0x52, 0x44,
753         0x50, 0x00, 0x09, 0x00, 0x00, 0x00, 0x09, 0x00, 0x08, 0x00, 0xea, 0x03, 0x40, 0xe4, 0x01, 0x00,
754         0x18, 0x00, 0x01, 0x00, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x11, 0x04, 0x00, 0x00,
755         0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x0e, 0x00, 0x04, 0x00, 0x02, 0x00, 0x1c, 0x00, 0x08, 0x00,
756         0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x20, 0x03, 0x58, 0x02, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00,
757         0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x58, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
758         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x42, 0x0f, 0x00, 0x01, 0x00,
759         0x14, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x22, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00,
760         0x00, 0x00, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
761         0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0xa1, 0x06, 0x00, 0x00, 0x40, 0x42,
762         0x0f, 0x00, 0x40, 0x42, 0x0f, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00,
763         0x08, 0x00, 0x06, 0x00, 0x00, 0x00, 0x12, 0x00, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00,
764         0x0a, 0x00, 0x01, 0x00, 0x19, 0x00, 0x19, 0x00, 0x0d, 0x00, 0x58, 0x00, 0x35, 0x00, 0x00, 0x00,
765         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xed, 0xbf, 0xa5, 0xcd, 0xb1, 0xae, 0xbe,
766         0x88, 0x35, 0x56, 0xe5, 0xc2, 0x01, 0xaf, 0xbe, 0xc8, 0xed, 0xbf, 0xa5, 0x8c, 0x33, 0x40, 0xe4,
767         0x08, 0x30, 0x40, 0xe4, 0x01, 0x00, 0x00, 0x00, 0x08, 0x30, 0x40, 0xe4, 0x00, 0x00, 0x00, 0x00,
768         0xc0, 0xed, 0xbf, 0xa5, 0x34, 0xf5, 0xae, 0xbe, 0x08, 0x30, 0x40, 0xe4, 0xb4, 0xed, 0xbf, 0xa5,
769         0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x19, 0x00, 0x19, 0x00, 0x00, 0x00,
770         0x00, 0x00, 0x00, 0x00
771 };
772
773 #define EXPECT8(value) { in_uint8(s, unknown); if (unknown != (value)) printf("Unknown value on code line %u; expected 0x%x, got 0x%x\n", __LINE__, (value), unknown); }
774 #define EXPECT16(value) { in_uint16_le(s, unknown); if (unknown != (value)) printf("Unknown value on code line %u; expected 0x%x, got 0x%x\n", __LINE__, (value), unknown); }
775 #define EXPECT32(value) { in_uint32_le(s, unknown); if (unknown != (value)) printf("Unknown value on code line %u; expected 0x%x, got 0x%x\n", __LINE__, (value), unknown); }
776
777 void
778 process_presented_license(STREAM s)
779 {
780         unsigned char client_license_random[SEC_RANDOM_SIZE];
781         unsigned char client_license_rsa_data[SEC_MODULUS_SIZE];
782
783         uint16 length, license_size;
784         uint32 unknown;
785         uint8 *license, hwid[LICENCE_HWID_SIZE], signature[LICENCE_SIGNATURE_SIZE];
786         int i;
787         
788         EXPECT8(2);                   // version
789         in_uint16_le(s, length);
790
791         EXPECT32(1);                  // unknown
792         EXPECT16(0);
793         EXPECT16(0x0201);
794
795         in_uint8a(s, client_license_random, SEC_RANDOM_SIZE);
796         EXPECT16(0);
797         EXPECT16(SEC_MODULUS_SIZE + SEC_PADDING_SIZE);
798         in_uint8a(s, client_license_rsa_data, SEC_MODULUS_SIZE);
799         in_uint8s(s, SEC_PADDING_SIZE);
800
801         EXPECT16(1);
802         in_uint16_le(s, license_size);
803
804         license = (uint8 *)xmalloc(license_size);
805         in_uint8a(s, license, license_size);
806
807         printf("Received license:\n");
808         for (i = 0; i < license_size; ++i)
809                 printf(" 0x%02x", license[i]);
810         printf("\n");
811
812         EXPECT16(1);
813         EXPECT16(LICENCE_HWID_SIZE);
814         in_uint8a(s, hwid, LICENCE_HWID_SIZE);
815
816         printf("License hardware ID:\n");
817         for (i = 0; i < LICENCE_HWID_SIZE; ++i)
818                 printf(" 0x%02x", hwid[i]);
819         printf("\n");
820
821         in_uint8a(s, signature, LICENCE_SIGNATURE_SIZE);
822
823         if (!s_check_end(s)) {
824                 printf("Unknown data at the end of presented license!");
825         }
826
827         // now we can generate the keys we need
828         licence_generate_keys(client_license_random, demand_license + 4, client_license_rsa_data);
829 //      send_authreq();
830 }
831
832 /* Receive secure transport packet */
833 STREAM
834 sec_recv(void)
835 {
836         uint32 sec_flags;
837         uint16 channel;
838         STREAM s;
839
840         while ((s = mcs_recv(&channel)) != NULL)
841         {
842                 if (/*g_encryption || !g_licence_issued*/ 1)
843                 {
844                         in_uint32_le(s, sec_flags);
845                         printf("sec_flags=%x\n", sec_flags);
846                         
847                         if (sec_flags & SEC_ENCRYPT)
848                         {
849                                 printf("encrypt\n");
850                                 in_uint8s(s, 8);        /* signature */
851                                 sec_decrypt(s->p, s->end - s->p);
852                         }
853
854                         if (sec_flags & SEC_LICENCE_NEG)
855                         {
856                                 uint8 tag;
857                                 in_uint8(s, tag);
858                                 printf("SEC_LICENSE_NEG tag %x\n", tag);
859                                 
860                                 if (tag == LICENCE_TAG_PRESENT) {
861                                         process_presented_license(s);
862
863                                         s = sec_init(sizeof(result_license), SEC_LICENCE_NEG);
864                                         out_uint8p(s, result_license, sizeof(result_license));
865                                         s_mark_end(s);
866                                         sec_send(s, SEC_LICENCE_NEG);
867                                         
868                                         //g_licence_issued = 1;
869                                         
870                                         printf("Sending DEMAND_ACTIVE (0x%x bytes)\n", sizeof(demand_active));
871                                         s = sec_init(sizeof(demand_active), SEC_ENCRYPT);
872                                         out_uint8p(s, demand_active, sizeof(demand_active));
873                                         s_mark_end(s);
874                                         sec_send(s, SEC_ENCRYPT);
875                                 }
876                                 
877                                 continue;
878                         }
879
880                         if (sec_flags & SEC_LOGON_INFO) 
881                         {
882                                 printf("Received logon packet!\n");
883                                 rdp_get_logon_info(s);
884                         
885                                 // demand a license
886                                 {
887                                         STREAM s;
888
889                                         s = sec_init(sizeof(demand_license), SEC_LICENCE_NEG);
890                                         out_uint8p(s, demand_license, sizeof(demand_license));
891                                         s_mark_end(s);
892                                         sec_send(s, SEC_LICENCE_NEG);
893                                 }
894                                 
895                                 continue;
896                         }
897
898                         if (sec_flags & SEC_CLIENT_RANDOM) {
899                                 uint32 length;
900                                 uint8 inr[SEC_MODULUS_SIZE];
901                                 int i;
902                                 
903                                 printf("Receiving the client random!\n");
904                                 in_uint32_le(s, length);
905                                 if (length != SEC_MODULUS_SIZE + SEC_PADDING_SIZE) {
906                                         error("Client random was wrong size, %u bytes\n", length);
907                                 }
908                                 in_uint8a(s, sec_crypted_random, SEC_MODULUS_SIZE);
909                                 in_uint8s(s, SEC_PADDING_SIZE);
910                                 if (!s_check_end(s)) {
911                                         error("Junk after client random\n");
912                                 }
913                                 
914                                 reverse(sec_crypted_random, SEC_MODULUS_SIZE);
915
916                                 RSA_private_decrypt(SEC_MODULUS_SIZE, sec_crypted_random, inr, privkey, RSA_NO_PADDING);
917                         
918                                 reverse(inr + SEC_RANDOM_SIZE, SEC_RANDOM_SIZE);
919                                 
920                                 printf("Unencrypted client random: ");
921                                 for (i = 0; i < SEC_RANDOM_SIZE; ++i) {
922                                         printf("0x%x ", inr[i + SEC_RANDOM_SIZE]);
923                                 }
924                                 printf("\n");
925
926                                 // now we can generate the keys
927                                 sec_generate_keys(inr + SEC_RANDOM_SIZE, cacert, 1);
928                                 continue;
929                         }
930                 }
931
932                 printf("Received MCS data on ch %u\n", channel);
933                 if (channel != MCS_GLOBAL_CHANNEL)
934                 {
935                         channel_process(s, channel);
936                         continue;
937                 }
938
939                 return s;
940         }
941
942         return NULL;
943 }
944
945 /* Disconnect a connection */
946 void
947 sec_disconnect(void)
948 {
949         mcs_disconnect();
950 }