Saturday, September 14, 2013

Email Sending Library

Introduction

This is an small library which will enable your website / web application to send emails instantly. This is fully tested code and provides quick integration.

Background

Today’s application are not just software but a solution. In this solution we always had a need to communicate to the user. There are various ways of communicating, Email is one of them and is widely used. All developers must have felt the need to integrate an email sending option in their solution. If you google you will find various samples, tutorials and articles of doing so. They impart good amount of knowledge. However, developing email sending feature for your project will take good amount of time.  

Using the code

The library uses a single method SendMail for performing the email sending feature. There are five steps involved in the sending feature.
Step One 
//Step 1: Create Mail client, Mail message, Mail addresses.
SmtpClient MailClient = new SmtpClient();
MailMessage Email = new MailMessage();
MailAddress FromMailAddress = new MailAddress(EmailDetails.EmailFrom, EmailDetails.EmailDisplayName);
MailAddress ReplyToMailAddress = new MailAddress(EmailDetails.EmailFrom, EmailDetails.EmailDisplayName);
MailAddress[] ToMailAddress = new MailAddress[EmailDetails.EmailTo.Length]; 
The System.Net.Mail namespece provides with four classes namely SmtpClient, MailMessage, MailAddress and Attachment which will be used for sending email. In this step we create instances of SmtpClient, MailMessage and MailAddress. Here we creating two instances of MailAddress class to allow specify Sender's Email information and Reply to Email information seperately. We have created an array of MailAddress for Recipient's Email to allow multiple email addresses.  
Step Two 
//Step 2: Set the Mail client credentials and enable SSL.
MailClient.Host = ConfigurationManager.AppSettings["EmailHost"];
MailClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["EmailPort"]);
MailClient.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EmailUsername"], ConfigurationManager.AppSettings["EmailPassword"]);
MailClient.EnableSsl = true;  
In this step email server details with credentials are set. All these are taking from <appSettings>. The following settings are added to the web.config file from where the library will get the information. 
Settings (web.config)
<appSettings>
    <add key="EmailFrom" value="tester000@gmail.com"/>
    <add key="EmailUsername" value="tester000@gmail.com"/>
    <add key="EmailPassword" value="tester1234"/>
    <add key="EmailHost" value="smtp.gmail.com"/> 
    <add key="EmailPort" value="587"/>
</appSettings> 
Since the library takes the settings from web.config no changes to the code are required. 
Note: The setting name should exactly be same as mentioned in the settings block above.
Step Three
//Step 3: Set all Email options.
Email.From = FromMailAddress;
Email.ReplyTo = ReplyToMailAddress;
Email.Subject = EmailDetails.EmailSubject;
Email.Body = EmailDetails.EmailContents;
Email.IsBodyHtml = true;
for (int i = 0; i < ToMailAddress.Length; i++)
{
                    string EmailDisplayName = string.IsNullOrEmpty(EmailDetails.EmailToDisplayName[i]) ? "Recepient " + i.ToString() : EmailDetails.EmailToDisplayName[i];
                    ToMailAddress[i] = new MailAddress(EmailDetails.EmailTo[i], EmailDisplayName);
                    Email.To.Add(ToMailAddress[i]);
}  
Now all the options required for sending email are set the Sender, Recipients, Subject and Body. Since there can be multiple Recipients, a for loop all of them to MailMessage.
Step Four
//Step 4: Set all the attachments.
if (EmailDetails.EmailAttachments!=null)
{
 Attachment EmailAttachment = null;
 for (int i = 0; i < EmailDetails.EmailAttachments.Length; i++)
 {
  EmailAttachment = new Attachment(EmailDetails.EmailAttachments[i]);
                Email.Attachments.Add(EmailAttachment);
 }
}  
Now all attachments are added to the MailMessage. If there are no attachments pass null and the attachment adding step is skipped.
Step Five
//Step 5: Send Email.
MailClient.Send(Email);
Status = true; 
This is the final step where email is sent. The Send method doesn't return anything. In case it fails it throws an exception. The exception is captured and false status is returned to the calling method. A boolean value is returned indicating whether sending was success or failure.

