This repository has been archived by the owner on Mar 20, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 733
/
MessagingUtilities.cs
2031 lines (1817 loc) · 86.1 KB
/
MessagingUtilities.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-----------------------------------------------------------------------
// <copyright file="MessagingUtilities.cs" company="Outercurve Foundation">
// Copyright (c) Outercurve Foundation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace DotNetOpenAuth.Messaging {
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
#if CLR4
using System.Net.Http;
#endif
using System.Net.Mime;
using System.Runtime.Serialization.Json;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.Messaging.Reflection;
/// <summary>
/// A grab-bag of utility methods useful for the channel stack of the protocol.
/// </summary>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Utility class touches lots of surface area")]
public static class MessagingUtilities {
/// <summary>
/// The cryptographically strong random data generator used for creating secrets.
/// </summary>
/// <remarks>The random number generator is thread-safe.</remarks>
internal static readonly RandomNumberGenerator CryptoRandomDataGenerator = new RNGCryptoServiceProvider();
/// <summary>
/// A pseudo-random data generator (NOT cryptographically strong random data)
/// </summary>
internal static readonly Random NonCryptoRandomDataGenerator = new Random();
/// <summary>
/// The uppercase alphabet.
/// </summary>
internal const string UppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/// <summary>
/// The lowercase alphabet.
/// </summary>
internal const string LowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
/// <summary>
/// The set of base 10 digits.
/// </summary>
internal const string Digits = "0123456789";
/// <summary>
/// The set of digits and alphabetic letters (upper and lowercase).
/// </summary>
internal const string AlphaNumeric = UppercaseLetters + LowercaseLetters + Digits;
/// <summary>
/// All the characters that are allowed for use as a base64 encoding character.
/// </summary>
internal const string Base64Characters = AlphaNumeric + "+" + "/";
/// <summary>
/// All the characters that are allowed for use as a base64 encoding character
/// in the "web safe" context.
/// </summary>
internal const string Base64WebSafeCharacters = AlphaNumeric + "-" + "_";
/// <summary>
/// The set of digits, and alphabetic letters (upper and lowercase) that are clearly
/// visually distinguishable.
/// </summary>
internal const string AlphaNumericNoLookAlikes = "23456789abcdefghjkmnpqrstwxyzABCDEFGHJKMNPQRSTWXYZ";
/// <summary>
/// The length of private symmetric secret handles.
/// </summary>
/// <remarks>
/// This value needn't be high, as we only expect to have a small handful of unexpired secrets at a time,
/// and handle recycling is permissible.
/// </remarks>
private const int SymmetricSecretHandleLength = 4;
/// <summary>
/// The default lifetime of a private secret.
/// </summary>
private static readonly TimeSpan SymmetricSecretKeyLifespan = Configuration.DotNetOpenAuthSection.Messaging.PrivateSecretMaximumAge;
/// <summary>
/// A character array containing just the = character.
/// </summary>
private static readonly char[] EqualsArray = new char[] { '=' };
/// <summary>
/// A character array containing just the , character.
/// </summary>
private static readonly char[] CommaArray = new char[] { ',' };
/// <summary>
/// A character array containing just the " character.
/// </summary>
private static readonly char[] QuoteArray = new char[] { '"' };
/// <summary>
/// The set of characters that are unreserved in RFC 2396 but are NOT unreserved in RFC 3986.
/// </summary>
private static readonly string[] UriRfc3986CharsToEscape = new[] { "!", "*", "'", "(", ")" };
/// <summary>
/// A set of escaping mappings that help secure a string from javscript execution.
/// </summary>
/// <remarks>
/// The characters to escape here are inspired by
/// http://code.google.com/p/doctype/wiki/ArticleXSSInJavaScript
/// </remarks>
private static readonly Dictionary<string, string> javascriptStaticStringEscaping = new Dictionary<string, string> {
{ "\\", @"\\" }, // this WAS just above the & substitution but we moved it here to prevent double-escaping
{ "\t", @"\t" },
{ "\n", @"\n" },
{ "\r", @"\r" },
{ "\u0085", @"\u0085" },
{ "\u2028", @"\u2028" },
{ "\u2029", @"\u2029" },
{ "'", @"\x27" },
{ "\"", @"\x22" },
{ "&", @"\x26" },
{ "<", @"\x3c" },
{ ">", @"\x3e" },
{ "=", @"\x3d" },
};
/// <summary>
/// The available compression algorithms.
/// </summary>
internal enum CompressionMethod {
/// <summary>
/// The Deflate algorithm.
/// </summary>
Deflate,
/// <summary>
/// The GZip algorithm.
/// </summary>
Gzip,
}
/// <summary>
/// Transforms an OutgoingWebResponse to an MVC-friendly ActionResult.
/// </summary>
/// <param name="response">The response to send to the user agent.</param>
/// <returns>The <see cref="ActionResult"/> instance to be returned by the Controller's action method.</returns>
public static ActionResult AsActionResult(this OutgoingWebResponse response) {
Requires.NotNull(response, "response");
return new OutgoingWebResponseActionResult(response);
}
#if CLR4
/// <summary>
/// Transforms an OutgoingWebResponse to a Web API-friendly HttpResponseMessage.
/// </summary>
/// <param name="outgoingResponse">The response to send to the user agent.</param>
/// <returns>The <see cref="HttpResponseMessage"/> instance to be returned by the Web API method.</returns>
public static HttpResponseMessage AsHttpResponseMessage(this OutgoingWebResponse outgoingResponse) {
HttpResponseMessage response = new HttpResponseMessage(outgoingResponse.Status) {
Content = new StreamContent(outgoingResponse.ResponseStream)
};
var responseHeaders = outgoingResponse.Headers;
foreach (var header in responseHeaders.AllKeys) {
if (!response.Headers.TryAddWithoutValidation(header, responseHeaders[header])) {
response.Content.Headers.TryAddWithoutValidation(header, responseHeaders[header]);
}
}
return response;
}
#endif
/// <summary>
/// Gets the original request URL, as seen from the browser before any URL rewrites on the server if any.
/// Cookieless session directory (if applicable) is also included.
/// </summary>
/// <returns>The URL in the user agent's Location bar.</returns>
[SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "The Uri merging requires use of a string value.")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Expensive call should not be a property.")]
public static Uri GetRequestUrlFromContext() {
Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
return new HttpRequestWrapper(HttpContext.Current.Request).GetPublicFacingUrl();
}
/// <summary>
/// Strips any and all URI query parameters that start with some prefix.
/// </summary>
/// <param name="uri">The URI that may have a query with parameters to remove.</param>
/// <param name="prefix">The prefix for parameters to remove. A period is NOT automatically appended.</param>
/// <returns>Either a new Uri with the parameters removed if there were any to remove, or the same Uri instance if no parameters needed to be removed.</returns>
public static Uri StripQueryArgumentsWithPrefix(this Uri uri, string prefix) {
Requires.NotNull(uri, "uri");
Requires.NotNullOrEmpty(prefix, "prefix");
NameValueCollection queryArgs = HttpUtility.ParseQueryString(uri.Query);
var matchingKeys = queryArgs.Keys.OfType<string>().Where(key => key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
if (matchingKeys.Count > 0) {
UriBuilder builder = new UriBuilder(uri);
foreach (string key in matchingKeys) {
queryArgs.Remove(key);
}
builder.Query = CreateQueryString(queryArgs.ToDictionary());
return builder.Uri;
} else {
return uri;
}
}
/// <summary>
/// Sends a multipart HTTP POST request (useful for posting files).
/// </summary>
/// <param name="request">The HTTP request.</param>
/// <param name="requestHandler">The request handler.</param>
/// <param name="parts">The parts to include in the POST entity.</param>
/// <returns>The HTTP response.</returns>
public static IncomingWebResponse PostMultipart(this HttpWebRequest request, IDirectWebRequestHandler requestHandler, IEnumerable<MultipartPostPart> parts) {
Requires.NotNull(request, "request");
Requires.NotNull(requestHandler, "requestHandler");
Requires.NotNull(parts, "parts");
PostMultipartNoGetResponse(request, requestHandler, parts);
return requestHandler.GetResponse(request);
}
/// <summary>
/// Assembles a message comprised of the message on a given exception and all inner exceptions.
/// </summary>
/// <param name="exception">The exception.</param>
/// <returns>The assembled message.</returns>
public static string ToStringDescriptive(this Exception exception) {
// The input being null is probably bad, but since this method is called
// from a catch block, we don't really want to throw a new exception and
// hide the details of this one.
if (exception == null) {
Logger.Messaging.Error("MessagingUtilities.GetAllMessages called with null input.");
}
StringBuilder message = new StringBuilder();
while (exception != null) {
message.Append(exception.Message);
exception = exception.InnerException;
if (exception != null) {
message.Append(" ");
}
}
return message.ToString();
}
/// <summary>
/// Flattens the specified sequence of sequences.
/// </summary>
/// <typeparam name="T">The type of element contained in the sequence.</typeparam>
/// <param name="sequence">The sequence of sequences to flatten.</param>
/// <returns>A sequence of the contained items.</returns>
[Obsolete("Use Enumerable.SelectMany instead.")]
public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> sequence) {
ErrorUtilities.VerifyArgumentNotNull(sequence, "sequence");
foreach (IEnumerable<T> subsequence in sequence) {
foreach (T item in subsequence) {
yield return item;
}
}
}
/// <summary>
/// Cuts off precision beyond a second on a DateTime value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>A DateTime with a 0 millisecond component.</returns>
public static DateTime CutToSecond(this DateTime value) {
return value - TimeSpan.FromMilliseconds(value.Millisecond);
}
/// <summary>
/// Adds a name-value pair to the end of a given URL
/// as part of the querystring piece. Prefixes a ? or & before
/// first element as necessary.
/// </summary>
/// <param name="builder">The UriBuilder to add arguments to.</param>
/// <param name="name">The name of the parameter to add.</param>
/// <param name="value">The value of the argument.</param>
/// <remarks>
/// If the parameters to add match names of parameters that already are defined
/// in the query string, the existing ones are <i>not</i> replaced.
/// </remarks>
public static void AppendQueryArgument(this UriBuilder builder, string name, string value) {
AppendQueryArgs(builder, new[] { new KeyValuePair<string, string>(name, value) });
}
/// <summary>
/// Adds a set of values to a collection.
/// </summary>
/// <typeparam name="T">The type of value kept in the collection.</typeparam>
/// <param name="collection">The collection to add to.</param>
/// <param name="values">The values to add to the collection.</param>
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> values) {
Requires.NotNull(collection, "collection");
Requires.NotNull(values, "values");
foreach (var value in values) {
collection.Add(value);
}
}
/// <summary>
/// Tests whether two timespans are within reasonable approximation of each other.
/// </summary>
/// <param name="self">One TimeSpan.</param>
/// <param name="other">The other TimeSpan.</param>
/// <param name="marginOfError">The allowable margin of error.</param>
/// <returns><c>true</c> if the two TimeSpans are within <paramref name="marginOfError"/> of each other.</returns>
public static bool Equals(this TimeSpan self, TimeSpan other, TimeSpan marginOfError) {
return TimeSpan.FromMilliseconds(Math.Abs((self - other).TotalMilliseconds)) < marginOfError;
}
/// <summary>
/// Compares to string values for ordinal equality in such a way that its execution time does not depend on how much of the value matches.
/// </summary>
/// <param name="value1">The first value.</param>
/// <param name="value2">The second value.</param>
/// <returns>A value indicating whether the two strings share ordinal equality.</returns>
/// <remarks>
/// In signature equality checks, a difference in execution time based on how many initial characters match MAY
/// be used as an attack to figure out the expected signature. It is therefore important to make a signature
/// equality check's execution time independent of how many characters match the expected value.
/// See http://codahale.com/a-lesson-in-timing-attacks/ for more information.
/// </remarks>
public static bool EqualsConstantTime(string value1, string value2) {
// If exactly one value is null, they don't match.
if (value1 == null ^ value2 == null) {
return false;
}
// If both values are null (since if one is at this point then they both are), it's a match.
if (value1 == null) {
return true;
}
if (value1.Length != value2.Length) {
return false;
}
// This looks like a pretty crazy way to compare values, but it provides a constant time equality check,
// and is more resistant to compiler optimizations than simply setting a boolean flag and returning the boolean after the loop.
int result = 0;
for (int i = 0; i < value1.Length; i++) {
result |= value1[i] ^ value2[i];
}
return result == 0;
}
/// <summary>
/// Gets the public facing URL for the given incoming HTTP request.
/// </summary>
/// <param name="request">The incoming request. Cannot be <c>null</c>.</param>
/// <param name="serverVariables">The server variables to consider part of the request. Cannot be <c>null</c>.</param>
/// <returns>
/// The URI that the outside world used to create this request.
/// </returns>
/// <remarks>
/// Although the <paramref name="serverVariables"/> value can be obtained from
/// <see cref="HttpRequest.ServerVariables"/>, it's useful to be able to pass them
/// in so we can simulate injected values from our unit tests since the actual property
/// is a read-only kind of <see cref="NameValueCollection"/>.
/// </remarks>
public static Uri GetPublicFacingUrl(this HttpRequestBase request, NameValueCollection serverVariables) {
Requires.NotNull(request, "request");
Requires.NotNull(serverVariables, "serverVariables");
// Due to URL rewriting, cloud computing (i.e. Azure)
// and web farms, etc., we have to be VERY careful about what
// we consider the incoming URL. We want to see the URL as it would
// appear on the public-facing side of the hosting web site.
// HttpRequest.Url gives us the internal URL in a cloud environment,
// So we use a variable that (at least from what I can tell) gives us
// the public URL:
if (serverVariables["HTTP_HOST"] != null) {
ErrorUtilities.VerifySupported(request.Url.Scheme == Uri.UriSchemeHttps || request.Url.Scheme == Uri.UriSchemeHttp, "Only HTTP and HTTPS are supported protocols.");
string scheme = serverVariables["HTTP_X_FORWARDED_PROTO"] ?? request.Url.Scheme;
Uri hostAndPort = new Uri(scheme + Uri.SchemeDelimiter + serverVariables["HTTP_HOST"]);
UriBuilder publicRequestUri = new UriBuilder(request.Url);
publicRequestUri.Scheme = scheme;
publicRequestUri.Host = hostAndPort.Host;
publicRequestUri.Port = hostAndPort.Port; // CC missing Uri.Port contract that's on UriBuilder.Port
return publicRequestUri.Uri;
} else {
// Failover to the method that works for non-web farm enviroments.
// We use Request.Url for the full path to the server, and modify it
// with Request.RawUrl to capture both the cookieless session "directory" if it exists
// and the original path in case URL rewriting is going on. We don't want to be
// fooled by URL rewriting because we're comparing the actual URL with what's in
// the return_to parameter in some cases.
// Response.ApplyAppPathModifier(builder.Path) would have worked for the cookieless
// session, but not the URL rewriting problem.
return new Uri(request.Url, request.RawUrl);
}
}
/// <summary>
/// Gets the public facing URL for the given incoming HTTP request.
/// </summary>
/// <param name="request">The incoming request. Cannot be <c>null</c>. Server variables are read from this request.</param>
/// <returns>The URI that the outside world used to create this request.</returns>
public static Uri GetPublicFacingUrl(this HttpRequestBase request) {
Requires.NotNull(request, "request");
return GetPublicFacingUrl(request, request.ServerVariables);
}
/// <summary>
/// Gets the URL to the root of a web site, which may include a virtual directory path.
/// </summary>
/// <returns>An absolute URI.</returns>
internal static Uri GetWebRoot() {
HttpRequestBase requestInfo = new HttpRequestWrapper(HttpContext.Current.Request);
UriBuilder realmUrl = new UriBuilder(requestInfo.GetPublicFacingUrl());
realmUrl.Path = HttpContext.Current.Request.ApplicationPath;
realmUrl.Query = null;
realmUrl.Fragment = null;
return realmUrl.Uri;
}
/// <summary>
/// Creates the XML reader settings to use for reading XML from untrusted sources.
/// </summary>
/// <returns>
/// The new instance of <see cref="XmlReaderSettings"/>.
/// </returns>
/// <remarks>
/// The default values set here are based on recommendations from
/// http://msdn.microsoft.com/en-us/magazine/ee335713.aspx
/// </remarks>
internal static XmlReaderSettings CreateUntrustedXmlReaderSettings() {
return new XmlReaderSettings {
MaxCharactersFromEntities = 1024,
XmlResolver = null,
#if CLR4
DtdProcessing = DtdProcessing.Prohibit,
#else
ProhibitDtd = true,
#endif
};
}
/// <summary>
/// Clears any existing elements in a collection and fills the collection with a given set of values.
/// </summary>
/// <typeparam name="T">The type of value kept in the collection.</typeparam>
/// <param name="collection">The collection to modify.</param>
/// <param name="values">The new values to fill the collection.</param>
internal static void ResetContents<T>(this ICollection<T> collection, IEnumerable<T> values) {
Requires.NotNull(collection, "collection");
collection.Clear();
if (values != null) {
AddRange(collection, values);
}
}
/// <summary>
/// Strips any and all URI query parameters that serve as parts of a message.
/// </summary>
/// <param name="uri">The URI that may contain query parameters to remove.</param>
/// <param name="messageDescription">The message description whose parts should be removed from the URL.</param>
/// <returns>A cleaned URL.</returns>
internal static Uri StripMessagePartsFromQueryString(this Uri uri, MessageDescription messageDescription) {
Requires.NotNull(uri, "uri");
Requires.NotNull(messageDescription, "messageDescription");
NameValueCollection queryArgs = HttpUtility.ParseQueryString(uri.Query);
var matchingKeys = queryArgs.Keys.OfType<string>().Where(key => messageDescription.Mapping.ContainsKey(key)).ToList();
if (matchingKeys.Count > 0) {
var builder = new UriBuilder(uri);
foreach (string key in matchingKeys) {
queryArgs.Remove(key);
}
builder.Query = CreateQueryString(queryArgs.ToDictionary());
return builder.Uri;
} else {
return uri;
}
}
/// <summary>
/// Sends a multipart HTTP POST request (useful for posting files) but doesn't call GetResponse on it.
/// </summary>
/// <param name="request">The HTTP request.</param>
/// <param name="requestHandler">The request handler.</param>
/// <param name="parts">The parts to include in the POST entity.</param>
internal static void PostMultipartNoGetResponse(this HttpWebRequest request, IDirectWebRequestHandler requestHandler, IEnumerable<MultipartPostPart> parts) {
Requires.NotNull(request, "request");
Requires.NotNull(requestHandler, "requestHandler");
Requires.NotNull(parts, "parts");
Reporting.RecordFeatureUse("MessagingUtilities.PostMultipart");
parts = parts.CacheGeneratedResults();
string boundary = Guid.NewGuid().ToString();
string initialPartLeadingBoundary = string.Format(CultureInfo.InvariantCulture, "--{0}\r\n", boundary);
string partLeadingBoundary = string.Format(CultureInfo.InvariantCulture, "\r\n--{0}\r\n", boundary);
string finalTrailingBoundary = string.Format(CultureInfo.InvariantCulture, "\r\n--{0}--\r\n", boundary);
var contentType = new ContentType("multipart/form-data") {
Boundary = boundary,
CharSet = Channel.PostEntityEncoding.WebName,
};
request.Method = "POST";
request.ContentType = contentType.ToString();
long contentLength = parts.Sum(p => partLeadingBoundary.Length + p.Length) + finalTrailingBoundary.Length;
if (parts.Any()) {
contentLength -= 2; // the initial part leading boundary has no leading \r\n
}
request.ContentLength = contentLength;
var requestStream = requestHandler.GetRequestStream(request);
try {
StreamWriter writer = new StreamWriter(requestStream, Channel.PostEntityEncoding);
bool firstPart = true;
foreach (var part in parts) {
writer.Write(firstPart ? initialPartLeadingBoundary : partLeadingBoundary);
firstPart = false;
part.Serialize(writer);
part.Dispose();
}
writer.Write(finalTrailingBoundary);
writer.Flush();
} finally {
// We need to be sure to close the request stream...
// unless it is a MemoryStream, which is a clue that we're in
// a mock stream situation and closing it would preclude reading it later.
if (!(requestStream is MemoryStream)) {
requestStream.Dispose();
}
}
}
/// <summary>
/// Assembles the content of the HTTP Authorization or WWW-Authenticate header.
/// </summary>
/// <param name="scheme">The scheme.</param>
/// <param name="fields">The fields to include.</param>
/// <returns>A value prepared for an HTTP header.</returns>
internal static string AssembleAuthorizationHeader(string scheme, IEnumerable<KeyValuePair<string, string>> fields) {
Requires.NotNullOrEmpty(scheme, "scheme");
Requires.NotNull(fields, "fields");
var authorization = new StringBuilder();
authorization.Append(scheme);
authorization.Append(" ");
foreach (var pair in fields) {
string key = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Key);
string value = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Value);
authorization.Append(key);
authorization.Append("=\"");
authorization.Append(value);
authorization.Append("\",");
}
authorization.Length--; // remove trailing comma
return authorization.ToString();
}
/// <summary>
/// Parses the authorization header.
/// </summary>
/// <param name="scheme">The scheme. Must not be null or empty.</param>
/// <param name="authorizationHeader">The authorization header. May be null or empty.</param>
/// <returns>A sequence of key=value pairs discovered in the header. Never null, but may be empty.</returns>
internal static IEnumerable<KeyValuePair<string, string>> ParseAuthorizationHeader(string scheme, string authorizationHeader) {
Requires.NotNullOrEmpty(scheme, "scheme");
Contract.Ensures(Contract.Result<IEnumerable<KeyValuePair<string, string>>>() != null);
string prefix = scheme + " ";
if (authorizationHeader != null) {
// The authorization header may have multiple sections. Look for the appropriate one.
string[] authorizationSections = new string[] { authorizationHeader }; // what is the right delimiter, if any?
foreach (string authorization in authorizationSections) {
string trimmedAuth = authorization.Trim();
if (trimmedAuth.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { // RFC 2617 says this is case INsensitive
string data = trimmedAuth.Substring(prefix.Length);
return from element in data.Split(CommaArray)
let parts = element.Trim().Split(EqualsArray, 2)
let key = Uri.UnescapeDataString(parts[0])
let value = Uri.UnescapeDataString(parts[1].Trim(QuoteArray))
select new KeyValuePair<string, string>(key, value);
}
}
}
return Enumerable.Empty<KeyValuePair<string, string>>();
}
/// <summary>
/// Encodes a symmetric key handle and the blob that is encrypted/signed with that key into a single string
/// that can be decoded by <see cref="ExtractKeyHandleAndPayload"/>.
/// </summary>
/// <param name="handle">The cryptographic key handle.</param>
/// <param name="payload">The encrypted/signed blob.</param>
/// <returns>The combined encoded value.</returns>
internal static string CombineKeyHandleAndPayload(string handle, string payload) {
Requires.NotNullOrEmpty(handle, "handle");
Requires.NotNullOrEmpty(payload, "payload");
Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
return handle + "!" + payload;
}
/// <summary>
/// Extracts the key handle and encrypted blob from a string previously returned from <see cref="CombineKeyHandleAndPayload"/>.
/// </summary>
/// <param name="containingMessage">The containing message.</param>
/// <param name="messagePart">The message part.</param>
/// <param name="keyHandleAndBlob">The value previously returned from <see cref="CombineKeyHandleAndPayload"/>.</param>
/// <param name="handle">The crypto key handle.</param>
/// <param name="dataBlob">The encrypted/signed data.</param>
internal static void ExtractKeyHandleAndPayload(IProtocolMessage containingMessage, string messagePart, string keyHandleAndBlob, out string handle, out string dataBlob) {
Requires.NotNull(containingMessage, "containingMessage");
Requires.NotNullOrEmpty(messagePart, "messagePart");
Requires.NotNullOrEmpty(keyHandleAndBlob, "keyHandleAndBlob");
int privateHandleIndex = keyHandleAndBlob.IndexOf('!');
ErrorUtilities.VerifyProtocol(privateHandleIndex > 0, MessagingStrings.UnexpectedMessagePartValue, messagePart, keyHandleAndBlob);
handle = keyHandleAndBlob.Substring(0, privateHandleIndex);
dataBlob = keyHandleAndBlob.Substring(privateHandleIndex + 1);
}
/// <summary>
/// Gets a buffer of random data (not cryptographically strong).
/// </summary>
/// <param name="length">The length of the sequence to generate.</param>
/// <returns>The generated values, which may contain zeros.</returns>
internal static byte[] GetNonCryptoRandomData(int length) {
byte[] buffer = new byte[length];
NonCryptoRandomDataGenerator.NextBytes(buffer);
return buffer;
}
/// <summary>
/// Gets a cryptographically strong random sequence of values.
/// </summary>
/// <param name="length">The length of the sequence to generate.</param>
/// <returns>The generated values, which may contain zeros.</returns>
internal static byte[] GetCryptoRandomData(int length) {
byte[] buffer = new byte[length];
CryptoRandomDataGenerator.GetBytes(buffer);
return buffer;
}
/// <summary>
/// Gets a cryptographically strong random sequence of values.
/// </summary>
/// <param name="binaryLength">The length of the byte sequence to generate.</param>
/// <returns>A base64 encoding of the generated random data,
/// whose length in characters will likely be greater than <paramref name="binaryLength"/>.</returns>
internal static string GetCryptoRandomDataAsBase64(int binaryLength) {
byte[] uniq_bytes = GetCryptoRandomData(binaryLength);
string uniq = Convert.ToBase64String(uniq_bytes);
return uniq;
}
/// <summary>
/// Gets a random string made up of a given set of allowable characters.
/// </summary>
/// <param name="length">The length of the desired random string.</param>
/// <param name="allowableCharacters">The allowable characters.</param>
/// <returns>A random string.</returns>
internal static string GetRandomString(int length, string allowableCharacters) {
Requires.InRange(length >= 0, "length");
Requires.True(allowableCharacters != null && allowableCharacters.Length >= 2, "allowableCharacters");
char[] randomString = new char[length];
for (int i = 0; i < length; i++) {
randomString[i] = allowableCharacters[NonCryptoRandomDataGenerator.Next(allowableCharacters.Length)];
}
return new string(randomString);
}
/// <summary>
/// Computes the hash of a string.
/// </summary>
/// <param name="algorithm">The hash algorithm to use.</param>
/// <param name="value">The value to hash.</param>
/// <param name="encoding">The encoding to use when converting the string to a byte array.</param>
/// <returns>A base64 encoded string.</returns>
internal static string ComputeHash(this HashAlgorithm algorithm, string value, Encoding encoding = null) {
Requires.NotNull(algorithm, "algorithm");
Requires.NotNull(value, "value");
Contract.Ensures(Contract.Result<string>() != null);
encoding = encoding ?? Encoding.UTF8;
byte[] bytesToHash = encoding.GetBytes(value);
byte[] hash = algorithm.ComputeHash(bytesToHash);
string base64Hash = Convert.ToBase64String(hash);
return base64Hash;
}
/// <summary>
/// Computes the hash of a sequence of key=value pairs.
/// </summary>
/// <param name="algorithm">The hash algorithm to use.</param>
/// <param name="data">The data to hash.</param>
/// <param name="encoding">The encoding to use when converting the string to a byte array.</param>
/// <returns>A base64 encoded string.</returns>
internal static string ComputeHash(this HashAlgorithm algorithm, IDictionary<string, string> data, Encoding encoding = null) {
Requires.NotNull(algorithm, "algorithm");
Requires.NotNull(data, "data");
Contract.Ensures(Contract.Result<string>() != null);
// Assemble the dictionary to sign, taking care to remove the signature itself
// in order to accurately reproduce the original signature (which of course didn't include
// the signature).
// Also we need to sort the dictionary's keys so that we sign in the same order as we did
// the last time.
var sortedData = new SortedDictionary<string, string>(data, StringComparer.OrdinalIgnoreCase);
return ComputeHash(algorithm, (IEnumerable<KeyValuePair<string, string>>)sortedData, encoding);
}
/// <summary>
/// Computes the hash of a sequence of key=value pairs.
/// </summary>
/// <param name="algorithm">The hash algorithm to use.</param>
/// <param name="sortedData">The data to hash.</param>
/// <param name="encoding">The encoding to use when converting the string to a byte array.</param>
/// <returns>A base64 encoded string.</returns>
internal static string ComputeHash(this HashAlgorithm algorithm, IEnumerable<KeyValuePair<string, string>> sortedData, Encoding encoding = null) {
Requires.NotNull(algorithm, "algorithm");
Requires.NotNull(sortedData, "sortedData");
Contract.Ensures(Contract.Result<string>() != null);
return ComputeHash(algorithm, CreateQueryString(sortedData), encoding);
}
/// <summary>
/// Encrypts a byte buffer.
/// </summary>
/// <param name="buffer">The buffer to encrypt.</param>
/// <param name="key">The symmetric secret to use to encrypt the buffer. Allowed values are 128, 192, or 256 bytes in length.</param>
/// <returns>The encrypted buffer</returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "No apparent problem. False positive?")]
internal static byte[] Encrypt(byte[] buffer, byte[] key) {
using (SymmetricAlgorithm crypto = CreateSymmetricAlgorithm(key)) {
using (var ms = new MemoryStream()) {
var binaryWriter = new BinaryWriter(ms);
binaryWriter.Write((byte)1); // version of encryption algorithm
binaryWriter.Write(crypto.IV);
binaryWriter.Flush();
var cryptoStream = new CryptoStream(ms, crypto.CreateEncryptor(), CryptoStreamMode.Write);
cryptoStream.Write(buffer, 0, buffer.Length);
cryptoStream.FlushFinalBlock();
return ms.ToArray();
}
}
}
/// <summary>
/// Decrypts a byte buffer.
/// </summary>
/// <param name="buffer">The buffer to decrypt.</param>
/// <param name="key">The symmetric secret to use to decrypt the buffer. Allowed values are 128, 192, and 256.</param>
/// <returns>The encrypted buffer</returns>
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "This Dispose is safe.")]
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "No apparent problem. False positive?")]
internal static byte[] Decrypt(byte[] buffer, byte[] key) {
using (SymmetricAlgorithm crypto = CreateSymmetricAlgorithm(key)) {
using (var ms = new MemoryStream(buffer)) {
var binaryReader = new BinaryReader(ms);
int algorithmVersion = binaryReader.ReadByte();
ErrorUtilities.VerifyProtocol(algorithmVersion == 1, MessagingStrings.UnsupportedEncryptionAlgorithm);
crypto.IV = binaryReader.ReadBytes(crypto.IV.Length);
// Allocate space for the decrypted buffer. We don't know how long it will be yet,
// but it will never be larger than the encrypted buffer.
var decryptedBuffer = new byte[buffer.Length];
int actualDecryptedLength;
using (var cryptoStream = new CryptoStream(ms, crypto.CreateDecryptor(), CryptoStreamMode.Read)) {
actualDecryptedLength = cryptoStream.Read(decryptedBuffer, 0, decryptedBuffer.Length);
}
// Create a new buffer with only the decrypted data.
var finalDecryptedBuffer = new byte[actualDecryptedLength];
Array.Copy(decryptedBuffer, finalDecryptedBuffer, actualDecryptedLength);
return finalDecryptedBuffer;
}
}
}
/// <summary>
/// Encrypts a string.
/// </summary>
/// <param name="plainText">The text to encrypt.</param>
/// <param name="key">The symmetric secret to use to encrypt the buffer. Allowed values are 128, 192, and 256.</param>
/// <returns>The encrypted buffer</returns>
internal static string Encrypt(string plainText, byte[] key) {
byte[] buffer = Encoding.UTF8.GetBytes(plainText);
byte[] cipher = Encrypt(buffer, key);
return Convert.ToBase64String(cipher);
}
/// <summary>
/// Decrypts a string previously encrypted with <see cref="Encrypt(string, byte[])"/>.
/// </summary>
/// <param name="cipherText">The text to decrypt.</param>
/// <param name="key">The symmetric secret to use to decrypt the buffer. Allowed values are 128, 192, and 256.</param>
/// <returns>The encrypted buffer</returns>
internal static string Decrypt(string cipherText, byte[] key) {
byte[] cipher = Convert.FromBase64String(cipherText);
byte[] plainText = Decrypt(cipher, key);
return Encoding.UTF8.GetString(plainText);
}
/// <summary>
/// Performs asymmetric encryption of a given buffer.
/// </summary>
/// <param name="crypto">The asymmetric encryption provider to use for encryption.</param>
/// <param name="buffer">The buffer to encrypt.</param>
/// <returns>The encrypted data.</returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "No apparent problem. False positive?")]
internal static byte[] EncryptWithRandomSymmetricKey(this RSACryptoServiceProvider crypto, byte[] buffer) {
Requires.NotNull(crypto, "crypto");
Requires.NotNull(buffer, "buffer");
using (var symmetricCrypto = new RijndaelManaged()) {
symmetricCrypto.Mode = CipherMode.CBC;
using (var encryptedStream = new MemoryStream()) {
var encryptedStreamWriter = new BinaryWriter(encryptedStream);
byte[] prequel = new byte[symmetricCrypto.Key.Length + symmetricCrypto.IV.Length];
Array.Copy(symmetricCrypto.Key, prequel, symmetricCrypto.Key.Length);
Array.Copy(symmetricCrypto.IV, 0, prequel, symmetricCrypto.Key.Length, symmetricCrypto.IV.Length);
byte[] encryptedPrequel = crypto.Encrypt(prequel, false);
encryptedStreamWriter.Write(encryptedPrequel.Length);
encryptedStreamWriter.Write(encryptedPrequel);
encryptedStreamWriter.Flush();
var cryptoStream = new CryptoStream(encryptedStream, symmetricCrypto.CreateEncryptor(), CryptoStreamMode.Write);
cryptoStream.Write(buffer, 0, buffer.Length);
cryptoStream.FlushFinalBlock();
return encryptedStream.ToArray();
}
}
}
/// <summary>
/// Performs asymmetric decryption of a given buffer.
/// </summary>
/// <param name="crypto">The asymmetric encryption provider to use for decryption.</param>
/// <param name="buffer">The buffer to decrypt.</param>
/// <returns>The decrypted data.</returns>
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "This Dispose is safe.")]
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "No apparent problem. False positive?")]
internal static byte[] DecryptWithRandomSymmetricKey(this RSACryptoServiceProvider crypto, byte[] buffer) {
Requires.NotNull(crypto, "crypto");
Requires.NotNull(buffer, "buffer");
using (var encryptedStream = new MemoryStream(buffer)) {
var encryptedStreamReader = new BinaryReader(encryptedStream);
byte[] encryptedPrequel = encryptedStreamReader.ReadBytes(encryptedStreamReader.ReadInt32());
byte[] prequel = crypto.Decrypt(encryptedPrequel, false);
using (var symmetricCrypto = new RijndaelManaged()) {
symmetricCrypto.Mode = CipherMode.CBC;
byte[] symmetricKey = new byte[symmetricCrypto.Key.Length];
byte[] symmetricIV = new byte[symmetricCrypto.IV.Length];
Array.Copy(prequel, symmetricKey, symmetricKey.Length);
Array.Copy(prequel, symmetricKey.Length, symmetricIV, 0, symmetricIV.Length);
symmetricCrypto.Key = symmetricKey;
symmetricCrypto.IV = symmetricIV;
// Allocate space for the decrypted buffer. We don't know how long it will be yet,
// but it will never be larger than the encrypted buffer.
var decryptedBuffer = new byte[encryptedStream.Length - encryptedStream.Position];
int actualDecryptedLength;
using (var cryptoStream = new CryptoStream(encryptedStream, symmetricCrypto.CreateDecryptor(), CryptoStreamMode.Read)) {
actualDecryptedLength = cryptoStream.Read(decryptedBuffer, 0, decryptedBuffer.Length);
}
// Create a new buffer with only the decrypted data.
var finalDecryptedBuffer = new byte[actualDecryptedLength];
Array.Copy(decryptedBuffer, finalDecryptedBuffer, actualDecryptedLength);
return finalDecryptedBuffer;
}
}
}
/// <summary>
/// Gets a key from a given bucket with the longest remaining life, or creates a new one if necessary.
/// </summary>
/// <param name="cryptoKeyStore">The crypto key store.</param>
/// <param name="bucket">The bucket where the key should be found or stored.</param>
/// <param name="minimumRemainingLife">The minimum remaining life required on the returned key.</param>
/// <param name="keySize">The required size of the key, in bits.</param>
/// <returns>
/// A key-value pair whose key is the secret's handle and whose value is the cryptographic key.
/// </returns>
internal static KeyValuePair<string, CryptoKey> GetCurrentKey(this ICryptoKeyStore cryptoKeyStore, string bucket, TimeSpan minimumRemainingLife, int keySize = 256) {
Requires.NotNull(cryptoKeyStore, "cryptoKeyStore");
Requires.NotNullOrEmpty(bucket, "bucket");
Requires.True(keySize % 8 == 0, "keySize");
var cryptoKeyPair = cryptoKeyStore.GetKeys(bucket).FirstOrDefault(pair => pair.Value.Key.Length == keySize / 8);
if (cryptoKeyPair.Value == null || cryptoKeyPair.Value.ExpiresUtc < DateTime.UtcNow + minimumRemainingLife) {
// No key exists with enough remaining life for the required purpose. Create a new key.
if (cryptoKeyPair.Value == null) {
Logger.Messaging.InfoFormat("{0}.GetKeys returned no keys for bucket \"{1}\" with the required key length of {2} bits. A new key will be created", typeof(ICryptoKeyStore), bucket, keySize);
} else {
Logger.Messaging.InfoFormat("The first key returned by {0}.GetKeys for bucket \"{1}\" with the required key length of {2} bits was too near expiry to use. A new key will be created", typeof(ICryptoKeyStore), bucket, keySize);
}
ErrorUtilities.VerifyHost(minimumRemainingLife <= SymmetricSecretKeyLifespan, "Unable to create a new symmetric key with the required lifespan of {0} because it is beyond the limit of {1}.", minimumRemainingLife, SymmetricSecretKeyLifespan);
byte[] secret = GetCryptoRandomData(keySize / 8);
DateTime expires = DateTime.UtcNow + SymmetricSecretKeyLifespan;
var cryptoKey = new CryptoKey(secret, expires);
// Store this key so we can find and use it later.
int failedAttempts = 0;
tryAgain:
try {
string handle = GetRandomString(SymmetricSecretHandleLength, Base64WebSafeCharacters);
cryptoKeyPair = new KeyValuePair<string, CryptoKey>(handle, cryptoKey);
cryptoKeyStore.StoreKey(bucket, handle, cryptoKey);
} catch (CryptoKeyCollisionException) {
ErrorUtilities.VerifyInternal(++failedAttempts < 3, "Unable to derive a unique handle to a private symmetric key.");
Logger.Messaging.Warn("A randomly generated crypto key handle collided with an existing handle. Another randomly generated handle will be attempted till the retry count is met.");
goto tryAgain;
}
}
return cryptoKeyPair;
}
/// <summary>
/// Compresses a given buffer.
/// </summary>
/// <param name="buffer">The buffer to compress.</param>
/// <param name="method">The compression algorithm to use.</param>
/// <returns>The compressed data.</returns>
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "This Dispose is safe.")]
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "No apparent problem. False positive?")]
internal static byte[] Compress(byte[] buffer, CompressionMethod method = CompressionMethod.Deflate) {
Requires.NotNull(buffer, "buffer");
Contract.Ensures(Contract.Result<byte[]>() != null);
using (var ms = new MemoryStream()) {
Stream compressingStream = null;
try {
switch (method) {
case CompressionMethod.Deflate:
compressingStream = new DeflateStream(ms, CompressionMode.Compress, true);
break;
case CompressionMethod.Gzip:
compressingStream = new GZipStream(ms, CompressionMode.Compress, true);
break;
default:
Requires.InRange(false, "method");
break;
}
compressingStream.Write(buffer, 0, buffer.Length);
return ms.ToArray();
} finally {
if (compressingStream != null) {
compressingStream.Dispose();
}
}
}
}
/// <summary>
/// Decompresses a given buffer.
/// </summary>
/// <param name="buffer">The buffer to decompress.</param>
/// <param name="method">The compression algorithm used.</param>
/// <returns>The decompressed data.</returns>