/// <summary>Decrypts data that was encrypted using machine key encryption</summary> /// <param name="value">The string to decrypt in URL encoded format</param> /// <returns>A decrypted string in UTF8 format</returns> public static string UnprotectString(string value) { if (string.IsNullOrEmpty(value)) { return(null); } byte[] stream = HttpServerUtility.UrlTokenDecode(value); byte[] decodedValue = MachineKey.Unprotect(stream); return(System.Text.Encoding.UTF8.GetString(decodedValue)); }
/// <summary> /// Accepts reset key. Used during forgot password. /// </summary> /// <param name="userId"> </param> /// <param name="resetKey"></param> /// <returns>Returns a validated AuthUser, or null if validation failed.</returns> public AuthUser ValidateReset(int userId, string resetKey) { AuthUser user = GetByIdForLogin(userId); if (user == null) { return(null); } byte[] keyBytes = HttpServerUtility.UrlTokenDecode(resetKey); return(IsValidResetKey(user, keyBytes) ? user : null); }
public async Task <IHttpActionResult> Blackhole(string indexerID, string path, string jackett_apikey, string file) { var jsonReply = new JObject(); try { var indexer = indexerService.GetWebIndexer(indexerID); if (!indexer.IsConfigured) { logger.Warn(string.Format("Rejected a request to {0} which is unconfigured.", indexer.DisplayName)); throw new Exception("This indexer is not configured."); } if (serverService.Config.APIKey != jackett_apikey) { throw new Exception("Incorrect API key"); } path = Encoding.UTF8.GetString(HttpServerUtility.UrlTokenDecode(path)); path = protectionService.UnProtect(path); var remoteFile = new Uri(path, UriKind.RelativeOrAbsolute); var downloadBytes = await indexer.Download(remoteFile); if (string.IsNullOrWhiteSpace(Engine.Server.Config.BlackholeDir)) { throw new Exception("Blackhole directory not set!"); } if (!Directory.Exists(Engine.Server.Config.BlackholeDir)) { throw new Exception("Blackhole directory does not exist: " + Engine.Server.Config.BlackholeDir); } var fileName = DateTime.Now.Ticks.ToString() + "-" + StringUtil.MakeValidFileName(indexer.DisplayName, '_', false); if (string.IsNullOrWhiteSpace(file)) { fileName += ".torrent"; } else { fileName += "-" + StringUtil.MakeValidFileName(file, '_', false); // call MakeValidFileName() again to avoid any possibility of path traversal attacks } File.WriteAllBytes(Path.Combine(Engine.Server.Config.BlackholeDir, fileName), downloadBytes); jsonReply["result"] = "success"; } catch (Exception ex) { logger.Error(ex, "Error downloading to blackhole " + indexerID + " " + path); jsonReply["result"] = "error"; jsonReply["error"] = ex.Message; } return(Json(jsonReply)); }
public static string UnProtect(string text, string purpose) { if (string.IsNullOrEmpty(text)) { return(string.Empty); } byte[] stream = HttpServerUtility.UrlTokenDecode(text); byte[] decodedValues = MachineKey.Unprotect(stream, purpose); return(Encoding.UTF8.GetString(decodedValues)); }
private static string DesprotecToken(string String) { try { var ByteSinProteccion = HttpServerUtility.UrlTokenDecode(String); return(Encoding.ASCII.GetString(ByteSinProteccion)); } catch { return(null); } }
//------------------------------------------------------------------------------------------------------------------------------------------------------------- protected void Application_Error(Object sender, EventArgs e) { // 19-Jul-2015 - Get the error details when pages crash etc ... HttpException lastErrorWrapper = Server.GetLastError() as HttpException; if (lastErrorWrapper != null) { Exception lastError = lastErrorWrapper; if (lastErrorWrapper.InnerException != null) { lastError = lastErrorWrapper.InnerException; } string lastErrorTypeName = lastError.GetType().ToString(); string lastErrorMessage = lastError.Message; string lastErrorStackTrace = lastError.StackTrace; string currentPageOrResource = HttpContext.Current.Request.Url.ToString(); // 5-Feb-2016 - getting a few errors with "This is an invalid webresource request". // According to this dude - http://www.telerik.com/blogs/debugging-asp-net-2-0-web-resources-decrypting-the-url-and-getting-the-resource-name // this could be due to dodgy requests and you can decrypte the d attribute to find out the specific resource string decryptedResource = ""; try { if (currentPageOrResource != null && currentPageOrResource.Contains("WebResource.axd") == true) { string dVal = currentPageOrResource.Split(new string[] { "WebResource.axd?d=" }, StringSplitOptions.None)[1]; dVal = dVal.Split(new string[] { "&" }, StringSplitOptions.None)[0]; byte[] encryptedData = HttpServerUtility.UrlTokenDecode(dVal); Type machineKeySection = typeof(MachineKeySection); Type[] paramTypes = new Type[] { typeof(bool), typeof(byte[]), typeof(byte[]), typeof(int), typeof(int) }; MethodInfo encryptOrDecryptData = machineKeySection.GetMethod("EncryptOrDecryptData", BindingFlags.Static | BindingFlags.NonPublic, null, paramTypes, null); byte[] decryptedData = (byte[])encryptOrDecryptData.Invoke(null, new object[] { false, encryptedData, null, 0, encryptedData.Length }); decryptedResource = "(" + Encoding.UTF8.GetString(decryptedData) + ")"; } } catch (Exception exWebResource) { // F**K it ... decryptedResource = "(Couldn't decrypt the provided URL: " + exWebResource.ToString() + ")"; } string errorString = "Server response crashed: " + lastErrorTypeName + "\n\nPage or resource:" + currentPageOrResource + decryptedResource + "\n\nDetails:" + lastErrorMessage + "\n\nStackTrace:" + lastErrorStackTrace; Logger.LogError(6, errorString); MGLApplicationInterface.Instance().LastError = errorString.Replace("\n\n", "<br /><br />"); } }
///<summary> /// Decode Base64 encoded string with URL and Filename Safe Alphabet using UTF-8. ///</summary> ///<param name="str">Base64 code</param> ///<returns>The decoded string.</returns> public static string DecodificarUrlBase64(string str) { try { byte[] decbuff = HttpServerUtility.UrlTokenDecode(str); return(Encoding.GetEncoding(1252).GetString(decbuff)); } catch (Exception ex2) { return(DecodificarBase64(str)); } }
public static string Base64ForUrlDecode(string str) { if (!string.IsNullOrEmpty(str)) { var decbuff = HttpServerUtility.UrlTokenDecode(str); if (decbuff != null) { return(Encoding.UTF8.GetString(decbuff)); } } return(string.Empty); }
/// <summary> /// Decrypts the specified <paramref name="ticket" />. /// </summary> /// <param name="ticket">The ticket to decrypt.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public static AuthTicket Unprotect(string ticket) { if (ticket == null) { throw new ArgumentNullException(nameof(ticket)); } var stream = HttpServerUtility.UrlTokenDecode(ticket); var decodedValue = MachineKey.Unprotect(stream, "project", "authentication"); var decodedValueUtf8 = Encoding.UTF8.GetString(decodedValue); return(JsonConvert.DeserializeObject <AuthTicket>(decodedValueUtf8, JsonNetUtility.Settings)); }
public string GetUserNameFromToken(string token) { try { var decodedToken = HttpServerUtility.UrlTokenDecode(token); return(_crypto.GetValueFromToken(decodedToken)); } catch (FormatException) { return(null); } }
public static String Decrypt(String encryptedText) { try { var encryptedBytes = HttpServerUtility.UrlTokenDecode(encryptedText); //Convert.FromBase64String(encryptedText); return(Encoding.UTF8.GetString(Decrypt(encryptedBytes, GetRijndaelManaged(_key)))); } catch { return(null); } }
/// <summary> /// Validates the request against XSRF attack. /// </summary> /// <param name="sessionId">The session id embedded in the query string.</param> /// <returns> /// <c>true</c> if the request is safe. Otherwise, <c>false</c>. /// </returns> private bool ValidateRequestAgainstXsrfAttack(out string sessionId) { sessionId = null; // get the session id query string parameter string queryStringSessionId = this.requestContext.Request.QueryString[SessionIdQueryStringName]; // verify that the query string value is a valid guid Guid guid; if (!Guid.TryParse(queryStringSessionId, out guid)) { return(false); } // the cookie value should be the current username secured against this guid var cookie = this.requestContext.Request.Cookies[SessionIdCookieName]; if (cookie == null || string.IsNullOrEmpty(cookie.Value)) { return(false); } // extract the username embedded within the cookie // if there is any error at all (crypto, malformed, etc.), fail gracefully string usernameInCookie = null; try { byte[] encryptedCookieBytes = HttpServerUtility.UrlTokenDecode(cookie.Value); byte[] decryptedCookieBytes = MachineKeyUtil.Unprotect(encryptedCookieBytes, AntiXsrfPurposeString, "Token: " + queryStringSessionId); usernameInCookie = Encoding.UTF8.GetString(decryptedCookieBytes); } catch { return(false); } string currentUsername = GetUsername(this.requestContext); bool successful = string.Equals(currentUsername, usernameInCookie, StringComparison.OrdinalIgnoreCase); if (successful) { // be a good citizen, clean up cookie when the authentication succeeds var xsrfCookie = new HttpCookie(SessionIdCookieName, string.Empty) { HttpOnly = true, Expires = DateTime.Now.AddYears(-1) }; this.requestContext.Response.Cookies.Set(xsrfCookie); } sessionId = queryStringSessionId; return(successful); }
public static string GetCookie(string key) { key = Prefix + key; if (HttpContext.Current.Request.Cookies[key] == null || HttpContext.Current.Request.Cookies[key].Value == null) { return(null); } var decValue = HttpServerUtility.UrlTokenDecode(HttpContext.Current.Request.Cookies[key].Value); return(decValue != null?Encoding.UTF8.GetString(decValue) : ""); }
private static string Unprotect(string text, string purpose) { if (string.IsNullOrEmpty(text)) { return(null); } var stream = HttpServerUtility.UrlTokenDecode(text); var decodedValue = MachineKey.Unprotect(stream, purpose); return(Encoding.UTF8.GetString(decodedValue)); }
public override async Task GrantCustomExtension(OAuthGrantCustomExtensionContext context) { if (context.GrantType != "anonymous") { return; } var db = new KiwiContext(); var protectedToken = HttpServerUtility.UrlTokenDecode(context.Parameters.Get("token")); if (protectedToken == null) { return; } var anonymousToken = Encoding.UTF8.GetString(MachineKey.Unprotect(protectedToken)); var tokenArray = anonymousToken.Split('‼'); var reportId = Int32.Parse(tokenArray[0]); var time = DateTime.Parse(tokenArray[1]); if (tokenArray.Length != 2 && reportId != 0 && time != new DateTime()) { context.SetError("invalid_grant", "This token is invalid"); return; } if (time < DateTime.Now) { context.SetError("invalid_grant", "This token has expired"); return; } if (await db.Reports.FindAsync(reportId) == null) { context.SetError("invalid_grant", "No report found with that ID"); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Role, "Anonymous")); identity.AddClaim(new Claim("reportId", reportId.ToString())); identity.AddClaim(new Claim("is_anonymous", "true")); // token for reporting users should be valid for 10 minutes //context.Options.AccessTokenExpireTimeSpan = new TimeSpan(0, 10, 0); context.Validated(identity); }
public void ProcessRequest(HttpContext context) { context.PushRewritenUri(); if (string.IsNullOrEmpty(context.Request["p"])) { _params = new Dictionary <string, string>(context.Request.QueryString.Count); //Form params and redirect foreach (var key in context.Request.QueryString.AllKeys) { _params.Add(key, context.Request.QueryString[key]); } //Pack and redirect var uriBuilder = new UriBuilder(context.Request.GetUrlRewriter()); var token = HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(_params))); uriBuilder.Query = "p=" + token; context.Response.Redirect(uriBuilder.Uri.ToString(), true); } else { _params = ((Dictionary <string, object>) new JavaScriptSerializer().DeserializeObject( Encoding.UTF8.GetString(HttpServerUtility.UrlTokenDecode(context.Request["p"])))).ToDictionary(x => x.Key, y => (string)y.Value); } if (!string.IsNullOrEmpty(Auth)) { try { var profile = ProviderManager.Process(Auth, context, _params); if (profile != null) { SendClientData(context, profile); } } catch (ThreadAbortException) { //Thats is responce ending } catch (Exception ex) { SendClientData(context, LoginProfile.FromError(ex)); } } else { //Render xrds RenderXrds(context); } context.PopRewritenUri(); }
public async Task <HttpResponseMessage> Download(string indexerID, string path, string apikey, string file) { try { var indexer = indexerService.GetIndexer(indexerID); if (!indexer.IsConfigured) { logger.Warn(string.Format("Rejected a request to {0} which is unconfigured.", indexer.DisplayName)); return(Request.CreateResponse(HttpStatusCode.Forbidden, "This indexer is not configured.")); } path = Encoding.UTF8.GetString(HttpServerUtility.UrlTokenDecode(path)); if (serverService.Config.APIKey != apikey) { return(new HttpResponseMessage(HttpStatusCode.Unauthorized)); } var target = new Uri(path, UriKind.RelativeOrAbsolute); target = indexer.UncleanLink(target); var downloadBytes = await indexer.Download(target); // This will fix torrents where the keys are not sorted, and thereby not supported by Sonarr. var torrentDictionary = BEncodedDictionary.DecodeTorrent(downloadBytes); downloadBytes = torrentDictionary.Encode(); char[] invalidChars = System.IO.Path.GetInvalidFileNameChars(); for (int i = 0; i < file.Count(); i++) { if (invalidChars.Contains(file[i])) { file = file.Remove(i, 1).Insert(i, " "); } } var result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new ByteArrayContent(downloadBytes); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-bittorrent"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = file }; return(result); } catch (Exception e) { logger.Error(e, "Error downloading " + indexerID + " " + path); return(new HttpResponseMessage(HttpStatusCode.NotFound)); } }
public static byte[] FromBase64Url(this string rfc4648) { if (rfc4648.Length % 4 != 0) { rfc4648 += (4 - rfc4648.Length % 4); } else { rfc4648 += 0; } return(HttpServerUtility.UrlTokenDecode(rfc4648) ?? throw new InvalidOperationException()); }
/// <summary> /// Decode an item from a url token. /// </summary> /// <typeparam name="T">The item type.</typeparam> /// <param name="token">The item token.</param> /// <returns>The item instance.</returns> public static T Decode <T>(string token) { var buffer = HttpServerUtility.UrlTokenDecode(token); using (var memory = new MemoryStream(buffer)) using (var gzip = new GZipStream(memory, CompressionMode.Decompress)) using (var reader = new BsonReader(gzip)) { var serializer = JsonSerializer.CreateDefault(); var item = serializer.Deserialize <T>(reader); return(item); } }
public ActionResult SQLRemovePlan(string node, string handle) { var planHandle = HttpServerUtility.UrlTokenDecode(handle); var instance = SQLInstance.Get(node); if (instance == null) { return(JsonError("Could not find server " + node)); } var result = instance.RemovePlan(planHandle); return(result != 0 ? Json(true) : JsonError("There was an error removing the plan from cache")); }
public static Guid DecodeGuid(this string value) { value.AssertNotNull("value"); var result = HttpServerUtility.UrlTokenDecode(value); if (result == null || result.Length != 16) { throw new BadRequestException("Value does not represent an ID: " + value + ", Result: " + result); } return(new Guid(result)); }
public static int?Unprotect(string protectedText) { if (!String.IsNullOrEmpty(protectedText)) { var protectedBytes = HttpServerUtility.UrlTokenDecode(protectedText); //var protectedBytes = Convert.FromBase64String(protectedText); var unprotectedBytes = MachineKey.Unprotect(protectedBytes, Purpose); var unprotectedText = Encoding.UTF8.GetString(unprotectedBytes); var finalString = unprotectedText.Substring(Secret1.Length, unprotectedText.Length - Secret2.Length - Secret1.Length); return(int.Parse(finalString)); } return(null); }
// String transformation helpers internal static string Base64ToHex(string base64) { StringBuilder builder = new StringBuilder((int)(base64.Length * 1.5)); foreach (byte b in HttpServerUtility.UrlTokenDecode(base64)) { builder.Append(HexDigit(b >> 4)); builder.Append(HexDigit(b & 0x0F)); } string result = builder.ToString(); return(result); }
public static byte [] GetProtectedData(string strEncryptedText) { byte[] byteProtectedData = null; switch (enumPurpose) { case EnumPurpose.OWINCOOKIE: strEncryptedText = strEncryptedText.Replace('-', '+').Replace('_', '/'); var padding = 3 - ((strEncryptedText.Length + 3) % 4); if (padding != 0) { strEncryptedText = strEncryptedText + new string('=', padding); } byteProtectedData = Convert.FromBase64String(strEncryptedText); break; case EnumPurpose.OWINOAUTH: strEncryptedText = strEncryptedText.Replace('-', '+').Replace('_', '/'); var padding1 = 3 - ((strEncryptedText.Length + 3) % 4); if (padding1 != 0) { strEncryptedText = strEncryptedText + new string('=', padding1); } byteProtectedData = Convert.FromBase64String(strEncryptedText); break; case EnumPurpose.ASPXAUTH: byteProtectedData = CryptoUtil.HexToBinary(strEncryptedText); break; case EnumPurpose.WEBRESOURCE: byteProtectedData = HttpServerUtility.UrlTokenDecode(strEncryptedText); break; case EnumPurpose.SCRIPTRESOURCE: byteProtectedData = HttpServerUtility.UrlTokenDecode(strEncryptedText); break; case EnumPurpose.VIEWSTATE: byteProtectedData = System.Convert.FromBase64String(strEncryptedText); break; case EnumPurpose.UNKNOWN: byteProtectedData = null; break; default: byteProtectedData = null; break; } return(byteProtectedData); }
private String ConvertFromBase64(String text) { try { var bytes = HttpServerUtility.UrlTokenDecode(text); var @string = Encoding.UTF8.GetString(bytes); return(@string); } catch (Exception) { return(null); } }
public static string Decrypt(string cipherText, string Password) { try { byte[] cipherBytes = HttpServerUtility.UrlTokenDecode(cipherText); PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16)); return(System.Text.Encoding.Unicode.GetString(decryptedData)); } catch { return(string.Empty); } }
public ActionResult TopDetail(string node, string handle, int?offset = null) { var planHandle = HttpServerUtility.UrlTokenDecode(handle); var i = SQLInstance.Get(node); var vd = new OperationsTopDetailModel { Instance = i, Op = i.GetTopOperation(planHandle, offset).Data }; return(View("Operations.Top.Detail", vd)); }
/// <summary> /// Gets the token secret from the specified token. /// </summary> /// <param name="token">The token.</param> /// <returns> /// The token's secret /// </returns> public string GetTokenSecret(string token) { HttpCookie cookie = this.Context.Request.Cookies[TokenCookieKey]; if (cookie == null || string.IsNullOrEmpty(cookie.Values[token])) { return(null); } byte[] cookieBytes = HttpServerUtility.UrlTokenDecode(cookie.Values[token]); byte[] clearBytes = MachineKeyUtil.Unprotect(cookieBytes, TokenCookieKey, "Token:" + token); string secret = Encoding.UTF8.GetString(clearBytes); return(secret); }
public ActionResult TopPlan(string node, string handle) { var planHandle = HttpServerUtility.UrlTokenDecode(handle); var i = SQLInstance.Get(node); var op = i.GetTopOperation(planHandle).Data; if (op == null) { return(ContentNotFound("Plan was not found.")); } var ms = new MemoryStream(Encoding.UTF8.GetBytes(op.QueryPlan)); return(File(ms, "text/xml", $"QueryPlan-{Math.Abs(handle.GetHashCode())}.sqlplan")); }
private static T Read <T>(string signature, string secret, bool bUseSecret) { try { var payloadParts = Encoding.UTF8.GetString(HttpServerUtility.UrlTokenDecode(signature)).Split('?'); if (false == bUseSecret || (GetHashBase64(payloadParts[1] + secret) == payloadParts[0]) || (GetHashBase64MD5(payloadParts[1] + secret) == payloadParts[0])) { return(new JavaScriptSerializer().Deserialize <T>(payloadParts[1])); } } catch (Exception) { } return(default(T)); }