Design patterns: Factory Method

This is a creational pattern, the factory method pattern is a design pattern that allows for the creation of objects without specifying the type of object that is to be created in code. A factory class contains a method that allows determination of the created type at run-time.

The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.

Elements involved:

  • FactoryBase: This is an abstract base class for the concrete factory classes that will actually generate new objects.
  • ConcreteFactory: Inheriting from the FactoryBase class, the concrete factory classes inherit the actual factory method. This is overridden with the object generation code unless already implemented in full in the base class.
  • ProductBase: This abstract class is the base class for the types of object that the factory can create. It is also the return type for the factory method.
  • ConcreteProduct: Multiple subclasses of the Product class are defined, each containing specific functionality. Objects of these classes are generated by the factory method.

We should use the Factory Method design pattern when:

  • when a class can’t anticipate the type of the objects it is supposed to create.
  • when a class wants its subclasses to be the ones to specific the type of a newly created object.

Let´s see some code:

public abstract class FactoryBase {
    public abstract ProductBase build(int type);
}
public abstract class ProductBase {
    public abstract void whoIAm();
}
public class ConcreteFactory extends FactoryBase {

    @Override
    public ProductBase build(int type) {
        final ProductBase productBase;

        switch (type) {
            case 1:
                productBase = new ConcreteProduct1();
                break;

            case 2:
                productBase = new ConcreteProduct2();
                break;

            default:
                throw new IllegalArgumentException(String.format("Illegal type %s", type));
        }

        return productBase;
    }
}
public class ConcreteProduct1 extends ProductBase {

    @Override
    public void whoIAm() {
        System.out.println("I am ConcreteProduct1");
    }
}
public class ConcreteProduct2 extends ProductBase {

    @Override
    public void whoIAm() {
        System.out.println("I am ConcreteProduct2");
    }
}
public class Main {
    public static void main(String[] args) {
        final FactoryBase factoryBase = new ConcreteFactory();

        factoryBase.build(1).whoIAm();
        factoryBase.build(2).whoIAm();
    }
}

The output after the execution should be something like that:

I am ConcreteProduct1
I am ConcreteProduct2

You can find the code in my GitHub repository “design-apperns“.

Design patterns: Factory Method

OWASP Top 10

The OWASP project is an open source project related with the cyber security field. The project contains information about web application security, mobile security and, lately, IoT security. In addition, multiple back-end security information too, due to all the previous technologies use usually these systems to receive and process their information. If you do not know and you like cyber security, you should definitely take a look.

They have multiple projects like tools, methodologies, metrics, documentation but, one of the most known projects is the OWASP Top 10. The project is a document with the ten most critical web application security risks.

They have multiple versions of the document but, the last one was from 2013 (you can find it here). Obviously, this is a quite old version, not a lot of things has changed since them because, unfortunately, some of the vulnerabilities are still out there but, still, and old version. But, there are some good news, they released on the 10 of April the 2017 version. Right now, it is just a release candidate, the final version is scheduled for July or August this year. We can find this release version here.

These ten security risk are sorted by relevancy. Let’s take a look to them very quickly. We will go deeper in future articles.

A1 – Injection

The injection attacks, where we can find SQL injection, LDAP injection, XPath injection, command injection and some other, is still the most important. It has been in the first place since I remember and everyday we can see examples in the news about them.

A2 – Broken Authentication and Session Management

In second place, we can find the errors produced due to the wrong authentication management or wrong session management. Sessions that never expire, especially the ones used in GET requests that can be indexed in browser or proxies. Areas of the application where the session is not properly checked. We can find attacks like session fixation or session hijacking.

A3 – Cross-Site Scripting (XSS)

In third place, we can find the XSS attacks. Probably, together with the injection attacks the most well known attacks. We can see them everywhere, fun images inserted in government pages or hight traffic pages using scripting languages the browsers understand.

A4 – Broken Access Control

The fourth one, it is the broken access control risk, there are areas of our application that are not properly protected and non authenticated users can access them and do things they should not.

A5 – Security Misconfiguration

In the fifth place, we can find misconfiguration. It can be configuration errors in our servers, or even just error messages giving away more information about our systems than they should.

A6 – Sensitive Data Exposure

