Merge pull request #487 from mayerwin/patch-1
[mono.git] / mcs / class / Mono.Security / Mono.Security.Protocol.Ntlm / ChallengeResponse2.cs
1 //
2 // Mono.Security.Protocol.Ntlm.ChallengeResponse
3 //      Implements Challenge Response for NTLM v1 and NTLM v2 Session
4 //
5 // Authors:
6 //      Sebastien Pouliot <sebastien@ximian.com>
7 //      Martin Baulig <martin.baulig@xamarin.com>
8 //
9 // (C) 2003 Motus Technologies Inc. (http://www.motus.com)
10 // (C) 2004 Novell (http://www.novell.com)
11 // (C) 2012 Xamarin, Inc. (http://www.xamarin.com)
12 //
13 // References
14 // a.   NTLM Authentication Scheme for HTTP, Ronald Tschalär
15 //      http://www.innovation.ch/java/ntlm.html
16 // b.   The NTLM Authentication Protocol, Copyright © 2003 Eric Glass
17 //      http://davenport.sourceforge.net/ntlm.html
18 //
19
20 //
21 // Permission is hereby granted, free of charge, to any person obtaining
22 // a copy of this software and associated documentation files (the
23 // "Software"), to deal in the Software without restriction, including
24 // without limitation the rights to use, copy, modify, merge, publish,
25 // distribute, sublicense, and/or sell copies of the Software, and to
26 // permit persons to whom the Software is furnished to do so, subject to
27 // the following conditions:
28 // 
29 // The above copyright notice and this permission notice shall be
30 // included in all copies or substantial portions of the Software.
31 // 
32 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
33 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
34 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
35 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
36 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
37 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
38 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
39 //
40
41 using System;
42 using System.IO;
43 using System.Net;
44 using System.Globalization;
45 using System.Security.Cryptography;
46 using System.Text;
47
48 using Mono.Security.Cryptography;
49
50 namespace Mono.Security.Protocol.Ntlm {
51
52         public static class ChallengeResponse2 {
53
54                 static private byte[] magic = { 0x4B, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25 };
55
56                 // This is the pre-encrypted magic value with a null DES key (0xAAD3B435B51404EE)
57                 // Ref: http://packetstormsecurity.nl/Crackers/NT/l0phtcrack/l0phtcrack2.5-readme.html
58                 static private byte[] nullEncMagic = { 0xAA, 0xD3, 0xB4, 0x35, 0xB5, 0x14, 0x04, 0xEE };
59
60                 static byte[] Compute_LM (string password, byte[] challenge)
61                 {
62                         var buffer = new byte [21];
63
64                         // create Lan Manager password
65 #if MOONLIGHT
66                         DESCryptoServiceProvider des = new DESCryptoServiceProvider ();
67 #else
68                         DES des = DES.Create ();
69 #endif
70                         des.Mode = CipherMode.ECB;
71                         ICryptoTransform ct = null;
72                                 
73                         // Note: In .NET DES cannot accept a weak key
74                         // this can happen for a null password
75                         if ((password == null) || (password.Length < 1)) {
76                                 Buffer.BlockCopy (nullEncMagic, 0, buffer, 0, 8);
77                         } else {
78                                 des.Key = PasswordToKey (password, 0);
79                                 ct = des.CreateEncryptor ();
80                                 ct.TransformBlock (magic, 0, 8, buffer, 0);
81                         }
82                                 
83                         // and if a password has less than 8 characters
84                         if ((password == null) || (password.Length < 8)) {
85                                 Buffer.BlockCopy (nullEncMagic, 0, buffer, 8, 8);
86                         } else {
87                                 des.Key = PasswordToKey (password, 7);
88                                 ct = des.CreateEncryptor ();
89                                 ct.TransformBlock (magic, 0, 8, buffer, 8);
90                         }
91                                 
92                         des.Clear ();
93
94                         return GetResponse (challenge, buffer);
95                 }
96
97                 static byte[] Compute_NTLM_Password (string password)
98                 {
99                         var buffer = new byte [21];
100
101                         // create NT password
102 #if MOONLIGHT
103                         MD4Managed md4 = new MD4Managed ();
104 #else
105                         MD4 md4 = MD4.Create ();
106 #endif
107                         byte[] data = ((password == null) ? (new byte [0]) : (Encoding.Unicode.GetBytes (password)));
108                         byte[] hash = md4.ComputeHash (data);
109                         Buffer.BlockCopy (hash, 0, buffer, 0, 16);
110                         
111                         // clean up
112                         Array.Clear (data, 0, data.Length);
113                         Array.Clear (hash, 0, hash.Length);
114
115                         return buffer;
116                 }
117
118                 static byte[] Compute_NTLM (string password, byte[] challenge)
119                 {
120                         var buffer = Compute_NTLM_Password (password);
121                         return GetResponse (challenge, buffer);
122                 }
123
124                 static void Compute_NTLMv2_Session (string password, byte[] challenge,
125                                                     out byte[] lm, out byte[] ntlm)
126                 {
127                         var nonce = new byte [8];
128                         var rng = RandomNumberGenerator.Create ();
129                         rng.GetBytes (nonce);
130
131                         var sessionNonce = new byte [challenge.Length + 8];
132                         challenge.CopyTo (sessionNonce, 0);
133                         nonce.CopyTo (sessionNonce, challenge.Length);
134
135                         lm = new byte [24];
136                         nonce.CopyTo (lm, 0);
137
138 #if MOONLIGHT
139                         MD5Managed md5 = new MD5Managed ();
140 #else
141                         MD5 md5 = MD5.Create ();
142 #endif
143                         
144                         var hash = md5.ComputeHash (sessionNonce);
145                         var newChallenge = new byte [8];
146                         Array.Copy (hash, newChallenge, 8);
147
148                         ntlm = Compute_NTLM (password, newChallenge);
149
150                         // clean up
151                         Array.Clear (nonce, 0, nonce.Length);
152                         Array.Clear (sessionNonce, 0, sessionNonce.Length);
153                         Array.Clear (newChallenge, 0, newChallenge.Length);
154                         Array.Clear (hash, 0, hash.Length);
155                 }
156
157                 static byte[] Compute_NTLMv2 (Type2Message type2, string username, string password)
158                 {
159                         var ntlm_hash = Compute_NTLM_Password (password);
160
161                         var ubytes = Encoding.Unicode.GetBytes (username.ToUpperInvariant ());
162                         var tbytes = Encoding.Unicode.GetBytes (type2.TargetName.ToUpperInvariant ());
163
164                         var bytes = new byte [ubytes.Length + tbytes.Length];
165                         ubytes.CopyTo (bytes, 0);
166                         Array.Copy (tbytes, 0, bytes, ubytes.Length, tbytes.Length);
167
168                         var md5 = new HMACMD5 (ntlm_hash);
169                         var ntlm_v2_hash = md5.ComputeHash (bytes);
170
171                         Array.Clear (ntlm_hash, 0, ntlm_hash.Length);
172                         md5.Clear ();
173
174                         var ntlm_v2_md5 = new HMACMD5 (ntlm_v2_hash);
175
176                         var now = DateTime.Now;
177                         var timestamp = now.Ticks - 504911232000000000;
178                         
179                         var nonce = new byte [8];
180                         var rng = RandomNumberGenerator.Create ();
181                         rng.GetBytes (nonce);
182                         
183                         byte[] blob = new byte [28 + type2.TargetInfo.Length];
184                         blob[0] = 0x01;
185                         blob[1] = 0x01;
186
187                         Buffer.BlockCopy (BitConverterLE.GetBytes (timestamp), 0, blob, 8, 8);
188
189                         Buffer.BlockCopy (nonce, 0, blob, 16, 8);
190                         Buffer.BlockCopy (type2.TargetInfo, 0, blob, 28, type2.TargetInfo.Length);
191
192                         var challenge = type2.Nonce;
193
194                         var hashInput = new byte [challenge.Length + blob.Length];
195                         challenge.CopyTo (hashInput, 0);
196                         blob.CopyTo (hashInput, challenge.Length);
197
198                         var blobHash = ntlm_v2_md5.ComputeHash (hashInput);
199
200                         var response = new byte [blob.Length + blobHash.Length];
201                         blobHash.CopyTo (response, 0);
202                         blob.CopyTo (response, blobHash.Length);
203
204                         Array.Clear (ntlm_v2_hash, 0, ntlm_v2_hash.Length);
205                         ntlm_v2_md5.Clear ();
206                         Array.Clear (nonce, 0, nonce.Length);
207                         Array.Clear (blob, 0, blob.Length);
208                         Array.Clear (hashInput, 0, hashInput.Length);
209                         Array.Clear (blobHash, 0, blobHash.Length);
210
211                         return response;
212                 }
213
214                 public static void Compute (Type2Message type2, NtlmAuthLevel level,
215                                             string username, string password,
216                                             out byte[] lm, out byte[] ntlm)
217                 {
218                         lm = null;
219
220                         switch (level) {
221                         case NtlmAuthLevel.LM_and_NTLM:
222                                 lm = Compute_LM (password, type2.Nonce);
223                                 ntlm = Compute_NTLM (password, type2.Nonce);
224                                 break;
225
226                         case NtlmAuthLevel.LM_and_NTLM_and_try_NTLMv2_Session:
227                                 if ((type2.Flags & NtlmFlags.NegotiateNtlm2Key) == 0)
228                                         goto case NtlmAuthLevel.LM_and_NTLM;
229                                 Compute_NTLMv2_Session (password, type2.Nonce, out lm, out ntlm);
230                                 break;
231
232                         case NtlmAuthLevel.NTLM_only:
233                                 if ((type2.Flags & NtlmFlags.NegotiateNtlm2Key) != 0)
234                                         Compute_NTLMv2_Session (password, type2.Nonce, out lm, out ntlm);
235                                 else
236                                         ntlm = Compute_NTLM (password, type2.Nonce);
237                                 break;
238
239                         case NtlmAuthLevel.NTLMv2_only:
240                                 ntlm = Compute_NTLMv2 (type2, username, password);
241                                 break;
242
243                         default:
244                                 throw new InvalidOperationException ();
245                         }
246                 }
247
248                 static byte[] GetResponse (byte[] challenge, byte[] pwd) 
249                 {
250                         byte[] response = new byte [24];
251 #if MOONLIGHT
252                         DESCryptoServiceProvider des = new DESCryptoServiceProvider ();
253 #else
254                         DES des = DES.Create ();
255 #endif
256                         des.Mode = CipherMode.ECB;
257                         des.Key = PrepareDESKey (pwd, 0);
258                         ICryptoTransform ct = des.CreateEncryptor ();
259                         ct.TransformBlock (challenge, 0, 8, response, 0);
260                         des.Key = PrepareDESKey (pwd, 7);
261                         ct = des.CreateEncryptor ();
262                         ct.TransformBlock (challenge, 0, 8, response, 8);
263                         des.Key = PrepareDESKey (pwd, 14);
264                         ct = des.CreateEncryptor ();
265                         ct.TransformBlock (challenge, 0, 8, response, 16);
266                         return response;
267                 }
268
269                 static byte[] PrepareDESKey (byte[] key56bits, int position) 
270                 {
271                         // convert to 8 bytes
272                         byte[] key = new byte [8];
273                         key [0] = key56bits [position];
274                         key [1] = (byte) ((key56bits [position] << 7)     | (key56bits [position + 1] >> 1));
275                         key [2] = (byte) ((key56bits [position + 1] << 6) | (key56bits [position + 2] >> 2));
276                         key [3] = (byte) ((key56bits [position + 2] << 5) | (key56bits [position + 3] >> 3));
277                         key [4] = (byte) ((key56bits [position + 3] << 4) | (key56bits [position + 4] >> 4));
278                         key [5] = (byte) ((key56bits [position + 4] << 3) | (key56bits [position + 5] >> 5));
279                         key [6] = (byte) ((key56bits [position + 5] << 2) | (key56bits [position + 6] >> 6));
280                         key [7] = (byte)  (key56bits [position + 6] << 1);
281                         return key;
282                 }
283
284                 static byte[] PasswordToKey (string password, int position) 
285                 {
286                         byte[] key7 = new byte [7];
287                         int len = System.Math.Min (password.Length - position, 7);
288                         Encoding.ASCII.GetBytes (password.ToUpper (CultureInfo.CurrentCulture), position, len, key7, 0);
289                         byte[] key8 = PrepareDESKey (key7, 0);
290                         // cleanup intermediate key material
291                         Array.Clear (key7, 0, key7.Length);
292                         return key8;
293                 }
294         }
295 }