You are on page 1of 24

Cyber Security Auditing Software

Improve your
Firewall Auditing
As a penetration tester you have to be an expert in multiple
technologies. Typically you are auditing systems installed and
maintained by experienced people, often protective of their own
methods and technologies. On any particular assessment testers may
have to perform an analysis of Windows systems, UNIX systems, web
applications, databases, wireless networking and a variety of network
protocols and firewall devices. Any security issues identified within
those technologies will then have to be explained in a way that both
management and system maintainers can understand.
he network scanning phase of a
penetration assessment will quickly
identify a number of security
weaknesses and services running on the
scanned systems. This enables a tester to
quickly focus on potentially vulnerable
systems and services using a variety of tools
that are designed to probe and examine
them in more detail e.g. web service query
tools. However this is only part of the picture
and a more thorough analysis of most
systems will involve having administrative
access in order to examine in detail how
they have been configured. In the case of
firewalls, switches, routers and other
infrastructure devices this could mean
manually reviewing the configuration files
saved from a wide variety of devices.

Although various tools exist that can


examine some elements of a configuration,
the assessment would typically end up
being a largely manual process. Nipper
Studio is a tool that enables penetration
testers, and non-security professionals, to
quickly perform a detailed analysis of
network infrastructure devices. Nipper
Studio does this by examining the actual
configuration of the device, enabling a much
more comprehensive and precise audit than
a scanner could ever achieve.

www.titania.com
With Nipper Studio penetration testers can be experts in You can customize the audit policy for your customer’s
every device that the software supports, giving them the specific requirements (e.g. password policy), audit the
ability to identify device, version and configuration device to that policy and then create the report detailing
specific issues without having to manually reference the issues identified. The reports can include device
multiple sources of information. With support for around specific mitigation actions and be customized with your
100 firewalls, routers, switches and other infrastructure own companies styling. Each report can then be saved
devices, you can speed up the audit process without in a variety of formats for management of the issues.
compromising the detail. Why not see for yourself, evaluate for
free at titania.com

Ian has been working with leading global


organizations and government agencies to
help improve computer security for more
than a decade.
He has been accredited by CESG for his security and
team leading expertise for over 5 years. In 2009 Ian
Whiting founded Titania with the aim of producing
security auditing software products that can be used by
non-security specialists and provide the detailed
analysis that traditionally only an experienced
penetration tester could achieve. Today Titania’s
products are used in over 40 countries by government
and military agencies, financial institutions,
telecommunications companies, national infrastructure
organizations and auditing companies, to help them
secure critical systems.

www.titania.com
Secure Coding
Make Sure Your Program is Safe

Copyright © 2014 Hakin9 Media Sp. z o.o. SK

Table of Contents

TOOLS

Introduction to W3af scanner


by Ashutosh Agrawal; Bhaumik Shah 08
W3af plugins communicate with each other, for example discovery plugin identifies different application
URLs and passes the result to the audit plugin, which further uses these URLs to find vulnerabilities. W3af
has features like fuzzing and manual request generator and also be configured as man-in-the-middle proxy.

Windows 8 Hacking Using Meterpreter (via Mozilla Firefox)


by Rohit Patel 16
Meterpreter has been developed within Metasploit Framework for making Post Exploitation faster and
easier. The Meterpreter is an advanced multifunction payload that can be used to leverage our capabilities
dynamically at run time when we are standing in the Remote System. In simple terms Meterpreter provides
you with the Interactive Shell which allows you to use extensible features at run time and thus increases your
chances for successful Penetration test.

Local Area Network Attacks with Yersinia


by Mirko Raimondi 22
Security is surely an important theme in LAN environments, where, if the network administrators does not
configure Switches in the right way, several kinds of attacks will be possible. In this article an overview of
the network protocols exploited by these kind of attacks was reported, moreover in order to explain methods
used by hackers to execute that, examples of these attacks were shown and their countermeasures were
reported. The attacks were executed by mean of the Yersinia.

VULNERABILITIES

Vulnerabilities in Industrial Control Systems


by Nikoloz Kokhreidze 32
In this article I have covered differences related to the security of both ICS and conventional IT systems.
Threat sources of ICS and common vulnerabilities have also been identified which draws a general picture of
lack of security policies in this field.

Why Do SQL Injection Vulnerabilities Occur?