The sixth place is unfortunately one that should not exist but we can find too often. It is when sensitive data is exposed, like personal data, medical records or any other private and sensitive information the systems store and it is not properly protected. This information should be encrypted properly or it should be protected using second factor authentication systems or some other options to avoid leaks and, in case the bad guys access the information, make impossible to read it.

A7 – Insufficient Attack Protection

In the seventh place, we can find a new one. Insufficient attack protection, basically means that there are not enough measures, countermeasures o tools to prevent security incidents in place. Prevention: WAF, Anti-DDoS system, not periodic pentest, … Detection: logs, SIEM, IDS, IPS, … Response: backups, encrypted DB, …

A8 – Cross-Site Request Forgery (CSRF)

The eighth is old and well known where the victim sends its session cookie and/or any other automatically included authentication information, to a vulnerable web application through a malicious link.

A9 – Using Components with Known Vulnerabilities

The ninth is a basic one, all the applications have bugs and they need to receive updates and these updates need to be installed, if we or our security teams do not do this, we are going to be vulnerable.

A10 – Under-protected APIs

The last one is a new one, it has been there for a few years but I guess that it has been during the last years when the explosion about exposing APIs has arrived and, multiple back-end systems have hundreds if not thousands of APIs exposed to the world to be consumed and not all of them properly protected.

As we can see, the list does not change too much between version and we are having the same problems, risk and vulnerabilities we were having four years ago.

OWASP Top 10

Design Patterns: Builder

This is a creational pattern, as it is used to control class instantiation. The builder pattern is a design pattern that allows for the step-by-step creation of complex objects using the correct sequence of actions. The construction is controlled by a director object that only needs to know the type of object it is to create.

Elements involved:

  • Product: The product class defines the type of the complex object that is to be generated by the builder pattern.
  • Builder: This abstract base class defines all of the steps that must be taken in order to correctly create a product. Each step is generally abstract as the actual functionality of the builder is carried out in the concrete subclasses. The getProduct method is used to return the final product. The builder class is often replaced with a simple interface.
  • ConcreteBuilder: There may be any number of concrete builder classes inheriting from Builder. These classes contain the functionality to create a particular complex product.
  • Director: The director class controls the algorithm that generates the final product object. A director object is instantiated and its construct method is called. The method includes a parameter to capture the specific concrete builder object that is to be used to generate the product. The director then calls methods of the concrete builder in the correct order to generate the product object. On completion of the process, the getProduct method of the builder object can be used to return the product.

We should use the Builder design pattern when:

When object creation algorithms should be decoupled from the system, and multiple representations of creation algorithms are required. This decoupling is useful as you can add new creation functionality to your system without affecting the core code. You also get control over the creation process at runtime with this approach.

Let´s see some code:

public abstract class Builder {
    public abstract void buildA();
    public abstract void buildB();
    public abstract void buildC();
    public abstract Product getProduct();
}
public class ConcreteBuilder extends Builder {

    private final Product product = new Product();

    @Override
    public void buildA() { this.product.setA("A"); }

    @Override
    public void buildB() { this.product.setB("B"); }

    @Override
    public void buildC() { this.product.setC("C"); }

    @Override
    public Product getProduct() { return this.product; }
}
public class Product {

    public String a;
    public String b;
    public String c;

    public String getA() { return a; }
    public void setA(String a) { this.a = a; }
    public String getB() { return b; }
    public void setB(String b) { this.b = b; }
    public String getC() { return c; }
    public void setC(String c) { this.c = c; }
}
public class Director {

    public Product construct(final Builder builder) {
        builder.buildA();
        builder.buildB();
        builder.buildC();

        return builder.getProduct();
    }
}
public class Main {

    public static void main(String[] args) {
        final Director director = new Director();
        final Product product = director.construct(new ConcreteBuilder());

        System.out.println(String.format("Product: A = %s, B = %s, C = %s",
                product.getA(), product.getB(), product.getC()));
    }
}

You can find the code in my GitHub repository “design-apperns“.

Not exactly matching the pattern described in the book wrote by the GoF, we can see a couple more definitions/implementations of the Builder pattern.

The first one is used to build immutable objects and, in addition, it makes easier to add new properties to your object without having a constructor with a huge number of parameters. It is similar to a fluent interface usually implemented by using method cascading or method chaining.

