Monday, 11 March 2024

Read Outlook mail c sharp .net C# Azure Active Directory

 using Microsoft.Exchange.WebServices.Data;

using MailKit;

using MailKit.Net.Imap;

using MailKit.Search;

using MailKit.Security;

using Microsoft.Identity.Client;

using Microsoft.Win32.SafeHandles;

using MimeKit;

using Newtonsoft.Json;

using Newtonsoft.Json.Linq;

using System;

using System.Collections.Generic;

using System.Configuration;

using System.Data;

using System.Data.SqlClient;

using System.IO;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Net.Mail;

using System.Runtime.InteropServices;

using System.Security.Authentication;

using System.Text;

using System.Text.RegularExpressions;

using System.Threading;

using System.Threading.Tasks;

using System.Windows.Forms;


namespace PopClient

{

    static class Program

    {

        #region SASMechanism Variables

        static readonly string tenant = "tenant";

        static readonly string smtp_server = "smtp.office365.com";

        static readonly string aad_app_id = "aad_app_id";

        static readonly string aad_app_secret = "aad_app_secret";

        static readonly string user = "user";

        static readonly string pass = "pass";

        static readonly string imap_server = "outlook.office365.com";

        #endregion

        const string ExchangeAccount = "pass";

        /// <summary>

        /// The main entry point for the application.

        /// </summary>

        static void Main()

        {

            #region SecurityProtocolType  Setting 

            try

            { //try TLS 1.3

                ServicePointManager.SecurityProtocol = (SecurityProtocolType)12288

                                                     | (SecurityProtocolType)3072

                                                     | (SecurityProtocolType)768

                                                     | SecurityProtocolType.Tls;

            }

            catch (NotSupportedException)

            {

                try

                { //try TLS 1.2

                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072

                                                         | (SecurityProtocolType)768

                                                         | SecurityProtocolType.Tls;

                }

                catch (NotSupportedException)

                {

                    try

                    { //try TLS 1.1

                        ServicePointManager.SecurityProtocol = (SecurityProtocolType)768

                                                             | SecurityProtocolType.Tls;

                    }

                    catch (NotSupportedException)

                    { //TLS 1.0

                        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

                    }

                }

            }

            #endregion        

            MainAsync().GetAwaiter().GetResult();

            Console.ReadLine();

        }

        static async System.Threading.Tasks.Task MainAsync()

        {

                       var cca = ConfidentialClientApplicationBuilder

                .Create(aad_app_id)

                .WithClientSecret(aad_app_secret)

                .WithTenantId(tenant)

                .Build();


            var ewsScopes = new string[] { "https://outlook.office365.com/.default" };

            try

            {

                var authResult = await cca.AcquireTokenForClient(ewsScopes)

                    .ExecuteAsync();


                // Configure the ExchangeService with the access token

                var ewsClient = new ExchangeService();

                ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");

                ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);

                ewsClient.ImpersonatedUserId =

                    new ImpersonatedUserId(ConnectingIdType.SmtpAddress, user);


                //Include x-anchormailbox header

                ewsClient.HttpHeaders.Add("X-AnchorMailbox", user);


                // Make an EWS call

                // Read 100 mails

                foreach (EmailMessage email in ewsClient.FindItems(WellKnownFolderName.Inbox, new ItemView(10)))

                {

                    string strFrom = "", ToRecipients = "", BccRecipients = "", CcRecipients = "", Subject = "", Body = "", TextBody = "", Attachments = "";

                    //email.Load(new PropertySet(EmailMessageSchema.ConversationTopic, ItemSchema.Attachments,

                    // ItemSchema.TextBody));

                    PropertySet plainTextPropertySet = new PropertySet(BasePropertySet.FirstClassProperties)

                    { RequestedBodyType = BodyType.Text, };

                    EmailMessage emailMessage = EmailMessage.Bind(ewsClient, email.Id, plainTextPropertySet);

                    string body = emailMessage.Body.Text;

                    email.IsRead = true;

                    email.Update(ConflictResolutionMode.AutoResolve);


                    strFrom = email.From.Address;

                    Console.WriteLine(email.ConversationTopic);

                    Console.WriteLine("From : " + strFrom);

                    Console.WriteLine("To : " + email.ToRecipients.ToString());

                    Console.WriteLine("BCC : " + email.BccRecipients);

                    Console.WriteLine("CC : " + email.CcRecipients);


                    Console.WriteLine("Subject : " + email.Subject);

                    EmailMessage message = EmailMessage.Bind(ewsClient, new ItemId(email.Id.ToString()));

                    if (message.HasAttachments && message.Attachments[0] is FileAttachment)

                    {

                        FileAttachment fileAttachment = message.Attachments[0] as FileAttachment;

                        fileAttachment.Load(@"C:\PRAMOD\PROJECT\ReadMailOutlook\PopClient\PopClient\\Attachments\\" + fileAttachment.Name);

                       // lblAttach.Text = "Attachment Downloaded : " + fileAttachment.Name;

                    }

                     }

 }