The attached sample contains a sample web form with the method call and also the library source code. This library can be used by adding reference to the library(dll) in other projects.
To send email, simply call SendEmail method as mentioned below 
Method Call
ResultLBL.Text = SLEmail.SendEmail(ToTBX.Text, "Tester", SubjectTBX.Text, BodyTBX.Text, null, true).ToString(); 
Parameters 
  • Recipient's Email
  • Recipient's Name
  • Subject
  • Body of Email 
  • Attachments
  • Whether the Email service uses SSL?

Points of Interest

We always look at software reusability. I used to copy paste this code in all my applications and would ideally change the Email Server Credentials and other related details in the code. I learned how I can create a library(dll) which can be reused and made pluggable by reading the Email Server Credentials and other related details from a config file rather than editing the code.

Using class object as parameter to pass values which avoids changes to the method definition and method call. Also, we need not worry about the sequence. You can simply add members to class when you need to add parameters. 

History

I would welcome suggestions from all of you. Also, planning to enhance this library with more capabilities. 

Saturday, January 29, 2011

AJAX Client Control for ASP.Net

We all experienced the power of AJAX. May it be any web platform you are using for developing a web application, you can work with AJAX. With regards to ASP.Net we have AJAX Control Library which provides us with extensions and also with controls which makes using AJAX in our web applications a breeze.

Basically, ASP.Net is a technology which is server based and all the processing happens at server end. At times you need things to work at client end but still wish to utilize the power of server side processing which is inherited by the ASP.Net server controls. These controls are the ASP.NET AJAX representations of DOM elements, allowing you to program against these elements using the ASP.NET AJAX Framework. So now you harness the power of server controls for your client controls.

More on this read this

Dataset and Visual Studio Development.

Today, had to decide on the Data Layer of my Web Application and had to finalize the implementation that had to be done. I analyzed the last application to find out how it was done. Also, I searched for some content on the web.

After some research I found that it can be done in two ways. One to have my business logic done in a class file which interacts with the Data and provides application with a Dataset or Datatable object with the data. Second, to have a Dataset item added to my project which is an XML Style Definition file encapsulating my data and logic.

On a detailed research I found that the later option is strongly typed and has more usability with other components than the former. This also enables the IDE to provide intellisense to the developer.

The best part is you don't code just drag & drop and it's done. Yes without doubt the actual integration of this Dataset in your project needs some basic understanding of the Dataset is organized and how you can harness the power it has.

Monday, January 3, 2011

Saturday, December 25, 2010

Choosing CSS Versions

When working with Cascading Style Sheets you often find yourself working with specific versions. 

Click here find more ...

Wednesday, December 8, 2010

Verify a List of URLs in C# Asynchronously

Recently I wanted to test a bunch of URLs to see whether they were broken/valid.  In my scenario, I was checking on URLs for advertisements that are served by Lake Quincy Media’s ad server (LQM is the largest Microsoft developer focused advertising network/agency).  However, this kind of thing is an extremely common task that should be very easy for any web developer or even just website administrator to want to do.  It also gave me an opportunity to use the new asynch features in .NET 4 for a production use, since prior to this I’d only played with samples.

Check if a URL is OK

First, you’ll need a method that will tell you whether a given URL is OK.  What OK means might vary based on your needs – in my case I was just looking for the status code.  I found the following codehere.

   1: private static bool RemoteFileExists(string url)
   2: {
   3:     try
   4:     {
   5:         var request = WebRequest.Create(url) as HttpWebRequest;
   6:         request.Method = "HEAD";
   7:         var response = request.GetResponse() as HttpWebResponse;
   8:         return (response.StatusCode == HttpStatusCode.OK);
   9:     }
  10:     catch
  11:     {
  12:         return false;
  13:     }
  14: }

 

Using this Synchronously

If you want to use this synchronously, it’s pretty simple.  Get a list of URLs and write a loop something like this:

   1: foreach (var link in myLinksToCheck)
   2: {
   3:    link.IsValid = RemoteFileExists(link.Url);
   4: }

 

I checked about 1500 URLs with my script and I wrote it with a flag that would let me run it synch or asynch.  The synchronous version took about an hour and forty minutes to complete.  The asynch one took about seventeen minutes to complete.

