Showing posts with label Utility. Show all posts
Showing posts with label Utility. Show all posts

Friday, August 5, 2011

PowerShell script for dumping access control lists (ACL)

I don’ t know if I have ever mentioned, that I am in charge for the security of some of our systems. According to “The Open Web Application Security Project (OWASP)” (https://www.owasp.org/index.php/Top_10_2010-Main) security misconfiguration is at the 6th place of the TOP10 Risks. Since I am responsible for a web cluster I wrote a small PowerShell script for reporting the access control list (ACLs) . Given an root folder, the script traverse all child object recursively (depth first) and it only outputs those ACLs which are not inherited by the parent folder. I use the script for doing security reviews. This script can be also very useful if you are planning to migrate a webserver.

Clear-Host
$path =  $args[0]   
$outPutFile =  $args[1]  
$startDate = Get-Date 
$newLine = "`r`n" #is a carrage return/line feed. 

#check input parameters
if([System.IO.Directory]::Exists($path) -eq $false){
    throw (new-object System.IO.DirectoryNotFoundException("Directory does not exist or is missing!"))
}
If($path.EndsWith("\"))
{
    $path = $path.Remove($path.Length-1, 1)
}
if ([System.String]::IsNullOrEmpty($outPutFile)){
    throw (new-object System.ApplicationException("OutputFile is missing!"))
}

#Build information for the header of the output file, if file exist it will be owerwritten!  
$header = "Start: " + $startDate + $newLine + "Output file: " + $outPutFile + $newLine + "ACL of the analyzed path: " + $path + $newLine
$mainPathAcl = get-ACL $path | Format-List
out-file -encoding ASCII -filePath $outPutFile -InputObject $header
out-file -encoding ASCII -filePath $outPutFile -append -InputObject $mainPathAcl

#depth first traverse
$myStack = new-object  System.Collections.Stack 
[System.IO.DirectoryInfo]$rootInfo = New-Object System.IO.DirectoryInfo($path)
$myStack.Push($rootInfo)

while ($myStack.Count -ne 0){
    $actualItem = $myStack.Pop();  #get last item
    #add children to stack
    if ($actualItem -is [System.IO.DirectoryInfo])
    {
        [System.IO.FileSystemInfo[]]$dirs2 = $actualItem.GetFileSystemInfos() | Sort-Object Name -Descending
        if ($dirs2){#check if it is null.
            Foreach ($dir1 in $dirs2) {  #add to the stack
                $myStack.Push($dir1)
            }
        }
        
        if($actualItem.Parent.FullName -eq $rootInfo.FullName){
            $appHeader = "" + $newLine + "------------------------" + $newLine + $actualItem.Name + $newLine + "------------------------"
              out-file -encoding ASCII -filePath $outPutFile -append -InputObject $appHeader    
        }
    }
    
    #dump acls if not inherited
    $aclActFile = Get-Acl -Path $actualItem.FullName
    $WriteFileHeader = $true; 
    Foreach ($Access in $aclActFile.Access) { 
        $Inherited = [string]$Access.IsInherited 
        if ($Inherited -eq "False") {
            #write File Header
              if ($WriteFileHeader) {
                $fileHeader = "File: " + $actualItem.FullName + $newLine + "SDDL: " + $aclActFile.Sddl
                out-file -encoding ASCII -filePath $outPutFile -append -InputObject  $fileHeader
                $WriteFileHeader = $false;
            }
            #write AccessControl in csv
            $output = "ACL:  " + $Access.AccessControlType + ", " + $Access.IdentityReference + ", " + $Access.FileSystemRights 
            out-file -encoding ASCII -filePath $outPutFile -append -InputObject $output
        }    
    }
}

#Footer
$endDate = Get-Date 
$elapsedTime = $endDate - $startDate 
$footer = "" + $newLine + "Run completed at: " + $endDate + $newLine + "Elapsed Time:" + $newLine + $elapsedTime + $newLine
out-file -encoding ASCII -filePath $outPutFile -append -InputObject $footer 

Instructions:

  1. Copy this script in a file (example: aclDump.ps1)
  2. Open PowerShell
  3. Execute the following cmd, where parameter 1 is the root folder for dumbing ACL, and parameter 2 is the output file: .\aclDump.ps1 X:\Intepub C:\AclReport.txt.

PS: If you need to full backup ACLs or to transfer ACLs you should use tools like: SubInAcl (http://www.microsoft.com/download/en/details.aspx?id=23510)

Sunday, July 24, 2011

Putting it all together: ASP.NET MVC, SQLite, NHibernate, Fluent NHibernate & Log4Net

Today, I will explain how to set up a ASP.NET MVC project, which is using NHibernate for accessing a SQLite Database and Fluent NHibernate for configuring NHibernate. In this post I will give you a general overview about the structure of the project and in my future posts I will explain more in detail single its parts.

The sample project which can be downloaded from the following link http://dl.dropbox.com/u/36200417/MvcNhibernate.zip was setup as explained below.

The project is divided in two subprojects:
a)    MVC Web application
b)    DAL (Data Access Layer)

In a real project I would have more layers and subprojects, but for this example I want to keep it simple and therefore I removed the business layer.

First I was referencing all needed dlls:
- fluentnhibernate-NH3.0-binary-1.2.0.694
- log4net
- NHibernate-3.0.0.GA-bin
- SQLite-1.0.66.0-binaries

Afterwards I was generating a Database with the following command:sqlite3 test.db.

Copying the test.db file to the App_Data folder and adding the following connection string allows Asp.Net to access the SqLite Database.

<connectionStrings>
  <add name="SqLiteCon" connectionString="data source=|DataDirectory|test.db;" />
</connectionStrings>

Let’s now investigate on the structure of the project:

Project DAL:
/DAO: Data Access Objects provide abstract interfaces to a persistence medium like a database
/DAO/Interface: Interfaces for DAOs
/DAO/Implementation: Concrete implementation that provides access to the database with NHibernate. Note: BasicNhDAO<T, EntityKey> is a base class that provides basic functions (=CRUD). For every entity a DAO object exists, that is responsible for persisting the entity.
/Entities: Plain objects for encapsulating data.
/Entities/Interface: Interfaces for the plain objects
/Entities/Implementation:
/Mapping: FluentNHibernate Mappings, which are containing information how to map entities to tables of a database.
/SessionStorage: small framework for managing the NHibernate Session.

Project MvcNhibernate:
/App_Data: contains the SqLite database file
/Controllers: MVC Controllers. SqLiteController contains the logic for this example.
/Views/SqLite: MVC Views that are interesting for this example.

Thursday, July 21, 2011

ASP.NET MVC 3.0: CheckBoxListFor

Salve sviluppatori! È passato diverso tempo dal mio ultimo blog in italiano, perciò eccovi un metodo assolutamente utile per chi di voi sviluppa applicazioni web con ASP.NET MVC. Il metodo, che oggi vi propongo, serve per mostrare una lista di caselle di controllo (="Checkboxes"). Ricapitolando nel "Controller" vengono preparati i dati che verranno incorporati in un oggetto (="Model"), che poi verranno passati ed elaborati da una "View". Il metodo, che oggi vi presento, verrà utilizzato nella "View" ed estende la classe "HtmlHelper".

public static MvcHtmlString CheckBoxListFor<TModel, TKey, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, IDictionary<TKey, TValue>>> expForAvailableItems, Expression<Func<TModel, IList<TKey>>> expForSelectedKey)
{
    return CheckBoxListFor(htmlHelper, expForAvailableItems, expForSelectedKey, x => Convert.ToString(x), x => Convert.ToString(x), null, null);
}

public static MvcHtmlString CheckBoxListFor<TModel, TKey, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, IDictionary<TKey, TValue>>> expForAvailableItems, Expression<Func<TModel, IList<TKey>>> expForSelectedKey, Expression<Func<TValue, string>> expForValueToString, Expression<Func<TKey, string>> expForKeyToString, IDictionary<String, Object> htmlAttributesForListDiv = null, IDictionary<String, Object> htmlAttributesForItemDiv = null)
{
    //the name for the checkbox 
    string name = ExpressionHelper.GetExpressionText(expForSelectedKey);
    string HtmlName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
    if (String.IsNullOrEmpty(HtmlName))
    {
        throw new NullReferenceException("HtmlName is null");
    }

    //available items
    IDictionary<TKey, TValue> availableItems = expForAvailableItems.Compile().Invoke(htmlHelper.ViewData.Model);

    //selected items
    IList<TKey> selectedItems = expForSelectedKey.Compile().Invoke(htmlHelper.ViewData.Model);

    //convert value to string function
    Func<TValue, string> funcValueToString = expForValueToString.Compile();

    //convert key to string function
    Func<TKey, string> funcKeyToString = expForKeyToString.Compile();

    //Convert to checkboxlist
    TagBuilder listDiv = new TagBuilder("div");
    listDiv.MergeAttributes(htmlAttributesForListDiv, true);

    StringBuilder listItemsBuilder = new StringBuilder();
    // Define items
    // Loop through items
    Int32 index = 0;
    foreach (var item in availableItems)
    {
        // Define div
        TagBuilder inputdiv = new TagBuilder("div");
        inputdiv.MergeAttributes(htmlAttributesForItemDiv, true);

        // Define input 
        TagBuilder input = new TagBuilder("input");
        if (selectedItems.Contains(item.Key))
            input.MergeAttribute("checked", "checked");
        input.MergeAttribute("id", String.Concat(name, index));
        input.MergeAttribute("name", name);
        input.MergeAttribute("type", "checkbox");
        input.MergeAttribute("value", funcKeyToString(item.Key));

        // Define label
        TagBuilder label = new TagBuilder("label");
        label.MergeAttribute("for", String.Concat(name, index));
        label.SetInnerText(funcValueToString(item.Value));

        // Add item
        inputdiv.InnerHtml = String.Format("{0}{1}", input.ToString(TagRenderMode.SelfClosing), label.ToString(TagRenderMode.Normal));
        listItemsBuilder.Append(inputdiv.ToString(TagRenderMode.Normal));
        index++;
    }

    // Return list
    listDiv.InnerHtml = listItemsBuilder.ToString();
    return MvcHtmlString.Create(listDiv.ToString());
}