            catch (MsalException ex)

            {

                Console.WriteLine($"Error acquiring access token: {ex}");

            }

            catch (Exception ex)

            {

                Console.WriteLine($"Error: {ex}");

            }


            if (System.Diagnostics.Debugger.IsAttached)

            {

                Console.WriteLine("Hit any key to exit...");

                Console.ReadLine();

            }

        }


    public class MailMessages

    {

        public MimeMessage mMessage { get; set; }

        public IMailFolder imFolder { get; set; }

        public UniqueId uid { get; set; }

    }

}


Thursday, 8 February 2024

SecurityProtocolType TLS use in code without error for - Tls11, Tls12, and Tls13

 try { //try TLS 1.3

    ServicePointManager.SecurityProtocol = (SecurityProtocolType)12288

                                         | (SecurityProtocolType)3072

                                         | (SecurityProtocolType)768

                                         | SecurityProtocolType.Tls;

} catch (NotSupportedException) {

    try { //try TLS 1.2

        ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072

                                             | (SecurityProtocolType)768

                                             | SecurityProtocolType.Tls;

    } catch (NotSupportedException) {

        try { //try TLS 1.1

            ServicePointManager.SecurityProtocol = (SecurityProtocolType)768

                                                 | SecurityProtocolType.Tls;

        } catch (NotSupportedException) { //TLS 1.0

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

        }

    }

}


Thursday, 10 November 2022

get Tiny URL

 public static string getTinyURL(string url_)

    {

        string retVal = "";

        try

        {


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://tinyurl.com/api-create.php?url=" + url_);

            if (HttpContext.Current.Request.Url.Authority.Trim().ToLower().Contains("".Trim().ToLower()) || HttpContext.Current.Request.Url.Authority.Trim().ToLower().Contains("localhost".Trim().ToLower()))

            { }

            else

            {

                WebProxy myproxy = new WebProxy("", 8080);

                myproxy.BypassProxyOnLocal = false;

                request.Proxy = myproxy;

            }

            request.Method = "GET";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            StreamReader srd = new StreamReader(response.GetResponseStream());

            retVal = srd.ReadToEnd();

        }

        catch (Exception ex)

        {

            

        }


        return retVal;

    } 