by Vijay Kumar 36
I will start with the some PHP basics, a brief introduction to SQL queries and then we will move to database
connection with PHP. Finally, finally I will introduce you what is a bad programming.

4
Secure Coding Make Sure Your Program is Safe

SCENARIOS

Fighting Buffer Overflows With Address Space Layout Randomization


by John-André Bjǿrkhaug 39
As good as every time a programmer finds a new method to protect against a security vulnerability,
a very short time after, the protection mechanism is broken. One of many protection mechanisms against
vulnerabilities in modern operating systems is Address Space Layout Randomization, which was created
to avoid that an adversary to know where in memory a program is working, and were standard libraries
are located.

Integrated Malware Analysis


by Luigi Capuzzello 53
Day by day, we store more and more confidential information on our computers, from sites account
credentials to our bank account. Every day, malware becomes more and more silent, they don’t want you to
be suspicious, they just want to stay into your device to do something …that you don’t really want.

Secure Coding in C# .NET


by Gilad Ofir 64
As all of us programmers go day by day, writing more and more code, improving what’s already written and
developing new and improved code, we devote our time and effort to writing software that will do the work
for us and for our customers. As the industry relays on speed and efficiency, we put great effort in optimizing
performance, creating eye-appealing and stylish GUI, and use state-of-the-art technology to attract as many
buyers for our products.

SECURITY

BackTrack Linux: The Ultimate Hacker’s Arsenal


by Aman Singh 79
If I’d be asked to summarize my writing I would simply say that if you are on net, then you are vulnerable to
attacks. Mostly triggered by a group of people with unethical thinking. But almost all incoming attacks can
be stopped with just little knowledge of cyber world. You need not to be a techie for sure, all what you have
to do is to ensure that you are not leaving any loop holes in your network. No one can hack into or exploit
your system until and unless you let them. If you are well prepared, they can do nothing.

Top Application Security Mistakes / Myths


by Chetan Soni 95
I am sure that most of us have fallen victims to a system hack. And I am not talking about the basic hack like
Facebook status hacks that your team mates or your partners do. I am talking about your private information,
for example your bank login credentials, your email details, and your personal data which is being stolen
from your computer.

5
Secure Coding Make Sure Your Program is Safe

Dear Readers,
We would like to present you a new PenTest Secure Coding issue!

Nowadays, security is one of the most important matters regarding the storage and operations on personal
data and sharing public contents. Not only storage, but also transference of the information might be
prone to attacks and therefore be a subject of undesirable operations. That is why safety matters are of the
utmost priority.

That is also the reason PenTest Magazine is preparing a series of editions dedicated entirely to IT security
and suitable tools. Start with Secure Coding release and secure your data.

First of all, we have prepared a guide to a W3af scanner, a framework to help you protect web applications
detecting their vulnerabilities. You may also entertain yourself trying to hack Windows 8 with Meterpreter
tool or observing hackers executing their attacks using Yersinia penetration testing tool.

You will have a chance to read about vulnerabilities in industrial control systems and SQL. What is more, we
will show you how to fight buffer overflows and we will analyze an integrated malicious software.

One of our articles has been prepared particularly for the occasion by a blogger who was awarded in the last
Hakin9 Magazine’s Best IT Blog Challenge. The two-parts article treats of BackTrack Linux and Sniffers.
The article we recommend in the issue is Secure Coding in C#.NET.

We hope that you will find this edition both interesting and entertaining.

Stay safe and enjoy your time with PenTest Magazine!

Dominika Baczyńska and PenTest Team

6
Editor in Chief: Milena Bobrowska
milena.bobrowska@pentestmag.com

Managing Editor: Dominika Baczyńska


dominika.baczynska@software.com.pl

Editorial Advisory Board: Jeff Weaver, Rebecca Wynn

Betatesters & Proofreaders: Ricardo Puga Madrigal, Al


Alkoraishi, Dr. Hani Ragab, Tom Updegrove, José Luis Herrera

Special Thanks to the Beta testers and Proofreaders who helped


us with this issue. Without their assistance there would not be
a PenTest magazine.

Senior Consultant/Publisher: Pawel Marciniak

CEO: Ewa Dudzic


ewa.dudzic@pentestmag.com

Production Director: Andrzej Kuca


