martedì 30 ottobre 2012

After Epic Hack, Apple Suspends Over-the-Phone AppleID Password Resets


  • BY NATHAN OLIVAREZ-GILES AND MAT HONAN
  • 8:12 PM
  • Apple is considering changes to its AppleID password reset policies. But what those changes would be, if there are any, aren’t yet clear. Photo: Ariel Zambelich/Wired
    Apple on Tuesday ordered its support staff to immediately stop processing AppleID password changes requested over the phone, following the identity hacking of Wired reporter Mat Honan over the weekend, according to Apple employees.
    An Apple worker with knowledge of the situation, speaking on condition of anonymity, told Wired that the over-the-phone password freeze would last at least 24 hours. The employee speculated that the freeze was put in place to give Apple more time to determine what security policies needed to be changed, if any.
    The change follows similar security tightening at Amazon, which on Tuesday closed a hole in its customer service systems that gave people the ability to gain control of a customer’s Amazon account as long as the hacker knew the name, e-mail address and mailing address of the victim.
    Our Apple source’s information was corroborated by an Apple customer service representative, who told us Apple was halting all AppleID password resets by phone. The AppleCare representative shared that detail while Wired was attempting to replicate Honan’s hackers’ exploitation of Apple’s system for the second day. The attempt failed, and the representative said that the company was going through system-wide “maintenance updates” that prevented anyone from resetting any passwords over the phone. The rep said we should try calling back after about 24 hours, and directed us toiforgot.apple.com to change AppleID passwords ourselves on the web instead.
    “Right now, our system does not allow us to reset passwords,” the Apple rep told Wired. “I don’t know why.”
    In an earlier attempt on Tuesday to change an AppleID password (which is the same password used to log into iCloud and iTunes), Apple customer service offered up a different response, saying that passwords could only be changed over the phone if we were able to supply a serial number for a device linked to the AppleID in question — for example, an iPhone, iPad or MacBook computer. The rep also suggested changing our AppleID password online at appleid.apple.com or iforgot.apple.com.
    While it’s clear that Apple is reacting to the privacy vulnerability that surfaced with the hacking of Honan’s digital identity, it’s unclear what final policy change will emerge. Apple officials declined to comment on whether permanent changes to the company’s security measures were planned.
    On Monday, we were able to call Apple, reset AppleID passwords over the phone, and gain access to iCloud accounts by supplying AppleCare representatives with a name, e-mail address, mailing address and the last four digits of a credit card number linked to an AppleID. This is the exact same information hackers supplied Apple with on Friday to get a temporary password that gave them access to Honan’s iCloud account.
    From there, the hackers wiped Honan’s iPhone, iPad and MacBook. They also used their access to get into Honan’s .Me email account, which gave them access to his Google account (they wiped that too), his personal Twitter account and Gizmodo’s Twitter account. Honan previously worked as a reporter at Gizmodo and, under the hackers’ control, both Twitter accounts became a platform to spout racist and homophobic invective.
    Names with matching e-mail addresses and mailing addresses are easy enough to find on the web. Credit card numbers tied to a name can be found on many purchase receipts, and everyday millions of Americans give these valuable numbers out over the phone ordering pizzas, among other things.
    Yesterday, Apple issued a statement noting that “we found that our own internal policies were not followed completely.” However, Wired’s internal source at Apple said that if the support representative who took the hacker’s call issued a temporary password based on an Apple ID, billing address, and the last four digits of a credit card, he or she would have “absolutely” been in compliance with Apple policy.
    Wired reporter Alexandra Chang contributed to this report.

    Gli hacker mi hanno rubato la vita


    Il reporter e blogger americano Mat Honan, firma di Wired, ha perso tutte le mail, le foto e i documenti: i pirati informatici volevano violare il suo account Twitter, particolarmente pregiato. Né forza né fortuna per recuperare le password: hanno semplicemente chiamato il servizio clienti di Amazon e Apple

    di PAOLA ROSA ADRAGNA UNA VITA (digitale) completamente cancellata. Spazzata via. Irrecuperabile. Il primo compleanno della figlia, i cari scomparsi da poco e quegli attimi con gli amici del college che con il tempo ha perso di vista. Momenti della vita di Mat Honan, firma di Wired, cancellati dalle memorie fisiche di computer e telefono da una coppia di hacker ventenni che volevano divertirsi con il suo account Twitter.

    Un pizzico di astuzia e i numeri di telefono del servizio clienti Amazon e Apple. Questo è servito ai due ragazzi per impadronirsi della vita digitale di Mat e distruggerla. Nel giro di un'ora, come racconta lo stesso Honan sul suo blog 1, i due sono entrati nel suo account Google e lo hanno rimosso. Hanno poi usato il suo profilo Twitter, postando commenti omofobi e razzisti ("Ed è così che gran parte dei miei amici sono venuti a sapere quel che stava accadendo", racconta). Ma più di ogni altra cosa, hanno violato il suo AppleID e hanno cancellato tutto: foto, mail, documenti - un intero archivio digitale in gran parte conservato sul computer portatile. "Senza un backup", si maledice ora Honan. Non c'è più niente sul suo iPhone, né sull'iPad, tantomeno sul MacBook.

    Inizia tutto verso le 17 di venerdì scorso, mentre Mat gioca con la sua bambina. Il telefono si spegne, lui aspetta una telefonata e lo riaccende, inserisce la password di iCloud ma è sbagliata. Va per collegare il telefono al MacBook e scopre che le informazioni del suo account Google sono sbagliate. Serve un codice Pin da quattro cifre, che Mat non ha. L'idea dell'hackeraggio si fa strada nella sua mente e si rivolge al servizio clienti Apple. Una telefonata da 90 minuti che non risolve certo le cose, soprattutto perché per buona parte del tempo l'operatore crede di parlare con un altro cliente. L'equivoco dà a Mat però un'informazione fondamentale: per entrare nell'iCloud di un qualsiasi utente bastano un indirizzo di fatturazione e le ultime 4 cifre di una carta di credito. Due dati facilmente reperibili sul web, come ha scoperto a sue spese. E come gli ha spiegato uno dei due hacker, Phobia, 19 anni, che ha deciso di raccontargli passo dopo passo il percorso seguito, in cambio della promessa di non essere denunciato.

    "Non ho indovinato le tue password, né usato la forza". Inizia così il racconto di Phobia, che piano piano, rivela le falle dei sistemi di sicurezza dei due colossi coinvolti nel caso. Ma partiamo dall'inizio. Phobia risale alla mail Google di Mat tramite il suo sito. Va nella pagina di recovery di Google e fa finta di voler recuperare la password smarrita, e scopre l'indirizzo secondario ".Me", associato all'AppleID. Con questa informazione gli basta solo rintracciare l'indirizzo di Mat e le ultime quattro cifre della sua carta di credito per ottenere le credenziali d'accesso di iCloud direttamente dal servizio clienti AppleCare.

    Il complice di Phobia recupera l'indirizzo postale tramite il dominio di Mat, ma sarebbe stato possibile anche su un semplicissimo elenco telefonico. Non è altrettanto facile con il codice della carta, ma l'assistenza Apple non è l'unica che si può raggirare facilmente. Una telefonata ad Amazon - anzi due - e il gioco è fatto. Grazie alle informazioni che ha già, con la prima chiede di inserire una nuova carta di credito associata al profilo, mentre con la seconda fa finta di aver perso le credenziali di accesso e ottiene la possibilità di verificare tutte le carte di credito registrate sul proprio profilo. O meglio, solo gli ultimi quattro numeri. I quattro necessari per chiamare AppleCare e ottenere l'accesso ai ricordi di Mat e cancellarli per impedirgli di recuperare il possesso del suo pc o del suo telefono. Non per vendetta o per odio, spiega Phobia a un Mat disperato. Ma per poter usare il suo account Twitter perché a loro piace il suo nome utente: @mat. Un account che Honan si aggiudicò proprio in virtù del suo essere un geek, un maniaco della tecnologia, e in quanto tale tra i primissimi utenti del social network.

    La domanda resta perché tutto questo. Mat lo chiede a Phobia, ma la sua risposta non è soddisfacente. Il giovane hacker vuole pubblicizzare i buchi nella sicurezza delle grandi compagnie, così che possano sistemarli. Non è lui che ha materialmente ripulito la sua memoria, bensì il suo complice, ma sembra dispiaciuto. Alla fine, però, Honan ammette di non avercela neanche particolarmente con i due giovani hacker: "Sono un esperto di tecnologia, avrei dovuto saperlo che andava fatto un backup di quello a cui tengo", racconta ora. Così come non gli pare ora una grande idea l'aver utilizzato account di posta "concatenati" e tutti riconducibili all'account Apple, e impostazioni di sicurezza più complesse.

    L'intera storia apre un dibattito sull'affidabilità delle password e dei controlli sulla rete, specialmente con il cloud, ora che tutto è connesso. I codici alfanumerici tutelano abbastanza la sicurezza? Alcune informazioni sensibili vengono reperite con troppa facilità? L'unica cosa certa è che Mat non scorderà mai più di fare un backup, sperando che da qualche parte - nella nuvola - gli vengano restituite le foto della sua bimba.
    (10 agosto 2012)


    Maven, the better quickstart

    http://slopjong.de/2011/03/04/maven-the-better-quickstart/


    Posted on March 4, 2011



    I read a lot of Maven documentation and at the end the most interesting question “How do I run an applicationwith its dependencies?” wasn’t answered. Instead I was flooded with many xml configuration sections without showing a simple and complete configuration file. That’s why I wrote this howto but first a little story.
    I came across Ivy and Maven a couple of days ago, both of which make it very easy to add a list of libraries to your Java project and add them to the classpath.
    Basically both look for a project configuration file including your dependency list and they download the libraries from the internet and install them in the local repository ~/.ivy2 for Ivy and ~/.m2/repository for Maven which are then shared with your Ivy/Maven projects.
    While Ivy is only a dependency manager which is integrated with the most popular build management system for Java projects (Ant), Maven is more than just such a manager. With Maven you have a build system and a dependency manager in one tool.
    I focused on Maven and it took me a while to find out that a feature I was looking for wasn’t there natively. I assumed it would have a similar behaviour than Ivy but it hasn’t and works completely different.
    I was missing a clear Maven howto which shows in 5 minutes how your project is created, compiled, packaged and especially how your standard java application is run afterwards.
    I assume that Maven is already installed and that you are familiar with using a shell as I won’t use m2eclipse, the Maven integration for Eclipse. Maybe I’ll update this post later and give you a little introduction but for now let’s concentrate on using it in a shell.
    I don’t guarantee that everything is 100% correct because I don’t use Maven that long. Post a comment if something is wrong.

    Creating a new project

    First you should know that every single action in Maven is done by a plugin. Maven is shipped with the core plugin (1) by default but I didn’t figure out yet if this downloads the actual jar files the first time the actions are triggered. Maven actions are either goals or phases which groups multiple goals but I’m not going into details here just keep in mind that when you trigger a Maven action it has the following scheme:
    mvn plugin:goal options
    mvn phase
    
    By entering the following line you create your project:
    mvn archetype:generate -DgroupId=de.slopjong.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
    
    Remember the scheme plugin:goalarchetype is the plugin here and generate the goal. What the options mean is listed next.
    1. groupId – this is your package name where your source is located into. In general this is a unique ID of your department or simply use your domain in reverse order.
    2. artifactId – this is the folder name of your project. This name will be used for your package name. In this case my-app would appear in the package name if you created a bundle of your compiled project.
    3. archetypeArtifactId – the archetype is a template of the directory structure. maven-archetype-quickstart is the standard template for simple Maven projects. If you were creating a webapp the archetype would have been maven-archetype-webapp.
    4. interactiveMode – by setting the interactive mode to true you can define a source package named other than your groupId and the version number can be specified by yourself instead of using the standard 1.0-SNAPSHOT
    For the archetype maven-archetype-quickstart the resulting folder structure will be …
    my-app
    |-- pom.xml
    `-- src
        |-- main
        |   `-- java
        |       `-- de
        |           `-- slopjong
        |               `-- app
        |                   `-- App.java
        `-- test
            `-- java
                `-- de
                    `-- slopjong
                        `-- app
                            `-- AppTest.java
    
    … and for maven-archetype-webapp:
    my-app
    |-- pom.xml
    `-- src
        `-- main
            |-- resources
            `-- webapp
                |-- WEB-INF
                |   `-- web.xml
                `-- index.jsp
    
    You can see that the project object model file pom.xmlsrc/main/java and src/test/java were created for the standard java application. Web applications need another structure, that’s why for the template maven-archetype-webapp something slightly different was created. Essentially the directory layout is …
    my-app/
    |-- pom.xml
    |-- src
    |   |-- main
    |   |   |-- assembly
    |   |   |-- config
    |   |   |-- filters
    |   |   |-- java
    |   |   |-- resources
    |   |   `-- webapp
    |   |-- site
    |   `-- test
    |       |-- filters
    |       |-- java
    |       `-- resources
    `-- target
        |-- classes
        |-- maven-archiver
        `-- test-classes
    
    … for every Maven project. Of course not all these trees are also created by every archetype. Only those are created that are really needed. Having the same directory structure in every Maven project allows you to download projects from other developers while you already know its structure. This is called convention over configuration. In Ant you need to explicity configure it.
    When you run the generate goal Maven outputs something like this (I removed all the download messages):
    [INFO] Scanning for projects...
    [INFO]                                                                         
    [INFO] ------------------------------------------------------------------------
    [INFO] Building Maven Stub Project (No POM) 1
    [INFO] ------------------------------------------------------------------------
    [INFO] 
    [INFO] >>> maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom >>>
    [INFO] 
    [INFO] <<< maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom <<<
    [INFO] 
    [INFO] --- maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom ---
    [INFO] Generating project in Batch mode
    [INFO] ----------------------------------------------------------------------------
    [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
    [INFO] ----------------------------------------------------------------------------
    [INFO] Parameter: groupId, Value: de.slopjong.app
    [INFO] Parameter: packageName, Value: de.slopjong.app
    [INFO] Parameter: basedir, Value: /home/slopjong
    [INFO] Parameter: package, Value: de.slopjong.app
    [INFO] Parameter: version, Value: 1.0-SNAPSHOT
    [INFO] Parameter: artifactId, Value: my-app
    [INFO] ********************* End of debug info from resources from generated POM ***********************
    [INFO] project created from Old (1.x) Archetype in dir: /home/slopjong/my-app
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 2.958s
    [INFO] Finished at: Wed Mar 02 18:01:44 CET 2011
    [INFO] Final Memory: 7M/77M
    [INFO] ------------------------------------------------------------------------
    

    Compiling

    The previous step created a hello world code example …
    package de.slopjong.app;
    
    public class App 
    {
        public static void main( String[] args )
        {
            System.out.println( "Hello World!" );
        }
    }
    
    … which is compiled by executing the compile phase
    mvn compile
    
    Now Maven compiled your source to target/classes in your project folder. To run the main method change intotarget and execute
    java -cp classes de.slopjong.app.App
    
    Because the package with your class file is located in classes and not in the current directory you have to add it to the classpath by setting the cp option

    Adding dependencies

    Now the project object model must be edited. Open pom.xml which contains information about the project and configuration details used to build the project. Some of those information were given to Maven at the beginning when you created the project. It also created a jUnit dependency by default.
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>de.slopjong.app</groupId>
      <artifactId>my-app</artifactId>
      <packaging>jar</packaging>
      <version>1.0-SNAPSHOT</version>
      <name>my-app</name>
      <url>http://maven.apache.org</url>
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </project>
    
    If we’d like to use log4j – a framework of the Apache Logging Services – we have to add it as a dependency which Maven will try to resolve next time the project is built. To find out the groupID, the artifactId and theversion of your dependencies I recommend to use a Maven browser like mvnrepository.com.
    ...
      <dependencies>
        ...
        <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.16</version>
        </dependency>
      </dependencies>
    ...
    
    Change the java source …
    package de.slopjong.app;
    
    import org.apache.log4j.Logger;
    
    public class App 
    {
        static Logger logger = Logger.getLogger(App.class);
    
        public static void main( String[] args )
        {
            logger.info( "Hello World!" );
        }
    }
    
    … and compile again. If you try now to run the main method again at this stage, you’ll get an exception.
    Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/log4j/Logger
    
    This is because the logger library is not on your classpath. We could add the library from our local repository to the classpath but while this works for a very little amount of dependencies it shouldn’t be done like this. The reason is that the libraries are not flat organized in the repository. Each library itself is contained in a directory like groupId/artifactId/1.2.13/ so you would have to specify the full path to every single library. The disadvantage in adding directly libraries from the repository is that you can’t share your application with somebody else. You can’t just send the class file to a friend and hope he has a Maven environment or the required libraries installed. So now we are at the famous question.

    How do I run an application with its dependencies?

    When I started looking for an answer I had not yet understood the nitty-gritty of how the plugins integrate with Maven. The quickstarts Maven in 5 minutes and Maven Getting Started Guide don’t talk about this. Instead they have the section How do I build more than one project at once? but is this so important when you’re trying to compile a standard java application, seriously?
    The keyword here is again plugin. What you are looking for is done by the assembly plugin which packs all your dependencies into a jar file by executing …
    mvn assembly:single
    
    … but please continue reading before execution.
    Some older documentation refer to assembly goals other than single but these have been deprecated so don’t use them anymore. Before the product is assembled the first time the plugin must be configured first. Copy the build section so that your pom.xml looks like mine.
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>de.slopjong.app</groupId>
      <artifactId>my-app</artifactId>
      <packaging>jar</packaging>
      <version>1.0-SNAPSHOT</version>
      <name>my-app</name>
      <url>http://maven.apache.org</url>
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.16</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.2.1</version>
            <configuration>
              <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
              </descriptorRefs>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
    
    Now be sure that you are in the project root directory and assemble. The jar file is located in the target folder afterwards and it only contains the dependencies. Check the plugin site if you wish another plugin configuration .
    Change again into target and execute this:
    java -cp classes:my-app-1.0-SNAPSHOT-jar-with-dependencies.jar de.slopjong.app.App
    
    The only difference to the previous run is only the newly created jar file on your classpath. And don’t wonder about the warnings …
    log4j:WARN No appenders could be found for logger (de.slopjong.app.App).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
    
    … you’ve got. There’s no appender configured but log4j actually is working.
    You could also package your class files into a jar which makes it easier to distribute your application. This is done with the package phase.
    mvn package
    
    Also this jar file appears in the target folder which must be added to the classpath in place of classes.
    java -cp my-app-1.0-SNAPSHOT.jar:my-app-1.0-SNAPSHOT-jar-with-dependencies.jar de.slopjong.app.App
    
    You’ve reached the end of this howto but have a look at the ebooks Sonatype wrote.

    Books

    Sonatype.com offers Maven ebooks and if you want to avoid filling out a form with your name and email you can append the following lines one after the other to the domain:
    • /books/nexus-book/pdf/nxbook-pdf.pdf
    • /books/m2eclipse-book/pdf/m2ebook-pdf.pdf
    • /books/mvnex-book/pdf/mvnex-pdf.pdf
    • /books/mvnref-book/pdf/mvnref-pdf.pdf

    Creare un progetto per Eclipse con Maven

    Mi è capitato di scaricare un progetto opensource da source forge completo del suo file pom.xml, di compilarlo con Maven, ma di avere problemi a caricarlo su Eclipse.
    Creando un nuovo progetto Java e importandoci dentro i sorgenti, non era ovviamente sufficiente a creare un progetto Eclipse adeguato, con i classpath e packages corretti.

    Dopo un paio di ricerche con Google, ho proseguito così:

    • Da prompt dei comandi mi sono posizionato nella cartella a livello più alto del progetto, quella al cui interno si trova il folder src e le altre.
    • Da lì digito:    mvn clean eclipse:eclipse    che ha come effetto quello di creare un progetto per eclipse
    • A questo punto posso semplicemente andare in Eclipse e dal menù file seguo il wizard per importare un progetto già esistente.
    • Attenzione con questo sistema non viene creata la cartella "Lib" con dentro i realtivi jar. Quasta va copiata a mano, altrimenti non si può usare il designer.
    Come alternativa a questa procedura è quella di usare     m2eclipse   . Si trattta di un plugin per Eclipse che va installato come gli altri plugin di Eclipse dal menù Help-Install new software- Available software site e si specifica: http://download.eclipse.org/m2e-wtp/releases/ (m2e-wtp releases repository)

    QUesto strumento dovrebbe rendere più semplice importare, generare, manutenere progetti Maven con Eclipse.
    In particolare dovrebbe mantenere allineato il classpath di Eclipse con il pom.xml di Maven semplicemente specificando dal menù Maven del progetto, la voce  Enable Dependency Management.
    In realtà io nn ho trovato questa voce, e non l'housata.

    Con m2eclipse dovrebbe essere semplice importare un progetto che fià dispone di un pom.xml, ma nel mio caso, forse per mia ignoranza, non sono riuscito a farlo (seguendo il wizard mi veniva chiesto quali moduli volessi importare ma nnosapevo cosa rispondere) e quindi non l'ho usato.

    Informazioni interessanti si trovano in questo forum:

    e in questa guida:
           

    sabato 27 ottobre 2012

    Update PMD 4.2.6 to 5

    All the rules that make use of net.sourceforge.pmd.ast.SimpleNode  in pmd 4.26 and that have to be exported in pmd 5, must be rewritten taking in ccount that the class is not implemented in pmd 5.

    The equivalent class is: net.sourceforge.pmd.lang.ast.AbstractNode

    See: https://sourceforge.net/p/pmd/discussion/188193/thread/9490a962/

    venerdì 26 ottobre 2012

    Top 10 Secure Coding Practices


    Skip to end of metadata
    Go to start of metadata

    Top 10 Secure Coding Practices

    1.  Validate input. Validate input from all untrusted data sources. Proper input validation can eliminate the vast majority of software vulnerabilities. Be suspicious of most external data sources, including command line arguments, network interfaces, environmental variables, and user controlled files [Seacord 05].
    2.  Heed compiler warnings. Compile code using the highest warning level available for your compiler and eliminate warnings by modifying the code [C MSC00-AC++ MSC00-A]. Use static and dynamic analysis tools to detect and eliminate additional security flaws.
    3.  Architect and design for security policies. Create a software architecture and design your software to implement and enforce security policies. For example, if your system requires different privileges at different times, consider dividing the system into distinct intercommunicating subsystems, each with an appropriate privilege set.
    4.  Keep it simple. Keep the design as simple and small as possible [Saltzer 74, Saltzer 75]. Complex designs increase the likelihood that errors will be made in their implementation, configuration, and use. Additionally, the effort required to achieve an appropriate level of assurance increases dramatically as security mechanisms become more complex.
    5.  Default deny. Base access decisions on permission rather than exclusion. This means that, by default, access is denied and the protection scheme identifies conditions under which access is permitted [Saltzer 74, Saltzer 75].
    6.  Adhere to the principle of least privilege. Every process should execute with the the least set of privileges necessary to complete the job. Any elevated permission should be held for a minimum time. This approach reduces the opportunities an attacker has to execute arbitrary code with elevated privileges [Saltzer 74, Saltzer 75].
    7.  Sanitize data sent to other systems. Sanitize all data passed to complex subsystems [C STR02-A] such as command shells, relational databases, and commercial off-the-shelf (COTS) components. Attackers may be able to invoke unused functionality in these components through the use of SQL, command, or other injection attacks. This is not necessarily an input validation problem because the complex subsystem being invoked does not understand the context in which the call is made. Because the calling process understands the context, it is responsible for sanitizing the data before invoking the subsystem.
    8.  Practice defense in depth. Manage risk with multiple defensive strategies, so that if one layer of defense turns out to be inadequate, another layer of defense can prevent a security flaw from becoming an exploitable vulnerability and/or limit the consequences of a successful exploit. For example, combining secure programming techniques with secure runtime environments should reduce the likelihood that vulnerabilities remaining in the code at deployment time can be exploited in the operational environment [Seacord 05].
    9.  Use effective quality assurance techniques. Good quality assurance techniques can be effective in identifying and eliminating vulnerabilities. Fuzz testing, penetration testing, and source code audits should all be incorporated as part of an effective quality assurance program. Independent security reviews can lead to more secure systems. External reviewers bring an independent perspective; for example, in identifying and correcting invalid assumptions [Seacord 05].
    10. Adopt a secure coding standard. Develop and/or apply a secure coding standard for your target development language and platform.

    Bonus Secure Coding Practices

    1.  Define security requirements. Identify and document security requirements early in the development life cycle and make sure that subsequent development artifacts are evaluated for compliance with those requirements. When security requirements are not defined, the security of the resulting system cannot be effectively evaluated.
    2.  Model threats. Use threat modeling to anticipate the threats to which the software will be subjected. Threat modeling involves identifying key assets, decomposing the application, identifying and categorizing the threats to each asset or component, rating the threats based on a risk ranking, and then developing threat mitigation strategies that are implemented in designs, code, and test cases [Swiderski 04].

    Bonus Photograph

    I found the following photograph on the Web, and I'm still trying to figure out who owns the rights to it. If you know, please comment below.
    I like this photograph because it illustrates how the easiest way to break system security is often to circumvent it rather than defeat it (as is the case with most software vulnerabilities related to insecure coding practices).

    References

    [Saltzer 74] Saltzer, J. H. "Protection and the Control of Information Sharing in Multics." Communications of the ACM 17, 7 (July 1974): 388-402.
    [Saltzer 75] Saltzer, J. H. & Schroeder, M. D. "The Protection of Information in Computer Systems." Proceedings of the IEEE 63, 9 (September 1975), 1278-1308.
    [Seacord 05] Seacord, R. Secure Coding in C and C++. Upper Saddle River, NJ: Addison-Wesley, 2006 (ISBN 0321335724).
    [Swiderski 04] Swiderski, F. & Snyder, W. Threat Modeling. Redmond, WA: Microsoft Press, 2004.

    Ant-Contrib Tasks

    http://ant-contrib.sourceforge.net/SourceForge logo
    Attenzione, facendo il download come indicato dal sito, si scaricano i sorgenti che vanno compilati con MAVEN.

    Contents

    What's this?

    The Ant-Contrib project is a collection of tasks (and at one point maybe types and other tools) for Apache Ant.
    This Software is distributed under the Apache Software License.

    Installation

    First you must install Apache Ant itself, most of the Ant-Contrib tasks require Ant 1.5 or higher to work properly. You can download Ant from Apache.
    Ant-contrib releases are available at the downloads page. Mailing lists, CVS and bug trackers can be accessed from the project page.
    See the cc tasks for installation instructions for cpptasks. To install ant-contrib:
    1. Copy ant-contrib-0.3.jar to the lib directory of your Ant installation. If you want to use one of the tasks in your own project, add the lines
      <taskdef resource="net/sf/antcontrib/antcontrib.properties"/>
      
      to your build file.
    2. Keep ant-contrib-0.3.jar in a separate location. You now have to tell Ant explicitly where to find it (say in /usr/share/java/lib):
      <taskdef resource="net/sf/antcontrib/antcontrib.properties">
        <classpath>
          <pathelement location="/usr/share/java/lib/ant-contrib-0.3.jar"/>
        </classpath>
      </taskdef>

    Regex Online

    Siti web dove poter testare online le regular expressions:
    http://gskinner.com/RegExr/?32jsn
    http://www.rubular.com/
    http://www.regexplanet.com/advanced/java/index.html

    mercoledì 24 ottobre 2012

    Online XPath Validators

    This uses xPath 2.0 but has problem with IE9
    http://www.xpathtester.com/

    This is nice but uses xPath 1.0 and doesn't work on IE9:
    http://chris.photobooks.com/xml/default.htm

    martedì 23 ottobre 2012

    MSBuild Basics

    http://thomasardal.com/msbuild-tutorial/

    .NET 2.0 introduced a new tool called MSBuild. MSBuild is primarily used to build .NET applications, but can be used for other types of applications as well. From Windows Vista, MSBuild is distributed with Windows itself, making it a strong platform for implementing scripted application on non-developer PCs as well.
    Before .NET 2.0, application were built by one or more of these strategies:
    • Using the build menu from inside Visual Studio
    • Using the devenv.exe process from the command line with some extra parameters
    • Using a third-party tool like NAnt (which MSBuild is based on)
    The drawback with the first two strategies was that they were hard to script. The drawback with the third solution was that two build environments had to be held in sync and maintained. .NET 2.0 Visual Studio projects are now implemented in the MSBuild language, but MSBuild has no dependencies on Visual Studio itself. MSBuild can, in theory, be implemented in files with any extension, but a number of formats seem to be the supported standard from Microsoft: csproj, vbproj, vcproj, vjsproj, proj, and .targets. The first four are different types of project files for Visual Studio, while the last two are new extensions, which are either written by hand or with a tool knowing the MSBuild syntax. A few tools exist for this purpose. My personal opinion is that building in xml editor in Visual Studio is quite good for this purpose. A repeating question among MSBuild developers is if you should extend the files generated by visual studio with new stuff, or whether you should write your own containing your home-made MSBuild scripts. My personal opinion is to let Visual Studio generate its own projects (example: csproj files) and create your home-made scripts in a .proj file with the same name as the project. I usually start the .proj file by implementing the three targets: Clean, Build and Rebuild, which basically just calls the similar targets in the .csproj file. This way, you avoid updating an auto-generated file which you don’t have control over.
    An MSBuild file is implemented in XML. The root element of an MSBuild XML file will always be a project containing target elements. It is possible to run multiple targets in an MSBuild file. When the MSBuild script is started from the command line, it takes a build file as parameter as well as the names of the targets, which should be executed.
    A target is implemented as a sequential list of tasks. The tasks are executed in the order in which they are specified beneath the target element. Both targets and tasks can be dependent on each other.
    This is an example of a very simple file to build a .NET project:
    1
    2
    3
    4
    5
    6
    7
    <?xml version="1.0" encoding="utf-8" ?>
    <Target Name="Build">
    <Message Text="Building msbuildintro" />
    <MSBuild Projects="msbuildintro.csproj" Targets="Build" />
    </Target>
    </Project>
    The example defines a project with the MSBuild namespace. Using the namespace helps you develop the build file in Visual Studio using Intellisense. The build file contains a single target named Build. This target contains two tasks: Message and MSBuild. Message outputs a message to the console and is used primarily for debugging purposes. MSBuild runs a configurable number of targets on another build file. Since the .csproj file is also implemented in MSBuild, we are able to call targets in the build file from the example build file. In this case, we call the target Build in the .csproj file. All projects generated by Visual Studio automatically implement the Clean, Build and Rebuild targets. These targets are actually executed when you select the similar commands in the Build menu from within Visual Studio.

    Properties

    To be able to parameterize a build script, MSBuild has implemented properties. A property is a simple key/value type, which can be used from multiple locations in the scripts. Let’s look at an example using properties:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <?xml version="1.0" encoding="utf-8" ?>
    <PropertyGroup>
    <MyReleaseOutput>.\release</MyReleaseOutput>
    </PropertyGroup>
    <Target Name="Build">
    <Message Text="Building msbuildintro" />
    <MSBuild Projects="msbuildintro.csproj" Targets="Build" />
    </Target>
    <Target Name="Release" DependsOnTargets="Build">
    <MakeDir Directories="$(MyReleaseOutput)" />
    <Copy SourceFiles=".\bin\debug\msbuildintro.exe" DestinationFolder="$(MyReleaseOutput)" />
    </Target>
    </Project>
    This example defines a property defined in a property group. Properties can be defined both outside and inside the scope of a target. When a property is defined as in this example, the value of the property is assigned before executing the actual targets. In this example, I define a property called MyReleaseOutput and add the value .\release. I have added two targets as well: Build and Release. The Build target is similar to the one specified in the previous example, while the Release target is new. The Release target introduces a new attribute called DependsOnTargets, which is the way to define dependencies between targets in MSBuild. In this case, we tell MSBuild to run the Build target before running the Release targets. If you run the Build target manually before running the Release target, the Build target is run only once.
    The release target introduces two new tasks as well. MakeDir, which (well you guessed it) creates a new directory and Copy, which copies on or more files from A to B. MakeDir contains a single attribute, defining the path of the new directory.
    In this example that path is the value of the MyReleaseOutput property. Notice the use of the $(propertyname) syntax here. $() is used to reference properties in MSBuild. The copy task in our example points out a single file and the destination folder where this file should be copied to when executing the Release target. The $(MyReleaseOutput) used is again replaced by the value of this property.

    Items

    The example above copied a single file from one directory to another. This can certainly be useful in many situations, but sometimes this is simply not flexible enough. This is where items come in. An item gives the possibility of creating dynamic lists of, for instance, file names. Let’s start by looking at an example:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <?xml version="1.0" encoding="utf-8" ?>
    <PropertyGroup>
    <MyReleaseOutput>.\release</MyReleaseOutput>
    </PropertyGroup>
    <ItemGroup>
    <MyReleaseFiles Include=".\bin\debug\*.*" />
    </ItemGroup>
    <Target Name="Build">
    <Message Text="Building msbuildintro" />
    <MSBuild Projects="msbuildintro.csproj" Targets="Build" />
    </Target>
    <Target Name="Release" DependsOnTargets="Build">
    <MakeDir Directories="$(MyReleaseOutput)" />
    <Copy SourceFiles="@(MyReleaseFiles)" DestinationFolder="$(MyReleaseOutput)" />
    </Target>
    </Project>
    We start by defining an ItemGroup outer scope of a target. This means that the content is calculated before actually running any targets. In this example, I define an ItemGroup containing a single item called MyReleaseFiles. The item contains a single attribute called Include, which acts as a filter for the generated file list. In this case, all files beneath the bin\debug directory. I use this item in the copy task beneath the Release target to indicate which files should be copied when doing a release.
    The Include filter decides which file to include. We also have the possibility to specify an Exclude filter. The following example shows how:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <?xml version="1.0" encoding="utf-8" ?>
    <PropertyGroup>
    <MyReleaseOutput>.\release</MyReleaseOutput>
    </PropertyGroup>
    <ItemGroup>
    <MyReleaseFiles Include=".\bin\debug\*.*" Exclude=".\bin\debug\*vshost.exe" />
    </ItemGroup>
    <Target Name="Build">
    <Message Text="Building msbuildintro" />
    <MSBuild Projects="msbuildintro.csproj" Targets="Build" />
    </Target>
    <Target Name="Release" DependsOnTargets="Build">
    <MakeDir Directories="$(MyReleaseOutput)" />
    <Copy SourceFiles="@(MyReleaseFiles)" DestinationFolder="$(MyReleaseOutput)" />
    </Target>
    </Project>
    I added an Exlude attribute to my MyReleaseFiles item. The exclude in this example excludes all files beneath the bin\debug directory which end in vshost.exe. An item containing both Include and Exclude will be generated by taking all the files specified in the Include and subtracting the files specified in the Exlude.
    The last two examples of using items are actually not that useful because the content for the MyReleaseFiles item is generated before running the actual targets. On a new checkout or after a clean, no files exist in the bin\debug directory meaning that the generated file list will therefore be completely empty. Bummer! Let us fix the example. We define a new item inside the scope of a target instead:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <?xml version="1.0" encoding="utf-8" ?>
    <PropertyGroup>
    <MyReleaseOutput>.\release</MyReleaseOutput>
    </PropertyGroup>
    <Target Name="Build">
    <Message Text="Building msbuildintro" />
    <MSBuild Projects="msbuildintro.csproj" Targets="Build" />
    </Target>
    <Target Name="Release" DependsOnTargets="Build">
    <MakeDir Directories="$(MyReleaseOutput)" />
    <CreateItem Include=".\bin\debug\*.*" Exclude=".\bin\debug\*vshost.exe">
    <Output TaskParameter="Include" ItemName="MyReleaseFiles"/>
    </CreateItem>
    <Copy SourceFiles="@(MyReleaseFiles)" DestinationFolder="$(MyReleaseOutput)" />
    </Target>
    </Project>
    I moved the MyReleaseOutput item inside the Release target. This is done using the CreateItem task. The CreateItem task creates a new item on the fly which means that the content is generated at the point in time when the CreateItem task is executed. Notice that the CreateItem task contains an Output element. The Output element is used in a lot of different places in MSBuild where a target is able to output some data. In this case, it uses the ItemName attribute to define the name from the previous example.
    Anyone still reading? If you have read this far, you deserve a little prize:
    dilbert2002444471010.gif

    Conditions

    Besides the CreateItem task in a previous example, our build scripts have been very static until now. This can be sufficient for a lot of projects, but sometimes you need slightly more flexible build scripts. A feature for fulfilling this in MSBuild is called Conditions. A condition in MSBuild is not that different from a condition in other software languages. It is a possibility, for instance, to make more flexible structures to avoid running targets and/or tasks when certain conditions are met. You can define conditions on all targets and almost all tasks. Let’s check out another example:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <?xml version="1.0" encoding="utf-8" ?>
    <PropertyGroup>
    <MyReleaseOutput>.\release</MyReleaseOutput>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    </PropertyGroup>
    <Target Name="Build">
    <Message Text="Building msbuildintro $(Configuration)" />
    <MSBuild Projects="msbuildintro.csproj" Targets="Build" />
    </Target>
    <Target Name="Release" DependsOnTargets="Build" Condition="$(Configuration) == 'Release'">
    <MakeDir Directories="$(MyReleaseOutput)" />
    <CreateItem Include=".\bin\$(Configuration)\*.*" Exclude=".\bin\$(Configuration)\*vshost.exe">
    <Output TaskParameter="Include" ItemName="MyReleaseFiles" />
    </CreateItem>
    <Copy SourceFiles="@(MyReleaseFiles)" DestinationFolder="$(MyReleaseOutput)" />
    </Target>
    </Project>
    I added a lot of new stuff here. But of course you are already quite an MSBuild expert, so I think you will manage. First of all, I have added a new property named Configuration. This property contains a condition attribute, which determines the value of the property at runtime. If the Configuration property has not been set up front; the value of the attribute is set to Debug. Properties can be set upfront by using a special syntax on the command line:
    Msbuild.exe build.proj /p:Configuration=Debug /t:release
    More new stuff. I changed all references to the debug, with the value of the new Configuration property. This means that I am now able to run the script in both Debug and Release mode.
    The last new addition is the condition attribute on the release target. This condition examines if the value of the Configuration property is Release and only allows execution of the Release target if this condition is true.



    Frequently Used Tasks

    CallTarget – Executes another target inside the current build file. Used where a target needs to call another target at a specific place inside the target itself. If the target were just dependant on the other target being executed, we would use the DependsOnTargets attribute instead.
    Copy – We already saw this task in action. Copies one or more files from A to B.
    CreateItem – Create dynamic items.
    CreateProperty – Create dynamic properties.
    Delete – Deletes on or more files.
    Exec – Executes an external process. This is typically used to executed external tools, which did not implement MSBuild targets themself.
    MakeDir – Creates one or more directories.
    Message – Outputs a message to the console.
    MSBuild – Executes one or more targets in an external MSBuild file.
    RemoveDir – Removes one or more directories.
    And there are a lot more.

    Custom MSBuild Tasks

    It is possible to write your own MSBuild tasks. This can be extremely useful if you want to integrate some of your own tools with MSBuild or if you need to do stuff which is not yet supported by MSBuild. The following example shows how to write a simple addition task:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    using System;
    using Microsoft.Build.Utilities;
    using Microsoft.Build.Framework;
    namespace MyTasks
    {
    public class AddTask : Task
    {
    private int number1;
    [Required]
    public int Number1
    {
    get { return number1; }
    set { number1 = value; }
    }
    private int number2;
    [Required]
    public int Number2
    {
    get { return number2; }
    set { number2 = value; }
    }
    private int sum;
    [Output]
    public int Sum
    {
    get { return sum; }
    set { sum = value; }
    }
    public override bool Execute()
    {
    try
    {
    sum = number1 + number2;
    }
    catch (ArithmeticException e)
    {
    Console.WriteLine("Error occured during addition: {0}", e.Message);
    return false;
    }
    return true;
    }
    }
    }
    I start by defining the AddTask class which extends the Task class from the MSBuild API. By extending this task, I don’t need to worry about implementing conditions etc.
    I defined two properties which act as input variables to the addition task: Number1 and Number2. Both properties are marked with the Required attribute which tells the script to fail if they are not specified. An output property is added as well. The value of this property will be available within the build script. Let’s see how to use this new and fancy task:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <?xml version="1.0" encoding="utf-8" ?>
    <UsingTask TaskName="MyTasks.AddTask" AssemblyFile=".\AddTask.dll"/>
    <Target Name="Addition">
    <AddTask Number1="10" Number2="12">
    <Output TaskParameter="Sum" PropertyName="CalculatedSum" />
    </AddTask>
    <Message Text="10 + 12 = $(CalculatedSum)" />
    </Target>
    </Project>
    TODO: Describe inline tasks (http://msdn.microsoft.com/en-us/library/dd722601.aspx).
    Because my AddTask in an external task not built into the MSBuild framework, I use the UsingTask element to reference it. The name of the task as well as the assembly name is specified.
    The Addition target uses the AddTask with the two Number properties as attributes. The Output element copies the result of the task to a property called CalculatedSum. This property is accessible in the Message task for output on the console.
    You just implemented your first custom MSBuild task. Pretty easy, right?

    Generic Targets

    Once in a while a question pops up in different forums: How do I parameterize a common part of my script, making it possible to use it from different targets? This is a great question. We don’t want to have the same lines of code spread around our build script, making it longer than necessary and complex to maintain. MSBuild provides the CallTarget task, which executes another target inside the current build file. Unfortunately there is no way to parameterize the CallTarget task, making it unusable for anything other than simple situations where needed tasks are 100% identical.
    Let’s look at and example where we have two targets with some identical tasks:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    <?xml version="1.0" encoding="utf-8" ?>
    <Target Name="Target1">
    <Message Text="Hello World from Target1" />
    </Target>
    <Target Name="Target2">
    <Message Text="Hello World from Target2" />
    </Target>
    </Project>
    In the example we define two targets: Target1 and Target2. You will probably notice that the targets look very similar. The only difference is the text inside the Message task. This is a simple example of the problem and of course changing the text in both message tasks would be fairly simple. But you probably understand the problem here: It would be nice to refactor the targets (let’s call it “Extract Target”), so that the Hello World text will only be specified once. First of all we need to move the common tasks to a new target:
    1
    2
    3
    <Target Name="PrintMessage">
    <Message Text="Hello World from X" />
    </Target>
    Note that the replaced part of the Text with the X. Now we need to call this target, making sure that X will be replaced with the correct string. For this purpose we use another task called MSBuild. The MSBuild task was originally produced to be able to call targets inside other MSBuild scripts. The great thing about the MSBuild task is that it has the capability to receive properties. In order to call our PrintMessage target and print the correct string, we parameterize the target like this:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <?xml version="1.0" encoding="utf-8" ?>
    <Target Name="Target1">
    <MSBuild Projects="$(MSBuildProjectFile)" Targets="PrintMessage" Properties="Caller=Target1"/>
    </Target>
    <Target Name="Target2">
    <MSBuild Projects="$(MSBuildProjectFile)" Targets="PrintMessage" Properties="Caller=Target2"/>
    </Target>
    <Target Name="PrintMessage">
    <Message Text="Hello World from $(Caller)" />
    </Target>
    </Project>
    We use the MSBuild tasks in both Target1 and Target2. The $(MSBuildProjectFile) is a built-in property in MSBuild, which returns the filename of the current build file. What we do here is that we call the PrintMessage task on this. The properties attribute specify a single property named Caller. Multiple properties can be specified inside this attribute by separating them with a semicolon. In the PrintMessage task we simply print the message with the Caller property specified inside the Text attribute.

    Property functions

    TODO

    Links

    The MSBuild documentation is actually quite good and a must for all serious MSBuild developers:http://msdn2.microsoft.com/en-us/library/wea2sca5(VS.80).aspx
    A lot of different tools for handling MSBuild files exist. I haven’t been able to find a tool that makes it possible to run build scripts from within Visual Studio. You could start by installing the MSBuildShellExtension tool from: MSBuildShellExtension.
    Besides the build in tasks in MSBuild, there is a great community project, implementing a lot of nice tasks not implemented by Microsoft. Targets for search and replace, zipping, sending out mails, modifying subversion etc., can be found here: http://msbuildtasks.tigris.org/