Make it Parallel

If you want to see how to do things using the parallel libraries that are now part of .NET 4, there’s no better place to start than the Samples for Parallel Programming with the .NET Framework 4.  There’s some very cool stuff here.  Be sure to check out the Conway’s Game of Life WPF sample.

For me, there were two steps I had to take to turn my synchronous process into a parallelizable process.

1. Create an Action<T> method that would perform the URL check operation and store the result in my collection.  I created a method UpdateUrlStatus(Link linkToCheck) to do this work.

2. Call this method using the new Parallel.For() helper found in System.Threading.Tasks.

Here’s the code, slightly modified from my own domain-specific code:

   1: var linkList = GetLinks();  
   2: Console.WriteLine("Loaded {0} links.", linkList.Count);
   3:     
   4: Action<int> updateLink = i =>
   5:     {
   6:         UpdateLinkStatus(linkList[i]);
   7:         Console.Write(".");
   8:     };
   9: Parallel.For(0, linkList.Count, updateLink);
  10:  
  11: // replaces this synchronous version:
  12: for(int i=0; i < linkList.Count; i++)
  13: {
  14:     updateLink(i);
  15: }

 

In my scenario, using the parallel instead of the iterative approach dropped the time from about 100 minutes down to about 17.  That’s on a machine that appears to windows to have 8 cores.  100/8 = 12.5 so it’s not quite a straight eightfold increase, but it’s close.  If you’ve got applications that are doing a lot of the same kind of work and each operation has little or no dependencies on the other operations, consider using Action<T> and Parallel.For() to take advantage of the many cores available on most modern computers to speed it up.

Resource: http://stevesmithblog.com/blog/verify-a-list-of-urls-in-c-asynchronously/

 

 

Monday, December 6, 2010

HTML and Javascript injection

Introduction

This article is about HTML and Javascript injection techniques used to exploit web site vulnerabilities. Nowadays it's not usual to find a completely vulnerable site to this type of attacks, but only one is enough to exploit it.
I'll make a compilation of these techniques all together, in order to facilitate the reading and to make it entertaining.
HTML injection is a type of attack focused upon the way HTML content is generated and interpreted by browsers at client side.
Otherwise, Javascript is a widely used technology in dynamic web sites, so the use of technics based on this, like injection, complements the nomenclature of 'code injection'. 

Code injection

This type of attack is possible by the way the client browser has the ability to interpret scripts embedded within HTML content enabled by default, so if an attacker embeds script tags such <SCRIPT>, <OBJECT>,<APPLET>, or <EMBED> into a web site, web browser's Javascript engine will execute it.
A typical target of this type of injection are forums, guestbooks, or whatever section where administrator allows the insertion of text comments; if the design of the web site isn't parsing the comments inserted and takes '<' or '>' as real chars, a malicious user could type :

 Collapse
I like this site because <script>alert('Injected!');</script> teachs me a lot 

If it works and you can see the message box, the door is opened to attacker's imagination limits!. A common code insertion used to drive navigation to another website is something like this:

 Collapse
<H1> Vulnerability test </H1> 
 Collapse
<META HTTP-EQUIV="refresh" CONTENT="1;url=http://www.test.com">

  Same within <FK> or <LI> tag :

 Collapse
<FK STYLE="behavior: url(http://<<Other website>>;">

Other tags used to execute malicious Javascript code are, for example, <BR><DIV>, even background-image:

 Collapse
<BR SIZE="&{alert('Injected')}"> 
<DIV STYLE="background-image: url(javascript:alert('Injected'))">

<TITLE> tag is a common weak point if it's generated dynamically. For example, suppose this situation: 

 

 Collapse
<HTML>
<HEAD>
<TITLE><?php echo $_GET['titulo']; ?>
</TITLE> 
</HEAD> 
<BODY> 
...
</BODY> 
</HTML>
 
If you build titulo as 'example </title></head><body><img src=http://myImage.png>', HTML resulting would insert 'myImage.png' image first of all :  

 Collapse
<HTML>
<HEAD>
<TITLE>example</title></head><body><img src=http://myImage.png></TITLE>
</HEAD>
<BODY>
...
</BODY>
</HTML>
 