Nel "Controller" come già accennato prima vengono preparati i dati. Nel "Model" devono esistere un dizionario del tipo IDictionary<TKey, TValue> e una IList<TKey>. Il dizionario contiene tutti gli possibili elementi che verranno mostrati come caselle di controllo (="checkboxes"); la lista contiene le chiavi delle caselle di controllo selezionate.

[HttpGet]
[Authorize]
public ActionResult Edit()
{
    DataModel model = new DataModel();
    model.AvailableItems = DAO.GetAvailableItems().ToDictionary(x => x.ID, x => x.Desc);
    model.SelectedItems = DAO.GetSelectedItems().ToList(x => x.ID);
    return View(model);
}

Nella "View" per mostrare le caselle di controllo (="Checkboxes") basta chiamare la funzione ("CheckBoxListFor") e passare ad essa il dizionario e la lista che si trovano nel "Model". Non dimenticatevi di importare il "Namespace"!

<%@ Import Namespace="CuMvcApi.Helpers.HTML" %>

<%: Html.CheckBoxListFor(x=>x.AvailableItems, y=>y.SelectedItems) %>

Spero, che vi sia piaciuto questo articolo e che vi sia utile per il vostro lavoro!

Saturday, February 5, 2011

First part: MVC.net & jqGrid

This is the first part of a series of posts in which I am going to explain my solution for a fully functional data table with sorting, searching, filtering and paging functionalities. For reaching my goal I am using ASP.NET MVC 2.0 with jQuery (http://jquery.com/)and the jqGrid (http://www.trirand.com/blog/)plugin. I was browsing the internet looking for a solution, but I was not able to find a complete working solution. To be more precise I found some solution, but they were always buggy with common errors for example using simple string sorting for all data types. Basically, this examples were using string comparison, which for example is not evaluating  correctly on dates or on integers. A concrete example: Given numbers from 1 to 15 the sorted result would be 1,10,11,12,13,14,15,2,3,4,5,6,7,8,9.

Today I would like only to publish the sample project, to explain how to set up and to show how to use it. In the near future I will also explain more in detail some tricky parts of my solution. Today I would like only to publish the sample project, to explain how to set up and to show how to use it. In the near future I will also explain more in detail some tricky parts of my solution.

The project can be downloaded by the following url:
http://cid-a8f4afb63c503b89.office.live.com/self.aspx/.Public/MvcJqGrid.zip
It is enough to unzip and to start the solution.

Have fun to investigate about my approach!

Tuesday, January 4, 2011

Framework für iPhone, iPod Touch und iPad Webapp

Sollte ein Entwickler eine Webseite oder eine Webapplikation für einen iPhone, iPod Touch und iPad entwickeln, so empfehle ich euch folgendes free open source Framework iWebKit (http://iwebkit.net/).
photoiWebKit besteht aus mehreren Dateien, welche Ihnen ermöglicht auf einfacher weiße eine kompatibel Website oder Webapplikation für iPhone, iPod Touch und iPad zu erstellen. Das Kit ist für jedem  zugänglich und sehr einfach zu verwenden. Außerdem es ist gut dokumentiert und es gibt auch genügend Beispiele. iWebKit ist ein großartiges Werkzeug, weil es sehr einfach zu bedienen, extrem schnell, kompatibel und erweiterbar ist.

Die folgende Seite wurde mit diesem Framework erstellt: http://www.provincia.bz.it/meteo/mobile/

Monday, January 3, 2011

LINQ & Expressions costruzione a runtime

Questo post vi servirà come un piccolo aiuto per capire meglio i miei post futuri che parleranno di jQuery (http://jquery.com/) è jqGrid (http://www.trirand.com/blog/). Qualche volta è necessario costruire una LINQ  query a runtime, che non è una cosa triviale. Per imparare e per avere un piccolo aiuto, io ho utilizzato un istrumento chiamato Expression Tree Visualizer (http://msdn.microsoft.com/en-us/library/bb397975(VS.90).aspx), che permette di vedere la costruzione delle espressioni. Expression Tree Visualizer lo trovate negli esempi di VS2008.

image

Praticamente ho prima scritto la LINQ query che mi interessava. Questa la ho analizzata con Expression Tree Visualizer è ho infine riscritto la stessa LINQ query utilizzando solamente le espressioni (costruzione di un expression tree). Perché tutta questa fatica? Per scrive LINQ a runtime.

Esempio:
Questa LINQ query

cells => cells["Description"].eq(cells["Description"].Create("Daniel"));
è stata trasformata in
ParameterExpression param = Expression.Parameter(typeof(Dictionary<string, GridCell>), "cells");
//cells["Description"]
ConstantExpression pKey = Expression.Constant("Description");
MethodCallExpression dicCall = Expression.Call(param, "get_item", null, pKey);
//cells["Description"]
ConstantExpression pKey1 = Expression.Constant("Description");
MethodCallExpression dicCall1 = Expression.Call(param, "get_item", null, pKey1);
//.Create("Daniel")
ConstantExpression pStrValue = Expression.Constant("Daniel");
MethodCallExpression createCall = Expression.Call(dicCall, "Create", null, pStrValue);
//operation 
MethodCallExpression eqCall = Expression.Call(dicCall1, "eq", null, createCall);

Infine vorrei fare farvi nottare, che per qualcuno di voi potrà essere abbastanza l’utilizzo di queste librerie Dynamic LINQ (http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx).

Wednesday, November 3, 2010

Log4Net: esempio di configurazione

Un piccolo suggerimento per chi di voi utilizza Log4Net (http://logging.apache.org/log4net/index.html) ma utile: Invece di utilizzare log4net.Appender.FileAppender sarebbe consigliato l’utilizzo di log4net.Appender.RollingFileAppender, che vi da decisivamente più funzionalità per esempio potete impostare la grandezza massima del file di log o anche potete specificare che il file venga rinominato con un “date pattern”.

Ecco un esempio di configurazione:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    </configSections>
    <log4net debug="false">
        <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender, log4net">
            <file value="C:\xxx\xxx_Log4Net" />
            <appendToFile value="true" />
            <rollingStyle value="Composite" />
            <datePattern value=".yyyyMM'.log'" />
            <maxSizeRollBackups value="-1" />
            <maximumFileSize value="50MB" />
            <layout type="log4net.Layout.PatternLayout, log4net">
                <conversionPattern value="%d [%t] %-5p %c - %m%n" />
            </layout>
        </appender>
        <root>
            <priority value="ALL" />
            <appender-ref ref="RollingLogFileAppender" />
        </root>
    </log4net>
</configuration>

Qualche note:

Impostando la proprietà RollingStyle uguale a Composite istruisco a Log4Net che il file corrente si chiami xxx_Log4Net e i file successivi vengano denominati con il seguente pattern .yyyyMM'.log' (yy sta per anno e MM sta per mese). Per essere più esatti passato un mese il file corrente xxx_Log4Net verrà rinominato a xxx_Log4Net.yyyy.MM.log. Inoltre se il file supera la grandezza di 50Mb verrà creato un nuovo file con il nome xxx_Log4Net.1.

Saturday, September 18, 2010

Un estensione utile per l’oggetto NameValueCollection

Queste poche righe di codice permettono di trasformare una NameValueCollecition in un oggetto Dictionary<string, string>.

public static class NameValueCollectionExentsions
{
    public static IDictionary<string, string> ToDictionary(this NameValueCollection source)
    {
        return source.AllKeys.ToDictionary<string, string, string>(x => x, x => source[x]);
    }
}

Cosi facendo sarà possibile utilizzare LINQ per fare delle queries.

IDictionary<string, string> queryStr = context.Request.QueryString.ToDictionary();
queryStr.SingleOrDefault(x => x.Key.Equals("Value", StringComparison.InvariantCultureIgnoreCase));