fiddler - decode custom encrypted body in inspector by c# on the fly - fiddler

The content is Encrypt with an CUSTOM encrypter. fiddler captured content body is base64 encode string in plain text
The application traffic flow:
request:
base64Encode(customEncryptFromStringTobytes(jsonString) ) -> application -> http server
response:
customDecryptFrombytesToString(base64Decode(jsonString) ) <- application <- http server
I have the encrypt/decrypt class in c#:
string EncryptToBase64(string plainText);
string DecryptFromBase64(string plainText);
I build an exe to do the transform, I wonder how To make fiddler decode request/respose body by this exe on the fly
I want Fiddler show decrypt content in inspector , and encrypt again everytime I [Reissue and Edit(E)] the request.
I found something close but Dont know how to call an exe to do decode.
http://docs.telerik.com/fiddler/KnowledgeBase/FiddlerScript/ModifyRequestOrResponse
update:
I have implement the custom inspector for Fiddler. see the answer below.

I create an Extension for custom Inspector
full example https://github.com/chouex/FiddlerExtensionExample
you will build a dll and copy the file to Inspectors and Scripts folder in fiddler. restart fiddler will load the extenion.
note:
I used pre/post-build script to copy dll and restart fiddler in vs project.
custom inspector:
This Example just beautify the json body.
public class ResponseInspector : Inspector2, IResponseInspector2
{
TextBox myControl;
private byte[] m_entityBody;
private bool m_bDirty;
private bool m_bReadOnly;
public bool bReadOnly
{
get { return m_bReadOnly; }
set
{
m_bReadOnly = value;
// TODO: You probably also want to turn your visible control CONFIG.colorDisabledEdit (false) or WHITE (true) here depending on the value being passed in.
}
}
public void Clear()
{
m_entityBody = null;
m_bDirty = false;
myControl.Text = "";
}
public ResponseInspector()
{
// TODO: Add constructor logic here
}
public HTTPResponseHeaders headers
{
get { return null; // Return null if your control doesn't allow header editing.
}
set { }
}
public byte[] body
{
get { return m_entityBody; }
set
{
// Here's where the action is. It's time to update the visible display of the text
m_entityBody = value;
if (null != m_entityBody)
{
var text = System.Text.Encoding.UTF8.GetString(m_entityBody);
if (!String.IsNullOrEmpty(text) && text.StartsWith("{"))
{
text = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(text), Formatting.Indented);
}
myControl.Text = text;
// TODO: Use correct encoding based on content header.
}
else
{
myControl.Text = "";
}
m_bDirty = false;
// Note: Be sure to have an OnTextChanged handler for the textbox which sets m_bDirty to true!
}
}
public bool bDirty
{
get { return m_bDirty; }
}
public override int GetOrder()
{
return 0;
}
public override void AddToTab(System.Windows.Forms.TabPage o)
{
myControl = new TextBox(); // Essentially the TextView class is simply a usercontrol containing a textbox.
myControl.Height = o.Height;
myControl.Multiline = true;
myControl.ScrollBars = ScrollBars.Vertical;
o.Text = "TextViewExample";
o.Controls.Add(myControl);
o.Controls[0].Dock = DockStyle.Fill;
}
}
for Traffic Tamper(not mention in question but I think this is useful):
implement AutoTamperResponseBefore() in IAutoTamper2
This Example just replace any text from "xt" to "c1" in every request body

Add a dummy header 
Fiddler-Encoding: base64
 and encode your body using base64 if it contains any binary data. Fiddler will decode the data before transmitting it to the server.
Taken from http://www.fiddlerbook.com/fiddler/help/composer.asp

Related

How can i make remember me check box with unity?

I made an app that has a login form which gets the data from a SQL database on a server , i want to add a remember me check box so the user can automatically login , how can i do this or how can i save a data to text file then retrieve it back ?
thanks
unity, to addition to writing to a file, also provides local storing in PlayerPrefs, which work for all platforms.
Please read more about it here
https://docs.unity3d.com/ScriptReference/PlayerPrefs.html
You can store login information there and check it afterward to see if player has login credentials.
This script will create txt file in your project folder and write to it single row with login string. In order to use this you have to put this scrip anywhere you like then drag in editor your INPUT FIELD and toggle. Finaly assign OnClick event on your login button to execute loginClick() method.
using UnityEngine;
using UnityEngine.UI;
using System.IO;
public class InputFieldTest : MonoBehaviour {
//reference for InputField, needs to be assigned in editor
public InputField login;
string loginText;
//reference for Toggle, needs to be assigned in editor
public Toggle rememberToggle;
bool remeberIsOn;
// Use this for initialization
void Start ()
{
loginText = "";
FindLogin();
}
public void FindLogin()
{
if (File.Exists("userSetting.txt"))
{
using (TextReader reader = File.OpenText("userSetting.txt"))
{
string str;
if ((str = reader.ReadLine()) != null) login.text = str;
}
//Debug.Log(loginText);
}
}
public void remember()
{
using (TextWriter writer = File.CreateText("userSetting.txt"))
{
writer.WriteLine(login.text);
}
}
public void loginClick()
{
remeberIsOn = rememberToggle.isOn;
loginText = login.text;
if (remeberIsOn)
{
remember();
}
else
{
using (TextWriter writer = File.CreateText("userSetting.txt"))
{
writer.WriteLine("");
}
}
}
}