andrzej.kuca@pentestmag.com [ GEEKED AT BIRTH ]
DTP: Ireneusz Pogroszewski
Art Director: Ireneusz Pogroszewski
ireneusz.pogroszewski@pentestmag.com

Publisher: Hakin9 Media Sp. z o.o. SK


02-676 Warsaw, Poland
Postepu 17D
Phone: 1 917 338 3631
www.pentestmag.com

Whilst every effort has been made to ensure the high quality of
the magazine, the editors make no warranty, express or implied,
concerning the results of content usage.
All trade marks presented in the magazine were used only for
You can talk the talk.
informative purposes. Can you walk the walk?

All rights to trade marks presented in the magazine are


reserved by the companies which own them. [ IT’S IN YOUR DNA ]
LEARN:
Advancing Computer Science
DISCLAIMER! Artificial Life Programming
The techniques described in our articles may only be Digital Media
used in private, local networks. The editors hold no Digital Video
Enterprise Software Development
responsibility for misuse of the presented techniques Game Art and Animation
or consequent data loss. Game Design
Game Programming
Human-Computer Interaction
Network Engineering
Network Security
Open Source Technologies
Robotics and Embedded Systems
Serious Game and Simulation
Strategic Technology Development
Technology Forensics
Technology Product Design
Technology Studies
Virtual Modeling and Design
Web and Social Media Technologies

www.uat.edu > 877.UAT.GEEK


Please see www.uat.edu/fastfacts for the latest information about
degree program performance, placement and costs.
Secure Coding Make Sure Your Program is Safe

Secure Coding in C# .NET


by Gilad Ofir
As all of us programmers go day by day, writing more and more code, improving what’s
already written and developing new and improved code, we devote our time and effort to
writing software that will do the work for us and for our customers. As the industry relays on
speed and efficiency, we put great effort in optimizing performance, creating eye-appealing
and stylish GUI (Graphical User Interface), and use state-of-the-art technology to attract as
many buyers for our products.
However, even though the above is important, at times there is a concept that is often disregarded and
overlooked, Secure Code writing.

As the name implies, Secure Coding refers to the idea that software almost always contains flaws in either
the design, or the internal functions that could lead to security breaches and be exploited by hackers and
crackers.

Now, the magnitude of such a thing can be minimal to catastrophic in terms of the damage that is done.

In other words, we can consider severity of damage as the effect that is caused upon exploitation.

Does the damage apply just for the user, or are others being affected by it, or can it bring down an entire
enterprise? Even though it might seem odd that computer software can take down an entire enterprise, we
need to remember that a lot of today’s day to day businesses and activities are done using computers, such as
e-commerce, online banking, cloud services, etc.

It’s important to note that secure programming applies to all programming languages.

Some issues that are addressed by security are confidentiality, integrity, and availability (CIA) (Taken from
Whatis.com)

• Confidentiality prevents sensitive information from reaching the wrong people, while making sure that
the right people can in fact get it. A good example is an account number or routing number when banking
online. Data encryption is a common method of ensuring confidentiality. User IDs and passwords
constitute a standard procedure; two-factor authentication is becoming the norm and biometric verification
is an option as well. In addition, users can take precautions to minimize the number of places where the
information appears, and the number of times it is actually transmitted to complete a required transaction.

• Integrity involves maintaining the consistency, accuracy, and trustworthiness of data over its entire life
cycle. Data must not be changed in transit, and steps must be taken to ensure that data cannot be altered
by unauthorized people (for example, in a breach of confidentiality). In addition, some means must be in
place to detect any changes in data that might occur as a result of non-human-caused events such as an
electromagnetic pulse (EMP) or server crash. If an unexpected change occurs, a backup copy must be
available to restore the affected data to its correct state.

• Availability is best ensured by rigorously maintaining all hardware, performing hardware repairs
immediately when needed, providing a certain measure of redundancy and failover, providing adequate
communications bandwidth and preventing the occurrence of bottlenecks, implementing emergency
backup power systems, keeping current with all necessary system upgrades, and guarding against
malicious actions such as denial-of-service (DoS) attacks.

Microsoft suggests that the following will be taken into consideration in each developed software or system:

• Spoofing – Changing your identity to either trick or perform some kind of malicious activity.