There is another dangerous HTML tag that could exploit web browser's frames support characteristic :<IFRAME>. This tag allows (within Sandbox security layer) cross-scripting exploiting using web browser elements (address bar or bookmarks for example), but this theme is outside the scope of this article.

Otherwise, there is a commonly technique widely known as “in-line” code injection. This technique exploits javascript functions “alert” and “void”.
Testing it is very easy, just navigate to whatever site, and type in web browser's address bar:

 

 Collapse
javascript:alert('Executed!');

This is not a harmful script, as you see, but suppose you want to get information about the site, for example if it is using cookies or not, you could type something like this :

 Collapse
javascript:alert(document.cookie); 


If the website is not using cookies, no problem, but case else, you could read values like server session ID, or any user data stored in cookies by the application.

Suppose now that we use the void() javascript function instead of alert(). This function returns a NULL value to the web Browser, so no recharging page action is executed. We could change DOM values   inside this function and no navigation change state would occur. Imagine you've found a site that stores PHP session ID in the common cookie 'PHPSESSID'; if we start a new navigation to the same website in another webbrowser instance, we'll get a new 'PHPSESSID'; we could change session Ids in both instances by typing:

 Collapse
javascript: void(document.cookie=”PHPSESSID = <<Any other session ID>>”); alert(document.cookie);

You will see in the message box the new session ID assigned to the actual one. This example shows too the possibility of concatenate more than one action in the same line of execution.

Only taking a look to site cookies you could find some very descriptive one implementing security features, for example, if you find a site cookie like “logged=no”, probably you could go into the logged area simply by changing that cookie value:

 Collapse
javascript: void(document.cookie=”logged=yes”); 

Following this line, it's possible to modify any DOM object using javascript and inject it using previous techniques. Analyzing the source code of a web page you may find it uses forms (<FORM>) for different purposes; in this case, you could change any form field value using void() function, too. Suppose a shopping portal with a  shopping cart; if site designer didn't take care of this type of injection, you could fill the cart and pay for it only $1:

 Collapse
javascript:void(document.forms[0].total.value=1);

These other techniques are named indirect code injection; not only cookies or forms modification are exploited by this technique, any DOM component or HTTP header is exposed.

So, it's very important to keep in mind these code injection techniques when developing web applications as far as possible to make it a more safe application. 

Preventing code injection

When developing web applications it's very recommendable to follow the next considerations to prevent possible code injection :

  • Do not rely on client side Javascript validation whenever possible; as shown before, this is easily deceived using “in-line” injection. For example, suppose you have a shopping portal where you rely the price of each item at client side.
          Suppose yo have only one form to store the shopping chart;attackers could modify you bill, simply by     changing the price as seen before :
 Collapse
javascript:void(document.forms[0].price.value=1);

Solution to this situation is just maintaining shopping chart actions on server side, and getting client side refreshed via AJAX, for example.

  • Don't store sensible data into cookies, cause they can be easly modified by an attacker, as seen before. If you need to store data in cookies, store it with a hash signature generated with a server side key.
  • Never use hidden boxes to hold items because they can be hard coded into the code. Otherwise, you should always validate that fields at server side using a secure algorythm with data received from client as input :

 signatures.png

  • Like <TITLE> example above, you better not use dynamic DOM element generation. 
  • Take care about dynamic evaluation vulnerabilities (like <TITLE> example above). Imagine this piece of code in a PHP page :  

 

 Collapse
      $dato = $_GET['formAge']; 
eval('$edad = ' . $dato . ';');

eval() parameters will be processed, so if “formAge” is set to "5; system('/bin/rm -rf *')", additional code will be executed on server and will remove all files. Dangerous, don't you think so?

 

  • If you are developing a web site that allows user to upload content (forum, guestbook, “contact me”, etc), you may split special HTML chars, so injected tags will maintain in the website, but will not be executed; you can get this with strip_tags() PHP function, htmlentities(), urlencode() or htmlspecialchars(), for example.
  • Use SSL certificate for sensible operations; this doesn't avoid javascript injection, but avoids sensible data from being read by anyone else.



Ultimately, best defense to code injection attacks resides on “Best practices” while programming.