Let´s see an example.

public class Product {

    private final String a;
    private final String b;
    private final String c;
    private final String d;
    private final String e;

    private Product(ProductBuilder productBuilder) {
        this.a = productBuilder.a;
        this.b = productBuilder.b;
        this.c = productBuilder.c;
        this.d = productBuilder.d;
        this.e = productBuilder.e;
    }

    public String getA() { return a; }

    public String getB() { return b; }

    public String getC() { return c; }

    public String getD() { return d; }

    public String getE() { return e; }

    @Override
    public String toString() {
        return "Product{" + "a=" + a + ", b=" + b + ", c=" + c + ", d=" + d + ", e=" + e + '}';
    }

    public static class ProductBuilder {

        private final String a;
        private final String b;
        private String c; // Optional
        private String d; // Optional
        private String e; // Optional

        public ProductBuilder(String a, String b) {
            this.a = a;
            this.b = b;
        }

        public ProductBuilder setC(final String c) {
            this.c = c;
            return this;
        }

        public ProductBuilder setD(final String d) {
            this.d = d;
            return this;
        }

        public ProductBuilder setE(final String e) {
            this.e = e;
            return this;
        }

        public Product build() {
            return new Product(this);
        }
    }
}
public class Main {

    public static void main(String[] args) {
        System.out.print(new Product.ProductBuilder("A", "B")
                .setC("C")
                .setD("D")
                .setE("E")
                .build()
                .toString());
    }
}

You can find the example in the repository, in the builder project in the package labeled as “variant1”.

The second example, it is basically the same, but applied to POJOs to make easier to build them. It is a much more simplified version of the previous example.

Let´s see how this is:

public class Product {

    private String a;
    private String b;

    public String getA() { return this.a; }

    public Product setA(final String a) {
        this.a = a;
        return this;
    }

    public String getB() { return this.b; }

    public Product setB(final String b) {
        this.b = b;
        return this;
    }

    @Override
    public String toString() {
        return "Product{" + "a=" + a + ", b=" + b + '}';
    }
}
public class Main {

    public static void main(String[] args) {
        System.out.println(new Product()
                .setA("A")
                .setB("B")
                .toString());
    }
}

You can find the example in the repository, in the builder project in the package labeled as “variant2”.

Design Patterns: Builder

THC Hydra: Auditing passwords

As we have said previously, the Cyber Security world is full of useful tools to perform different task. At the end of the day, pentesters are usually very proficient with some of them, the ones they use in daily day basis but, at least, they know or they have tried some of the others. Even similar tools or tools that apparently do the same task, sometimes have slightly different behaviors that can be the difference between success or fail in a pentest.

The tool we are going to see today is called THC Hydra. THC Hydra is a tool that will help us to test the strength of our passwords auditing remote authentication services.

As an example, I am going to use the same set up I used in the Ncrack article before. If you do not know what I am talking about, you can follow this link to my previous article.

After we have our service running in our virtual machine, and we have checked the machine and the service are available, we can execute the “hydra” command.

Just a few notes before test our service.

You can execute the command to obtain information about how to execute the tool:

hydra

You will see that multiple flags are listed, and the most interesting part is the list of services that are supported by the tool. As an important note, I must say that the number of services supported by the tool depends on the kind of compilation and installation we have done. There are a few libraries or dependencies we need to install before THC Hydra to have support for all types of services.

To follow this example, it is enough if you have install the tool with the “libssh” support.

Now, let’s continue. As you have seen in the help description for the tool, there are multiple flags we can use, but for this test, we are going to focus in the next flags:

  • -l LOGIN or -L FILE: It allows us to give to the tool a user or a list of users.
  • -p PASS or -P FILE: It allows us to give to the tool a password or a list of passwords.
  • service: The service we want to test. In our case “ssh”

Now, following the appropriate syntax, we can execute the next command:

hydra -l fjavierm -P password.txt ssh://192.168.0.38

This is going to show us the result:

Hydra v8.4 (c) 2017 by van Hauser/THC - Please do not use in military or secret service organizations, or for illegal purposes.