• Information Sabotage – Corrupting, changing or deleting information that could potentially provide
inaccurate results, such as for medical data or banking.

8
Secure Coding Make Sure Your Program is Safe

• Denial – The ability to perform malicious activity without leaving evidence and minimizing the ability to
prove the activity, usually due to incorrect logging.

• Information Disclosure – The ability to expose secret and confidential information to the public or to be
used for blackmail.

• Denial of Service – The ability to disrupt the ongoing service providence, ranging from temporary to
permanent, and from little to severe damage.

• Privilege Escalation – The ability to obtain better and more privileged permissions to be able to cause
more damage, such as obtaining Domain Admin in Active Directory environment.

This article will focus on some of those issues and will try to provide a different and more secure approach,
as the goal is to bring security a few steps forward.

In my opinion, lack of security is caused by two main causes:

• Lack of knowledge – The programmer or designer has inefficient knowledge regarding secure coding or
even security in general.

• Finding security of lesser importance – Could be within the life cycle of the software that security issues
are not brought up and are not handled in the development.

I will try to address both development stage securities (in the SDL model) as well as code itself (with
examples). The Security Development Lifecycle (SDL) is a software development process that helps
developers build more secure software and address security compliance requirements while reducing
development cost (Microsoft).

Microsoft suggest that SDLC should be integrated in every step of software development.

Starting from training the personnel with security in mind, going through the software design,
implementation, QA, release and post-release.

The following will focus on some of the .NET offered services and security.

As a general rule of thumb, we do not fully trust information that is not in our control such as user input and
using an external module or API.
The reason for this is that we cannot assure that the information comes from a reliable source.

Managed and Unmanaged Code Issues


Managed code is a code that has its execution managed by the .NET Framework Common Language
Runtime. The .NET CLR provides services with the following benefits:

• Performance improvements.

• The ability to easily use components developed in other languages.

• Extensible types provided by a class library.

• Language features such as inheritance, interfaces, and overloading for object-oriented programming.

• Support for explicit free threading that allows creation of multithreaded scalable applications.

• Support for structured exception handling.

• Support for custom attributes.

9
Secure Coding Make Sure Your Program is Safe

• Garbage collection.

• Use of delegates instead of function pointers for increased type safety and security.

In contrast, unmanaged code offers the following benefits:

• Maximum speed of execution. The managed layer adds around 10% overhead to tze program.

• Maximum flexibility. Some features of some APIs are unavailable through the managed library. Using
unmanaged APIs from a managed code program is possible but more difficult, and introduces its own
performance issues.

However, working in an unmanaged code can provide security issues:

• Buffer Overflow.

• Arbitrary Code Execution.

• Memory Leak.

• Much more.

For example, Buffer Overflow can be caused by the following:

• Using the unsafe keyword that allows pointers. Unsafe code is just as easy to get wrong, as pointer based
code in C or C++.

• Using unsafe APIs, such as the methods from the Marshal class.

• Maximum speed of execution. The managed layer adds around 10% overhead to the program.

• Maximum flexibility. Some features of some APIs are unavailable through the managed library. Using
unmanaged APIs from a managed code program is possible but more difficult, and introduces its own
performance issues.

Consider the code in Figure 1.

Figure 1. Unsecure unmanaged Buffer Overflow example

The example in Figure 1 shows a buffer overflow that will occur when the iteration reaches its 10th place (if
the string provided is greater the 10 in length) where if were managed, it would do bounds-checking before
accessing an array unless it (CLR) can guarantee it is safe.

Please note that even working with managed code does guarantee that the code is always secure, even though the CLR helps
a programmer to avoid security issues. As a general rule of thumb, we do not fully trust information that is not in
our control such as user input and using an external module or API.

The reason for this is that we cannot assure that the information comes from a reliable source, but the .NET
provides us with ways to prevent unsecure access and possible security breach.

10
Secure Coding Make Sure Your Program is Safe

Code Access Security (CAS)


Another security problem that we face is the lack of ability to fully control the execution of a code.

Normally, we can set inheritance level permissions (Private, Public, etc.), but it’s hard to restrict access to
a function for different cases, mainly when we look at more of a global approach. That is to say, not only
which class can access the code, but which person or entity can run a particular function in a code, or even,
deny other code to run our code if it does not comply with our requirements.

This is .NET comes into action with CAS.