Get Convert DateTime

 public DateTime GetConvertDateTime(string Date)

    {

        DateTime date = new DateTime();

        string CurrentPattern = Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern;

        string[] Split = new string[] { "-", "/", @"\", "." };

        string[] Patternvalue = CurrentPattern.Split(Split, StringSplitOptions.None);

        string[] DateSplit = Date.Split(Split, StringSplitOptions.None);

        string NewDate = "";

        try

        {

            NewDate = DateSplit[0] + "/" + DateSplit[1] + "/" + DateSplit[2];


            date = DateTime.Parse(NewDate, Thread.CurrentThread.CurrentCulture);


        }

        catch (Exception ex)

        {

            NewDate = DateSplit[1] + "/" + DateSplit[0] + "/" + DateSplit[2];


            date = DateTime.Parse(NewDate, Thread.CurrentThread.CurrentCulture);

        }

        finally

        {


        }


        return date;


    }






 Create Google SMTP App password and use  those password for mail send

Create password URL: 

https://myaccount.google.com/security

https://myaccount.google.com/apppasswords

https://myaccount.google.com/u/0/apppasswords

Thursday, 25 March 2021

VAPT

<meta http-equiv="Content-Security-Policy" content="default-src 'self' * 'unsafe-inline'; child-src *; object-src *; frame-src *; script-src * 'unsafe-inline' 'unsafe-eval'; style-src * 'unsafe-inline'; font-src *">

 -----------

 void Application_PreSendRequestHeaders(object sender, EventArgs e)

    {

        HttpContext.Current.Response.Headers.Remove("Server");

        Response.Headers.Set("Server", "My httpd server");


        HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");

        Response.Headers.Set("X-AspNet-Version", "XXX");


        HttpContext.Current.Response.Headers.Remove("X-AspNetMvc-Version");

        Response.Headers.Set("X-AspNetMvc-Version", "XXX");


        HttpContext.Current.Response.Headers.Remove("X-Powered-By");

        Response.Headers.Set("X-Powered-By", "XXX");  

    }



https://portswigger.net/research/exploiting-cors-misconfigurations-for-bitcoins-and-bounties

https://portswigger.net/web-security/cors


Access-Control-Allow-Origin: https://www.drreddys.com/

Access-Control-Allow-Credentials: true

-------------

Cookies HttpOnly 

<add name="strict-transport-security" value="max-age=31536000" />: 

<compilation debug="false" targetFramework="4.7.1" numRecompilesBeforeAppRestart="2000">

--------

<system.webServer>

    <httpProtocol>

      <customHeaders>

        <add name="Cache-Control" value="no-cache, no-store, must-revalidate, pre-check=0, post-check=0, max-age=0, s-maxage=0" />

        <add name="Pragma" value="no-cache" />

        <add name="Expires" value="0" />

<add name="X-Frame-Options" value="deny" />

<add name="X-content-type-options" value="nosniff" />

<add name="strict-transport-security" value="max-age=31536000" />

      </customHeaders>

    </httpProtocol>

    </system.webServer>


1. XPath injection                                     –Pramod -- done

5. Input returned in response (reflected)               –Pramod -- Done

6. Suspicious input transformation (reflected)     –Pramod –Done

7. Cross-domain Referer leakage                               -- Sudha --WIP



$("input[type='checkbox'][name='checkhlprof']:checked").length

$("input[type='checkbox'][name='checkhltermcond']:checked").length



1. XPath injection

WIP


2. SSL certificate

Nitin : please check the SSL certificate


3. Content type incorrectly stated

<add name="X-content-type-options" value="nosniff" />


4. Strict transport security not enforced

I have redirect from http to https 

  <rewrite>

   <rules>

      <rule name="HTTPS Rule behind AWS Elastic Load Balancer Rule" stopProcessing="true">

         <match url="^(.*)$" ignoreCase="false" />

         <conditions>

            <add input="{HTTP_X_FORWARDED_PROTO}" pattern="^http$" ignoreCase="false" />

         </conditions>

         <action type="Redirect" url="https://{SERVER_NAME}{URL}" redirectType="Found" />

      </rule>

   </rules>

</rewrite>



5. Input returned in response (reflected)

WIP



6. Suspicious input transformation (reflected)

Error page Default redirect ot error page thus response is showing "error page" by Umbraco CMS


9. Frameable response (potential Clickjacking)

<add name="X-Frame-Options" value="deny" />sameorigin


10. Cacheable HTTPS response

 <add name="Cache-Control" value="no-cache, no-store, must-revalidate, pre-check=0, post-check=0, max-age=0, s-maxage=0" />

        <add name="Pragma" value="no-cache" />

        <add name="Expires" value="0" />



7. Cross-domain Referer leakage

https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css

https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js


8. Cross-domain script include

https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js


Thursday, 21 January 2021

RSS feed API read and show on your website

 private string ParseRssFile()

{
    XmlDocument rssXmlDoc = new XmlDocument();

    // Load the RSS file from the RSS URL
    rssXmlDoc.Load("http://feeds.feedburner.com/techulator/articles");

    // Parse the Items in the RSS file
    XmlNodeList rssNodes = rssXmlDoc.SelectNodes("rss/channel/item");

    StringBuilder rssContent = new StringBuilder();

    // Iterate through the items in the RSS file
    foreach (XmlNode rssNode in rssNodes)
    {
        XmlNode rssSubNode = rssNode.SelectSingleNode("title");
        string title = rssSubNode != null ? rssSubNode.InnerText : "";
                
        rssSubNode = rssNode.SelectSingleNode("link");
        string link = rssSubNode != null ? rssSubNode.InnerText : "";
                
        rssSubNode = rssNode.SelectSingleNode("description");
        string description = rssSubNode != null ? rssSubNode.InnerText : "";

        rssContent.Append("<a href='" + link + "'>" + title + "</a><br>" + description);
    }

    // Return the string that contain the RSS items
    return rssContent.ToString();
}