Hydra (http://www.thc.org/thc-hydra) starting at 2017-04-02 08:26:38
[WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4
[DATA] max 3 tasks per 1 server, overall 3 tasks, 3 login tries (l:1/p:3), ~1 try per task
[DATA] attacking service ssh on port 22
[22][ssh] host: 192.168.0.38 login: fjavierm password: pa$$w0rd
1 of 1 target successfully completed, 1 valid password found
Hydra (http://www.thc.org/thc-hydra) finished at 2017-04-02 08:26:41

As we can see, we have been able to find the weak password.

THC Hydra: Auditing passwords

Machine learning branches

In machine learning we can find three main different branches where we can classify the algorithms:

  • Supervised learning.
  • Unsupervised learning.
  • Reinforcement learning.

Supervised learning

In supervised algorithms you know the input and the output that you need from your model. You do not know how the output is achieved from the input data or how are the inner relations among you data, but definitely know the output data.

As an example, we can take a magazine publication that it has the subscription data of a determinate number of customers or old customers, let’s say 100.000 customers. The company in charge of the magazine knows that half of these customers (50.000) have cancelled their subscriptions and the other half (50.000) are still subscribed, and they want a model to predict what customers will cancel their subscriptions.

We know the input: customers subscription data, and the output: cancelled or not.

We can then build our training data set with 90.000 customers data. Half of them cancelled and half of them still active. We will train our system with this training set. And after that we will try to predict the result for the other 10.000 we left outside the training data to check the accuracy of our model.

Unsupervised learning

In unsupervised learning algorithms you do not know what is the output of your model, you maybe know there is some kind of relation or correlation in your data but, maybe, the data is too complex to guess.

In this kind of algorithms, you normalize your data in ways that it can be compared and you wait for the model to find some of these relationships. One of the special characteristics of these models is that, while the model can suggest different ways to categorize or order your data, it is up to you to make further research on these to unveil something useful.

For example, we can have a company selling a huge number of products and they want to improve their system to target customers with useful advertisement campaigns. We can give to our algorithm the customers data and the algorithms can suggest some relations: age range, location, …

Reinforcement learning

In reinforcement learning algorithms, they do not receive immediately the reward for their actions, and they need to accumulate some consecutive decision to know if the actions/decisions are or not correct. In this scenario, there is no supervisor, the feedback about the decision is delayed and agent’s actions affect the subsequent data it receives.

One example of this, it can be the chess game, where the algorithm is going to be taking decisions but, till the end of the game, it is not going to be able to know if these decisions were correct or not and, obviously, previous decisions affect subsequent decisions.

Machine learning branches

Git Bash: Shell prompt customization

What is it?

Git Bash for Windows is not just bash compiled for Windows. It is a package that contains bash, which is a command-line shell, and a collection of other, separate *nix utilities which you can run using the shell, compiled for Windows, and a new command-line interface terminal window called mintty.

You can download it from here.

Shell prompt customization

If we want to customize the shell prompt according to our preferences, we just need to edit the file “git-prompt.sh”. In a Windows x64 system, we can find it in:

C:\Program Files\Git\etc\profile.d\git-prompt.sh

Now we just need to play a little bit with the different options available.

As an example, the version I am using right now looks like that:

TITLEPREFIX='Bash Prompt (Git for Windows) =>'

PS1='\[\033]0;$TITLEPREFIX:${PWD//[^[:ascii:]]/?}\007\]' # set window title
PS1="$PS1"'\[\033[32m\]'       # change to green
PS1="$PS1"'\w'                 # current working directory
if test -z "$WINELOADERNOEXEC"
then
    GIT_EXEC_PATH="$(git --exec-path 2>/dev/null)"
    COMPLETION_PATH="${GIT_EXEC_PATH%/libexec/git-core}"
    COMPLETION_PATH="${COMPLETION_PATH%/lib/git-core}"
    COMPLETION_PATH="$COMPLETION_PATH/share/git/completion"
    if test -f "$COMPLETION_PATH/git-prompt.sh"
    then
        . "$COMPLETION_PATH/git-completion.bash"
        . "$COMPLETION_PATH/git-prompt.sh"
        PS1="$PS1"'\[\033[36m\]'  # change color to cyan
        PS1="$PS1"'`__git_ps1`'   # bash function
    fi
fi
PS1="$PS1"'\[\033[0m\]'        # change color
PS1="$PS1"'$ '                 # prompt: always $
MSYS2_PS1="$PS1"               # for detection by MSYS2 SDK's bash.basrc
Git Bash: Shell prompt customization

Design patterns: Abstract Factory

This is a creational pattern, as it is used to control class instantiation. The abstract factory pattern is used to provide a client with a set of related or dependant objects. The set of objects created by the factory is determined at run-time according to the selection of concrete factory class.

Provides a level of indirection that abstracts the creation of families of related or dependent objects without directly specifying their concrete classes. The factory object has the responsibility for providing creation services for the entire platform family. Clients never create platform objects directly, they ask the factory to do that for them.

This mechanism makes exchanging product families easy because the specific class of the factory object appears only once in the application – where it is instantiated. The application can wholesale replace the entire family of products simply by instantiating a different concrete instance of the abstract factory.

Elements involved:

  • AbstractFactory: This is an abstract base class for the concrete factory classes that will generate new sets of related objects. A method is included for each type of object that will be instantiated.
  • ConcreteFactory: Inheriting from the AbstractFactory class, the concrete factory classes override the methods that generate the suite of objects required by the client.
  • AbstractProduct: This abstract class is the base class for the types of object that a factory can create. One base type exists for each of the distinct types of product required by the client.
  • ConcreteProduct: Multiple subclasses of the ConcreteProduct classes are defined, each containing specific functionality. Objects of these classes are generated by the abstract factory to populate the client.
  • Client: This class uses the factories to generate a family of related objects. In the UML diagram, the client has two private fields that hold instances of the abstract product classes.

We should use the Abstract Factory design pattern when:

  • the system needs to be independent from the way the products it works with are created.
  • the system is or should be configured to work with multiple families of products.
  • a family of products is designed to work only all together.
  • the creation of a library of products is needed, for which is relevant only the interface, not the implementation, too.

Let´s see some code:

public abstract class AbstractFactory {
    public abstract AbstractProduct createProduct();
}
public abstract class AbstractProduct {
    public abstract void operation1();
    public abstract void operation2();
}
public class ConcreteFactory1 extends AbstractFactory {
    @Override
    public AbstractProduct createProduct() {
        return new ConcreteProduct1();
    }
}
public class ConcreteFactory2 extends AbstractFactory {
    @Override
    public AbstractProduct createProduct() {
        return new Product2();
    }
}
public class ConcreteProduct1 extends AbstractProduct {
    public ConcreteProduct1() {
        System.out.println("Creating product 1...");
    }

    @Override
    public void operation1() {
        System.out.println("Executing ConcreteProduct1::operation1...");
    }

    @Override
    public void operation2() {
        System.out.println("Executing ConcreteProduct1::operation2...");
    }
}
public class ConcreteProduct2 extends AbstractProduct {
    public ConcreteProduct2() {
        System.out.println("Creating product 2...");
    }

    @Override
    public void operation1() {
        System.out.println("Executing Product2::operation1...");
    }

    @Override
    public void operation2() {
        System.out.println("Executing Product2::operation2...");
    }
}
public enum ProductType {
    PRODUCT_1,
    PRODUCT_2
}
public class FactoryMaker {

    public static AbstractFactory getFactory(final ProductType productType) {
        final AbstractFactory abstractFactory;

        switch (productType) {
            case PRODUCT_1:
                abstractFactory = new ConcreteFactory1();
                break;

            case PRODUCT_2:
                abstractFactory = new ConcreteFactory2();
                break;

            default:
                throw new IllegalArgumentException("The product type does not exist.");
        }

        return abstractFactory;
    }
}
public class Client {

    public static void main(String[] args) {
        Arrays.stream(ProductType.values())
            .forEach(productType -> {
                AbstractFactory abstractFactory = FactoryMaker.getFactory(productType);
                AbstractProduct product = abstractFactory.createProduct();

                product.operation1();
                product.operation2();
            });
    }
}

The output after the execution should be something like that:

Creating product 1...
Executing ConcreteProduct1::operation1...
Executing ConcreteProduct1::operation2...
Creating product 2...
Executing Product2::operation1...
Executing Product2::operation2...

You can find the code in my GitHub repository “design-apperns“.

Design patterns: Abstract Factory