Code Access Security (CAS), in the Microsoft .NET framework, is Microsoft’s solution to prevent untrusted
code from performing privileged actions.

When the CLR loads an assembly, it will obtain evidence for the assembly and use this to identify the code
group that the assembly belongs to.

A code group contains a permission set (one or more permissions). Code that performs a privileged action
will perform a code access demand which will cause the CLR to walk up the call stack and examine the
permission set granted to the assembly of each method in the call stack. The code groups and permission sets
are determined by the administrator of the machine who defines the security policy (Wikipedia). CAS performs
the following:

• Defines permissions and permission sets that represent the right to access various system resources.

• Enables administrators to configure security policy by associating sets of permissions with groups of code
(code groups(.

• Enables code to request the permissions it requires in order to run, as well as the permissions that would be
useful to have, and specifies which permissions the code must never have.

• Grants permissions to each assembly that is loaded, based on the permissions requested by the code and
on the operations permitted by security policy.

• Enables code to demand that its callers have specific permissions.

• Enables code to demand that its callers possess a digital signature, thus allowing only callers from a particular
organization or site to call the protected code.

• Enforces restrictions on code at runtime by comparing the granted permissions of every caller on the call
stack to the permissions that callers must have.

Code Access Security Basics


Applications that run under the CLR come across the CLR security, which grants them appropriate set of
permissions. Due to that, a programmer can sometimes receive Security exceptions if a code violates the
permissions given, but that’s just one of the features offered by the CLR.

The local security settings on a particular computer ultimately decide which permissions the code receives.

This is an important issue that may cause some code to execute on one computer, but generate a security
exception on the other due to insufficient permissions.

In contrast to the unmanaged code, that doesn’t enforce security.

It’s important, when working with CAS, to familiarize with the following:

11
Secure Coding Make Sure Your Program is Safe

• Writing type-safe code: To enable the code to benefit from code access security, we must use a compiler
that generates verifiably type-safe code.

• Imperative and declarative syntax: Interaction with the runtime security system is performed using imperative
and declarative security calls. Declarative calls are performed using attributes; imperative calls are performed
using new instances of classes within your code. Some calls can be performed only imperatively, while others
can be performed only declaratively. Some calls can be performed in either manner.

• Requesting permissions for our code: Requests are applied to the assembly scope, where your code
informs the runtime about permissions that it either needs to run or specifically does not want to. Security
requests are evaluated by the runtime when our code is loaded into memory. Requests cannot influence
the runtime to give our code more permissions than the runtime would have given your code had the
request not been made. However, requests are what your code uses to inform the runtime about the
permissions it requires in order to run.

• Using secure class libraries: Our class libraries use code access security to specify the permissions they
require in order to be accessed. We should be aware of the permissions required to access any library that
our code uses and make appropriate requests in our code.

Principle, Identity Objects and Evidence


Identity Objects
Identity Objects are used to encapsulate information about the user or entity being validated.

In their basic level, they contain the name and the authentication type.

The name can be a windows account name, while the authentication type can be a logon protocol (such as
Kerberos V5) or a custom value.

The .NET Framework defines a specialized WindowsIdentity object when using Windows Authentication (e.g.
When using an Active Directory), or GenericIdentity for most custom logon scenarios, we can even define
our own.

It makes use of the Identity interface for All Identity classes.

Figure 2. Generic Identity example

Principle (MSDN)
A principal represents the identity and role of a user and acts on the user’s behalf. Role-based security in the
.NET Framework supports three kinds of principals:

• Generic principals represent users and roles that exist independent of Windows NT and Windows 2000
users and roles.

• Windows principals represent Windows users and their roles (or their Windows NT and Windows 2000
groups). A Windows principal can impersonate another user, which means the principal can access a resource
on a user’s behalf while presenting the identity that belongs to that user.

• Custom principals can be defined by an application in any way that is needed for that particular
application. They can extend the basic notion of the principal’s identity and roles.

12
Secure Coding Make Sure Your Program is Safe

Principal Objects
Principal Objects are used for representing the Security Context under which the code is running, integrating
with the identity objects to decide who is allowed to run what.

The .NET provides a GenericPrincipal object and a WindowsPrincipal object.

The IPrincipal interface defines access to its associated Identity object as well as a method to determine if the user
that is identified as a role member.

For instance, whether the user “david” is a member of accounting role.

A role that is able to use functionality for updating the DB.

The IPrincipal interface defines a property for accessing an associated Identity object as well as a method
for determining whether the user identified by the Principal object is a member of a given role. All Principal
classes implement the IPrincipal interface as well as any additional properties and methods that are necessary.
For example, the common language runtime provides the WindowsPrincipal class, which implements
additional functionality for mapping Windows NT or Windows 2000 group membership to roles.

A Principal object is bound to a call context (CallContext) object within an application domain
(AppDomain). A default call context is always created with each new AppDomain, so there is always a call
context available to accept the Principal object. When a new thread is created, a CallContext object is also
created for the thread. The Principal object reference is automatically copied from the creating thread to the
new thread’s CallContext. If the runtime cannot determine which Principal object belongs to the creator of
the thread, it follows the default policy for Principal and Identity object creation.

A configurable application domain-specific policy defines the rules for deciding what type of Principal
object to associate with a new application domain. Where security policy permits, the runtime can create
Principal and Identity objects that reflect the operating system token associated with the current thread
of execution. By default, the runtime uses Principal and Identity objects that represent unauthenticated
users. The runtime does not create these default Principal and Identity objects until the code attempts to
access them.

Trusted code that creates an application domain can set the application domain policy that controls
construction of the default Principal and Identity objects. This application domain-specific policy applies
to all execution threads in that application domain. An unmanaged, trusted host inherently has the ability
to set this policy, but managed code that sets this policy must have the System.Security.Permissions.
SecurityPermission for controlling domain policy.

When transmitting a Principal object across application domains but within the same process (and therefore
on the same computer), the remoting infrastructure copies a reference to the Principal object associated with
the caller’s context to the callee’s context. (MSDN)

Writing Secure Class Libraries


Security vulnerabilities are a common when not fully understanding the correct way of using the .NET CLR
security. So for designing classes, we need to know how to securely design our classes.

Role-Based Security
Role-Based Security in C# is an implementation of the Role-Based security principle that sets the separation
of duty, and compartmentalization and the least privilege and to be used to force multiple approvals for
operations. It uses the Principal, which is constructed from an associated identity to manage and determine
how can we access a piece of code and how is it denied of any access.

13
Secure Coding Make Sure Your Program is Safe

Role-Based Security Checks


Once you have defined identity and principal objects, you can perform security checks against them in one
of the following ways.

Using Imperative Security Checks


For an imperative demand, we can call the Demand method (of the PrincipalPermission object) to determine
whether the current principal object represents the specified identity, role, or both. Assuming a properly
constructed PrincipalPermission object called MyPrincipalPermission, an imperative demand can be called with
the following code.

MyPrincipalPermission.Demand();

Figure 3 shows an example (taken from MSDN).

Figure 3. Perform imperative security checks example

14
Secure Coding Make Sure Your Program is Safe

Using Declarative Security Checks


Declarative demands for PrincipalPermission work the same way as declarative demands for code access
permissions. Demands can be placed at the class level as well as on individual methods, properties, or
events. If a declarative demand is placed at both the class and member level, the declarative demand on the
member overrides (or replaces) the demand at the class level.

The following code example shows a modified version of the PrivateInfo method from the previous section’s
example. This version uses declarative security.

The PrincipalPermissionAttribute defines the principal that the current thread must have to invoke the method.

We simply pass SecurityAction.Demand with the name and role that we require (Figure 4).

Figure 4. Performing declarative security checks example

Directly Accessing the Principal Object


Although using imperative and declarative demands to invoke role-based security checks is the primary
mechanism for checking and enforcing identity and role membership, there might be cases where you want
to access the Principal object and its associated Identity object directly to do authorization tasks without
creating permission objects.

For example, we might not want to use declarative or imperative demands if we do not want a thrown
exception to be the default behavior for validation failure.

In such cases, we can use the static CurrentPrincipal property on the System.Threading.Thread class to access
the Principal object and call its methods.

After obtaining the principal object, we can use conditional statements to control access to our code based on
the principal name as shown in Figure 5.

Figure 5. Directly accessing a Principal object example

Security Tools (.NET Framework)


The command-line tools in this section help you perform security-related tasks, such as configuring security
policy, managing certificates, and digitally signing files. They enable you to test your components and
applications before you deploy them.

These tools are automatically installed with Visual Studio and with the Windows SDK. The best way to run
these tools is by using the Visual Studio or Windows SDK Command Prompt.

15
Secure Coding Make Sure Your Program is Safe

Caspol.exe (Code Access Security Policy Tool(

Enables us to view and configure security policy for the machine policy level, the user policy level, and the
enterprise policy level. In the .NET Framework 4 and later, this tool does not affect code access security
(CAS) policy unless the <legacyCasPolicy> element is set to true.
Cert2spc.exe (Software Publisher Certificate Test Tool(

Creates a Software Publisher’s Certificate (SPC) from one or more X.509 certificates. This tool is for testing
purposes only.
Certmgr.exe (Certificate Manager Tool(

Manages certificates, certificate trust lists (CTLs), and certificate revocation lists (CRLs).
Makecert.exe (Certificate Creation Tool(

Generates X.509 certificates for testing purposes only.


Peverify.exe (PEVerify Tool(

Helps us to verify whether our Microsoft intermediate language (MSIL) code and associated metadata meet
type safety requirements.
SecAnnotate.exe (.NET Security Annotator Tool(

Identifies the SecurityCritical and SecuritySafeCritical portions of an assembly.


SignTool.exe (Sign Tool(

Digitally signs files, verifies signatures in files, and time-stamps files.


Sn.exe (Strong Name Tool(

Helps to create assemblies with strong names. This tool provides options for key management, signature
generation, and signature verification.

Working with Digital Certificates and Code Signing


Imagine the following common scenario:

We are using C# to copy files from one computer to another, in order to execute them locally. A malicious
user is trying to interfere and uses a Man in the Middle attack to intercept the packets sent from the source
to its destination, and change the content, and replace it with a malicious software that he wants us to use
(could be a Trojan, a Virus, etc.). So one solution could be to transfer files using SSL only. Although it
provides the necessary protection against the Man in the Middle attack, we might not want to use TCP for
this kind of transfer and might want to use UDP (because it’s basically one the reasons why we have the
UDP protocol). So we need to think of another way to transfer without an overhead, but still retain security.

Another approach could be, to provide means to make sure that the file we copied to the destination was not
tempered with, and only then run it.

Code Signing
Code signing is the method of using a certificate-based digital signature to digitally sign executables, DLLs,
and scripts in order to verify the source’s identity to ensure that the code has not been changed or corrupted
since it was signed by the source.

16
Secure Coding Make Sure Your Program is Safe

This helps us and our applications to determine whether the software can be trusted for execution (Figure 6).

Figure 6. Code Signing


Purpose of Code Signing

Because of the potential damage that can be caused by an executable or script, it is important that users be
able to trust the code published on the Internet or delivered in a non-secure way (such as SSL).

If we know that an application is signed by a known author, instead of suspicionsuser, we’ll be much more
likely to install or run it.

There are two important ways that Code Signing increases trust:

• Authentication. Verifying who the author of the software is.

• Integrity. Verifying that the software hasn’t been tampered with since it was signed.

What is a Code Signing Certificate?


A code signing certificate allows us, to sign our code using a private and public key system similar to the
method used by SSL and SSH.

A public/private key pair is generated when the certificate is requested. The private key stays on the
applicant’s machine and is never sent to the certificate provider. The public key is submitted to the provider
with the certificate request and the provider issues a certificate. The code signing certificate acts as a digital
signature. When you sign data, you include your digital signature with the data. A certificate contains
information that fully identifies an entity, and is issued by a certificate authority (CA) after that authority
has verified the entity’s identity. When the sender of a message signs the message with its private key, the
message recipient can use the sender’s public key to verify the sender’s identity (Figure 7).

Figure 7. Signingtool.exe Example

17
Secure Coding Make Sure Your Program is Safe

Digital Certificates

Figure 8. Digital Certificate

In cryptography, a public key certificate (also known as a digital certificate or identity certificate) is an
electronic document that uses a digital signature to bind a public key with an identity – information such as
the name of a person or an organization, their address, and so forth (Figure 8).

The certificate can be used to verify that a public key belongs to an individual.

In a typical public key infrastructure (PKI) scheme, the signature will be of a certificate authority (CA).

In a web of trust scheme, the signature is of either the user (a self-signed certificate) or other users («endorsements»).

In either case, the signatures on a certificate are attestations by the certificate signer that the identity
information and the public key belong together.

For provable security this reliance on something external to the system has the consequence that any public
key certification scheme has to rely on some special setup assumption, such as the existence of
a certificate authority.
Contents of a Typical Digital Certificate

• Serial Number: Used to uniquely identify the certificate.

• Subject: The person or entity identified.

• Signature Algorithm: The algorithm used to create the signature.

• Signature: The actual signature to verify that it came from the issuer.

• Issuer: The entity that verified the information and issued the certificate.

18
Secure Coding Make Sure Your Program is Safe

• Valid-From: The date the certificate is first valid from.

• Valid-To: The expiration date.

• Key-Usage: Purpose of the public key (e.g. encipherment, signature, certificate signing).

• Public Key: The public key.

• Thumbprint Algorithm: The algorithm used to hash the public key certificate.

• Thumbprint (also known as fingerprint): The hash itself, used as an abbreviated form of the public key
certificate.

.NET Support for Certificates )Taken Code Guru)


Namespace System.Security.Cryptography.X509Certificates contains the implementation of the X.509 v3 certificate.
X.509 which is the standard for a public key infrastructure (PKI) for single sign-on and Privilege Management
Infrastructure. The various classes from this namespace allow operations such as creating stores, importing,
exporting, deleting, enumerating, and retrieving information on certificates.

The most important classes are:

• X509Store: represents a X.509 store, which is a physical catalog where certificates are persisted and
managed. There are several built in stores grouped in two locations: local machine (contains certificates
shared by all the users) and current user (contains certificates specific to the currently logged user).

• X509Certificate and X509Certificate2: represent a X.509 certificate.

• X509Certificate2Collection: represents a collection of X509Certificate2 objects.


Code Example: X509Certificate2

The following example demonstrates how to use an X509Certificate2 object to encrypt and decrypt a file.
It consists of 3 main functions:
GetCertificateFromStore

Retrieves a certificate from the certificate store of the current user (Figure 9).

Figure 9. Digital Certificate – GetCertificateFromStore

19
Secure Coding Make Sure Your Program is Safe

EncryptFile

Encrypts a file with the certificate (Figure 10).

Figure 10. Digital Certificate – EncryptFile


DecryptFile

Decrypts the file that was encrypted with the certificate (Figure 11).

20
Secure Coding Make Sure Your Program is Safe

Figure 11. Digital Certificate – DecryptFile

21
Secure Coding Make Sure Your Program is Safe

Conclusion
As you can see, C# and the .NET framework provide lots of easy-to-use, easy-to-understand and easy-to-
manage sets of classes, tools, and functions.

However, there are still a lot more to .NET than these examples and a lot more to learn and use when
building security-aware applications and softwares.

I believe that MSDN and other websites are a great source of information, but it is important to first understand
how stuff works, what is its purpose, and how to integrate it, than just copy and paste into our code.

Don’t forget, after all this, we still need to make sure that the code can actually run, and not overload it with
overheads. I hope that it’s been informative for you, and I’d like to thank you for reading!

About the Author


Has years of experience as a System Administrator and Integrator, he have been working mostly with
Windows OS and Linux OS, working with many AD environments, integrated with other Microsoft-
related products. Computer Programmer, best at C# language. He is Informa-tion Security Consultant
at Defensia Company now, advising customers in Information Security related issued, pentesting,
vulnerability assessment, code review and many more.

advertisement
U P D AT E
NOW WITH
STIG
AUDITING

IN SOME CASES

nipper studio
HAS VIRTUALLY

REMOVED
the
NEED FOR a
MANUAL AUDIT
CISCO SYSTEMS INC.
Titania’s award winning Nipper Studio configuration
auditing tool is helping security consultants and end-
user organizations worldwide improve their network
security. Its reports are more detailed than those typically
produced by scanners, enabling you to maintain a higher
level of vulnerability analysis in the intervals between
penetration tests.

Now used in over 45 countries, Nipper Studio provides a


thorough, fast & cost effective way to securely audit over
100 different types of network device. The NSA, FBI, DoD
& U.S. Treasury already use it, so why not try it for free at
www.titania.com

www.titania.com

You might also like