Powershell - How to print rendered HTML to a network printer? [duplicate]

I would like to create a function in C# that takes a specific webpage and coverts it to a JPG image from within ASP.NET. I don't want to do this via a third party or thumbnail service as I need the full image. I assume I would need to somehow leverage the webbrowser control from within ASP.NET but I just can't see where to get started. Does anyone have examples?
Ok, this was rather easy when I combined several different solutions:
These solutions gave me a thread-safe way to use the WebBrowser from ASP.NET:
http://www.beansoftware.com/ASP.NET-Tutorials/Get-Web-Site-Thumbnail-Image.aspx
http://www.eggheadcafe.com/tutorials/aspnet/b7cce396-e2b3-42d7-9571-cdc4eb38f3c1/build-a-selfcaching-asp.aspx
This solution gave me a way to convert BMP to JPG:
Bmp to jpg/png in C#
I simply adapted the code and put the following into a .cs:
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;
public class WebsiteToImage
{
private Bitmap m_Bitmap;
private string m_Url;
private string m_FileName = string.Empty;
public WebsiteToImage(string url)
{
// Without file
m_Url = url;
}
public WebsiteToImage(string url, string fileName)
{
// With file
m_Url = url;
m_FileName = fileName;
}
public Bitmap Generate()
{
// Thread
var m_thread = new Thread(_Generate);
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
return m_Bitmap;
}
private void _Generate()
{
var browser = new WebBrowser { ScrollBarsEnabled = false };
browser.Navigate(m_Url);
browser.DocumentCompleted += WebBrowser_DocumentCompleted;
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
browser.Dispose();
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Capture
var browser = (WebBrowser)sender;
browser.ClientSize = new Size(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom);
browser.ScrollBarsEnabled = false;
m_Bitmap = new Bitmap(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom);
browser.BringToFront();
browser.DrawToBitmap(m_Bitmap, browser.Bounds);
// Save as file?
if (m_FileName.Length > 0)
{
// Save
m_Bitmap.SaveJPG100(m_FileName);
}
}
}
public static class BitmapExtensions
{
public static void SaveJPG100(this Bitmap bmp, string filename)
{
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bmp.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}
public static void SaveJPG100(this Bitmap bmp, Stream stream)
{
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bmp.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}
public static ImageCodecInfo GetEncoder(ImageFormat format)
{
var codecs = ImageCodecInfo.GetImageDecoders();
foreach (var codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
// Return
return null;
}
}
And can call it as follows:
WebsiteToImage websiteToImage = new WebsiteToImage( "http://www.cnn.com", #"C:\Some Folder\Test.jpg");
websiteToImage.Generate();
It works with both a file and a stream. Make sure you add a reference to System.Windows.Forms to your ASP.NET project. I hope this helps.
UPDATE: I've updated the code to include the ability to capture the full page and not require any special settings to capture only a part of it.
Good solution by Mr Cat Man Do.
I've needed to add a row to suppress some errors that came up in some webpages
(with the help of an awesome colleague of mine)
private void _Generate()
{
var browser = new WebBrowser { ScrollBarsEnabled = false };
browser.ScriptErrorsSuppressed = true; // <--
browser.Navigate(m_Url);
browser.DocumentCompleted += WebBrowser_DocumentCompleted;
}
...
Thanks Mr Do
Here is my implementation using extension methods and task factory instead thread:
/// <summary>
/// Convert url to bitmap byte array
/// </summary>
/// <param name="url">Url to browse</param>
/// <param name="width">width of page (if page contains frame, you need to pass this params)</param>
/// <param name="height">heigth of page (if page contains frame, you need to pass this params)</param>
/// <param name="htmlToManipulate">function to manipulate dom</param>
/// <param name="timeout">in milliseconds, how long can you wait for page response?</param>
/// <returns>bitmap byte[]</returns>
/// <example>
/// byte[] img = new Uri("http://www.uol.com.br").ToImage();
/// </example>
public static byte[] ToImage(this Uri url, int? width = null, int? height = null, Action<HtmlDocument> htmlToManipulate = null, int timeout = -1)
{
byte[] toReturn = null;
Task tsk = Task.Factory.StartNew(() =>
{
WebBrowser browser = new WebBrowser() { ScrollBarsEnabled = false };
browser.Navigate(url);
browser.DocumentCompleted += (s, e) =>
{
var browserSender = (WebBrowser)s;
if (browserSender.ReadyState == WebBrowserReadyState.Complete)
{
if (htmlToManipulate != null) htmlToManipulate(browserSender.Document);
browserSender.ClientSize = new Size(width ?? browser.Document.Body.ScrollRectangle.Width, height ?? browser.Document.Body.ScrollRectangle.Bottom);
browserSender.ScrollBarsEnabled = false;
browserSender.BringToFront();
using (Bitmap bmp = new Bitmap(browserSender.Document.Body.ScrollRectangle.Width, browserSender.Document.Body.ScrollRectangle.Bottom))
{
browserSender.DrawToBitmap(bmp, browserSender.Bounds);
toReturn = (byte[])new ImageConverter().ConvertTo(bmp, typeof(byte[]));
}
}
};
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
browser.Dispose();
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
tsk.Wait(timeout);
return toReturn;
}
There is a good article by Peter Bromberg on this subject here. His solution seems to do what you need...
The solution is perfect, just needs a fixation in the line which sets the WIDTH of the image. For pages with a LARGE HEIGHT, it does not set the WIDTH appropriately:
//browser.ClientSize = new Size(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom);
browser.ClientSize = new Size(1000, browser.Document.Body.ScrollRectangle.Bottom);
And for adding a reference to System.Windows.Forms, you should do it in .NET-tab of ADD REFERENCE instead of COM -tab.
You could use WatiN to open a new browser, then capture the screen and crop it appropriately.

Render output format (HTML, JSON, XML) depending on parameter?

is there a good or proper way to render the output in Play Framework depending on a parameter? Example:
For HTML:
http://localhost:9000/user/get/5?v=HTML // should render HTML template
For JSON:
http://localhost:9000/user/get/5?v=JSON // should render JSON template
I think that a request interceptor could have the ability to achieve this, but I have no clue how to start or where to start :-(
Or perhaps, write a general render method that reads the parameters and output as requested, but this seems to me like overkill?
If /user/5?v=html and /user/5?v=json return two representations of the same resource, they should be the same URL, e.g. /user/5, according to the REST principles.
On client side, you can use the Accept header in your requests to indicate which representation you want the server to send you.
On server side, you can write the following with Play 2.1 to test the value of the Accept header:
public static Result user(Long id) {
User user = User.find.byId(id);
if (user == null) {
return notFound();
}
if (request().accepts("text/html")) {
return ok(views.html.user(user));
} else if (request().accepts("application/json")) {
return ok(Json.toJson(user));
} else {
return badRequest();
}
}
Note that the test against "text/html" should always be written prior to any other content type because browsers set the Accept header of their requests to */* which matches all types.
If you don’t want to write the if (request().accepts(…)) in each action you can factor it out, e.g. like the following:
public static Result user(Long id) {
User user = User.find.byId(id);
return representation(user, views.html.user.ref);
}
public static Result users() {
List<User> users = User.find.all();
return representation(users, views.html.users.ref);
}
private <T> Result representation(T resource, Template1<T, Html> html) {
if (resource == null) {
return notFound();
}
if (request().accepts("text/html")) {
return ok(html.apply(resource));
} else if (request().accepts("application/json")) {
return ok(Json.toJson(resource));
} else {
return badRequest();
}
}
Write 2 methods, use 2 routes (as you don't specify I will use Java samples:
public static Result userAsHtml(Long id) {
return ok(someView.render(User.find.byId(id)));
}
public static Result userAsJson(Long id) {
return play.libs.Json.toJson(User.find.byId(id));
}
routes:
/GET /user/get/:id/html controllers.YourController.userAsHtml(id:Long)
/GET /user/get/:id/json controllers.YourController.userAsJson(id:Long)
next you can just make a link in other view to display user's data
Show details
Get JSON
or something else...
edit #1
you can also use common if or case to determine final output
public static Result userAsV() {
String vType = form().bindFromRequest().get("v");
if (vTtype.equals("HTML")){
return ok(someView.render(User.find.byId(id)));
}
return play.libs.Json.toJson(User.find.byId(id));
}
I wanted the user to be able to be viewed in the browser as html or as json so the accepts method did not work for me.
I solved it by putting a generic renderMethod in a base class with the following style syntax
public static Result requestType( )
{
if( request().uri().indexOf("json") != -1)
{
return ok(Json.toJson(request()));
}
else
{
return ok("Got HTML request " + request() );
}
}

ASP.NET MVC 2 - Handling files in an edit action; Or, is it possible to create an 'Optional' data annotation which would skip over other attributes?

I've run into a bit of a design issue, and I'm curious if anyone else has run into something similar.
I have a fairly complex model which I have an Edit action method for. Each individual entity has two images associated with it, along with other, more mundane data. These images are [Required] upon creation. When editing an entity, however, these images already exist, since, again, they were required upon creation. Thus, I don't need to mark them as required.
Adding a bit of a monkey wrench to the whole thing is my custom image validation attribute:
public class ValidateFileAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
var file = value as HttpPostedFileBase;
if (file == null)
{
return false;
}
string[] validExtensions = { "jpg", "jpeg", "gif", "png" };
string[] validMimeTypes = { "image/jpeg", "image/pjepeg", "image/gif", "image/png" };
string[] potentialFileExtensions = file.FileName.Split('.');
string lastExtension = potentialFileExtensions[(potentialFileExtensions.Length - 1)];
string mimeType = file.ContentType;
bool extensionFlag = false;
bool mimeFlag = false;
foreach (string extension in validExtensions)
{
if (extension == lastExtension)
{
extensionFlag = true;
}
}
foreach (string mt in validMimeTypes)
{
if (mt == mimeType)
{
mimeFlag = true;
}
}
if (extensionFlag && mimeFlag)
{
return true;
}
else
{
return false;
}
}
}
What I'd ideally like to do would be to create some kind of [Optional] attribute which would bypass the image validator altogether if new files aren't POSTed along with the rest of the form data.
Is something like this possible? If not, how would the collective wisdom of Stack Overflow address the problem?
you might be interested in following article...
but i have to say i do agree with most in the article.
mainly the part : conditional validation
http://andrewtwest.com/2011/01/10/conditional-validation-with-data-annotations-in-asp-net-mvc/
hope this will helps.

Custom IronPython import resolution

I am loading an IronPython script from a database and executing it. This works fine for simple scripts, but imports are a problem. How can I intercept these import calls and then load the appropriate scripts from the database?
EDIT: My main application is written in C# and I'd like to intercept the calls on the C# side without editing the Python scripts.
EDIT: From the research I've done, it looks like creating your own PlatformAdaptationLayer is the way you're supposed to to implement this, but it doesn't work in this case. I've created my own PAL and in my testing, my FileExsists method gets called for every import in the script. But for some reason it never calls any overload of the OpenInputFileStream method. Digging through the IronPython source, once FileExists returns true, it tries to locate the file itself on the path. So this looks like a dead end.
After a great deal of trial and error, I arrived at a solution. I never managed to get the PlatformAdaptationLayer approach to work correctly. It never called back to the PAL when attempting to load the modules.
So what I decided to do was replace the built-in import function by using the SetVariable method as shown below (Engine and Scope are protected members exposing the ScriptEngine and ScriptScope for the parent script):
delegate object ImportDelegate(CodeContext context, string moduleName, PythonDictionary globals, PythonDictionary locals, PythonTuple tuple);
protected void OverrideImport()
{
ScriptScope scope = IronPython.Hosting.Python.GetBuiltinModule(Engine);
scope.SetVariable("__import__", new ImportDelegate(DoDatabaseImport));
}
protected object DoDatabaseImport(CodeContext context, string moduleName, PythonDictionary globals, PythonDictionary locals, PythonTuple tuple)
{
if (ScriptExistsInDb(moduleName))
{
string rawScript = GetScriptFromDb(moduleName);
ScriptSource source = Engine.CreateScriptSourceFromString(rawScript);
ScriptScope scope = Engine.CreateScope();
Engine.Execute(rawScript, scope);
Microsoft.Scripting.Runtime.Scope ret = Microsoft.Scripting.Hosting.Providers.HostingHelpers.GetScope(scope);
Scope.SetVariable(moduleName, ret);
return ret;
}
else
{ // fall back on the built-in method
return IronPython.Modules.Builtin.__import__(context, moduleName);
}
}
Hope this helps someone!
I was just trying to do the same thing, except I wanted to store my scripts as embedded resources. I'm creating a library that is a mixture of C# and IronPython and wanted to distribute it as a single dll. I wrote a PlatformAdaptationLayer that works, it first looks in the resources for the script that's being loaded, but then falls back to the base implementation which looks in the filesystem. Three parts to this:
Part 1, The custom PlatformAdaptationLayer
namespace ZenCoding.Hosting
{
internal class ResourceAwarePlatformAdaptationLayer : PlatformAdaptationLayer
{
private readonly Dictionary<string, string> _resourceFiles = new Dictionary<string, string>();
private static readonly char Seperator = Path.DirectorySeparatorChar;
private const string ResourceScriptsPrefix = "ZenCoding.python.";
public ResourceAwarePlatformAdaptationLayer()
{
CreateResourceFileSystemEntries();
}
#region Private methods
private void CreateResourceFileSystemEntries()
{
foreach (string name in Assembly.GetExecutingAssembly().GetManifestResourceNames())
{
if (!name.EndsWith(".py"))
{
continue;
}
string filename = name.Substring(ResourceScriptsPrefix.Length);
filename = filename.Substring(0, filename.Length - 3); //Remove .py
filename = filename.Replace('.', Seperator);
_resourceFiles.Add(filename + ".py", name);
}
}
private Stream OpenResourceInputStream(string path)
{
string resourceName;
if (_resourceFiles.TryGetValue(RemoveCurrentDir(path), out resourceName))
{
return Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
}
return null;
}
private bool ResourceDirectoryExists(string path)
{
return _resourceFiles.Keys.Any(f => f.StartsWith(RemoveCurrentDir(path) + Seperator));
}
private bool ResourceFileExists(string path)
{
return _resourceFiles.ContainsKey(RemoveCurrentDir(path));
}
private static string RemoveCurrentDir(string path)
{
return path.Replace(Directory.GetCurrentDirectory() + Seperator, "").Replace("." + Seperator, "");
}
#endregion
#region Overrides from PlatformAdaptationLayer
public override bool FileExists(string path)
{
return ResourceFileExists(path) || base.FileExists(path);
}
public override string[] GetFileSystemEntries(string path, string searchPattern, bool includeFiles, bool includeDirectories)
{
string fullPath = Path.Combine(path, searchPattern);
if (ResourceFileExists(fullPath) || ResourceDirectoryExists(fullPath))
{
return new[] { fullPath };
}
if (!ResourceDirectoryExists(path))
{
return base.GetFileSystemEntries(path, searchPattern, includeFiles, includeDirectories);
}
return new string[0];
}
public override bool DirectoryExists(string path)
{
return ResourceDirectoryExists(path) || base.DirectoryExists(path);
}
public override Stream OpenInputFileStream(string path)
{
return OpenResourceInputStream(path) ?? base.OpenInputFileStream(path);
}
public override Stream OpenInputFileStream(string path, FileMode mode, FileAccess access, FileShare share)
{
return OpenResourceInputStream(path) ?? base.OpenInputFileStream(path, mode, access, share);
}
public override Stream OpenInputFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
{
return OpenResourceInputStream(path) ?? base.OpenInputFileStream(path, mode, access, share, bufferSize);
}
#endregion
}
}
You would need to change the constant ResourceScriptsPrefix to whatever your base namespace is where you stored the python scripts.
Part 2, The custom ScriptHost
namespace ZenCoding.Hosting
{
internal class ResourceAwareScriptHost : ScriptHost
{
private readonly PlatformAdaptationLayer _layer = new ResourceAwarePlatformAdaptationLayer();
public override PlatformAdaptationLayer PlatformAdaptationLayer
{
get { return _layer; }
}
}
}
Part 3, finally, how to get a Python engine using your custom stuff:
namespace ZenCoding.Hosting
{
internal static class ResourceAwareScriptEngineSetup
{
public static ScriptEngine CreateResourceAwareEngine()
{
var setup = Python.CreateRuntimeSetup(null);
setup.HostType = typeof(ResourceAwareScriptHost);
var runtime = new ScriptRuntime(setup);
return runtime.GetEngineByTypeName(typeof(PythonContext).AssemblyQualifiedName);
}
}
}
It would be easy to change this to load scripts from some other location, like a database. Just change the OpenResourceStream, ResourceFileExists and ResourceDirectoryExists methods.
Hope this helps.
You can re-direct all I/O to the database using the PlatformAdaptationLayer. To do this you'll need to implement a ScriptHost which provides the PAL. Then when you create the ScriptRuntime you set the HostType to your host type and it'll be used for the runtime. On the PAL you then override OpenInputFileStream and return a stream object which has the content from the database (you could just use a MemoryStream here after reading from the DB).
If you want to still provide access to file I/O you can always fall back to FileStream's for "files" you can't find.
You need to implement import hooks. Here's an SO question with pointers: PEP 302 Example: New Import Hooks