Certificate related docs

How certificate chains work

A certificate chain is an ordered list of certificates, containing an SSL Certificate and Certificate Authority (CA) Certificates, that enable the receiver to verify that the sender and all CA’s are trustworthy. The chain or path begins with the SSL certificate, and each certificate in the chain is signed by the entity identified by the next certificate in the chain.

Any certificate that sits between the SSL Certificate and the Root Certificate is called a chain or Intermediate Certificate. The Intermediate Certificate is the signer/issuer of the SSL  Certificate. The Root CA Certificate is the signer/issuer of the Intermediate Certificate. If the Intermediate Certificate is not installed on the server (where the SSL certificate is installed) it may prevent some browsers, mobile devices, applications, etc. from trusting the SSL certificate. In order to make the SSL certificate compatible with all clients, it is necessary that the Intermediate Certificate be installed.

The chain terminates with a Root CA Certificate. The Root CA Certificate is always signed by the CA itself. The signatures of all certificates in the chain must be verified up to the Root CA Certificate.

The below figure illustrates a certification path from the certificate owner to the Root CA, where the chain of trust begins:



Here is a very simplified explanation:

  1. Your web browser downloads the web server’s certificate, which contains the public key of the web server. This certificate is signed with the private key of a trusted certificate authority.
  2. Your web browser comes installed with the public keys of all of the major certificate authorities. It uses this public key to verify that the web server’s certificate was indeed signed by the trusted certificate authority.
  3. The certificate contains the domain name and/or ip address of the web server. Your web browser confirms with the certificate authority that the address listed in the certificate is the one to which it has an open connection.
  4. Your web browser generates a shared symmetric key which will be used to encrypt the HTTP traffic on this connection; this is much more efficient than using public/private key encryption for everything. Your browser encrypts the symmetric key with the public key of the web server then sends it back, thus ensuring that only the web server can decrypt it, since only the web server has its private key.

Note that the certificate authority (CA) is essential to preventing man-in-the-middle attacks. However, even an unsigned certificate will prevent someone from passively listening in on your encrypted traffic, since they have no way to gain access to your shared symmetric key.



Your server has a certificate, consisting of a private and a public key. The server never gives out the private key of course, but everyone may get the public key. The public key is embedded within a certificate container format. This format contains the IP address or domain name of the server, the owner of this IP address/domain name, an e-mail address of the owner, etc.

The whole thing is signed by a trusted authority. The trusted authority, aka certificate authority (CA) also has a private/public key pair. You give them your certificate, they verify that the information in the container are correct and sign it by their private key, only they have access to.

The public key of the CA is installed on the user system by default, most well known CAs are included already in the default installation of your favorite OS or browser.

When now a user connects to your server, your server uses the private key to sign some data, packs that signed data together with its public key and sends everything to the client.

What can the client now do? First of all, it can use the public key it just got sent to verify the signed data. Since only the owner of the private key is able to sign the data correctly in such a way that the public key can verify the signature, it knows that whoever signed this piece of data, this person is owning the private key to the received public key. So far so well. But what stops a hacker to intercept the packet, replace the signed data with data he signed using a different certificate and also replace the public key with his public key? Nothing.

That’s why after the signed data has been verified (or before it is verified) the client verifies that the received public key has a valid CA signature. Using the already installed public CA key, it verifies that the received public key has been signed by a known CA. Otherwise it is rejected (as a hacker may have replaced it on the way).

Last but not least, it checks the information within the public key container. Does the IP address or domain name really match the IP address or domain name of the server the client is currently talking to? If not, something is fishy!

People may ask: What stops a hacker from just creating his own keypair and just putting your domain name or IP address into the cert? Easy: If he does that, no CA will sign his key. To get a CA signature, you must prove that you are really the owner of this IP address or domain name. The hacker is not, he cannot prove that, he won’t get a signature. So this won’t work.

Okay, how about the hacker registers his own domain, create a certificate for that, and have that signed by a CA? This works, he will get it CA signed, it’s his domain, no problem. However he cannot use this when hacking your connection. If he uses this certificate, the browser will immediately see that the signed public key is for domain example.net, but it is currently talking to example.com, not the same domain, thus something is fishy again.

The server certificate is signed with the private key of the CA. The browser uses the public key of the CA to verify the signature. There is no direct communication between browser and CA.

The important point is that the browser ships with the public CA key. In Firefox see Tools->Options->Advanced->Encryption->ViewCertificates->Authorities. So the browser knows beforehand all CAs it can trust.

If you don’t understand this, look up the basics of Asymmetric Cryptography and Digital Signatures.




The default path where certificates are looked up might be different on each platform. You can lookup your system configuration using the following command:

$ openssl version -d

OPENSSLDIR: "/etc/pki/tls"



Base-64 encoded X.509 (.cer).




Certificates and Encodings

At its core an X.509 certificate is a digital document that has been encoded and/or digitally signed according to RFC 5280.

In fact, the term X.509 certificate usually refers to the IETF’s PKIX Certificate and CRL Profile of the X.509 v3 certificate standard, as specified in RFC 5280, commonly referred to as PKIX for Public Key Infrastructure (X.509).

X509 File Extensions

The first thing we have to understand is what each type of file extension is.   There is a lot of confusion about what DER, PEM, CRT, and CER are and many have incorrectly said that they are all interchangeable.  While in certain cases some can be interchanged the best practice is to identify how your certificate is encoded and then label it correctly.  Correctly labeled certificates will be much easier to manipulat

Encodings (also used as extensions)

  • .DER = The DER extension is used for binary DER encoded certificates. These files may also bear the CER or the CRT extension.   Proper English usage would be “I have a DER encoded certificate” not “I have a DER certificate”.
  • .PEM = The PEM extension is used for different types of X.509v3 files which contain ASCII (Base64) armored data prefixed with a “—– BEGIN …” line.

Common Extensions

  • .CRT = The CRT extension is used for certificates. The certificates may be encoded as binary DER or as ASCII PEM. The CER and CRT extensions are nearly synonymous.  Most common among *nix systems
  • CER = alternate form of .crt (Microsoft Convention) You can use MS to convert .crt to .cer (.both DER encoded .cer, or base64[PEM] encoded .cer)  The .cerfile extension is also recognized by IE as a command to run a MS cryptoAPI command (specifically rundll32.exe cryptext.dll,CryptExtOpenCER) which displays a dialogue for importing and/or viewing certificate contents.
  • .KEY = The KEY extension is used both for public and private PKCS#8 keys. The keys may be encoded as binary DER or as ASCII PEM.

The only time CRT and CER can safely be interchanged is when the encoding type can be identical.  (ie  PEM encoded CRT = PEM encoded CER)

Common OpenSSL Certificate Manipulations

There are four basic types of certificate manipulations. View, Transform, Combination , and Extraction


Even though PEM encoded certificates are ASCII they are not human readable.  Here are some commands that will let you output the contents of a certificate in human readable form;

View PEM encoded certificate

Use the command that has the extension of your certificate replacing cert.xxx with the name of your certificate

openssl x509 -in cert.pem -text -noout
openssl x509 -in cert.cer -text -noout
openssl x509 -in cert.crt -text -noout

If you get the folowing error it means that you are trying to view a DER encoded certifciate and need to use the commands in the “View DER encoded certificate  below”

unable to load certificate
12626:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:647:Expecting: TRUSTED CERTIFICATE

View DER encoded Certificate

openssl x509 -in certificate.der -inform der -text -noout

If you get the following error it means that you are trying to view a PEM encoded certificate with a command meant for DER encoded certs. Use a command in the “View PEM encoded certificate above

unable to load certificate
13978:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1306:
13978:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:380:Type=X509


Transforms can take one type of encoded certificate to another. (ie. PEM To DER conversion)


openssl x509 -in cert.crt -outform der -out cert.der


openssl x509 -in cert.crt -inform der -outform pem -out cert.pem


In some cases it is advantageous to combine multiple pieces of the X.509 infrastructure into a single file.  One common example would be to combine both the private key and public key into the same certificate.

The easiest way to combine certs keys and chains is to convert each to a PEM encoded certificate then simple copy the contents of each file into a new file.   This is suitable for combining files to use in applications like Apache.


Some certs will come in a combined form.  Where one file can contain any one of: Certificate, Private Key, Public Key, Signed Certificate, Certificate Authority (CA), and/or Authority Chain.










openssl to save server certificate


# echo -n | openssl s_client -connect HOST:PORTNUMBER \


With SNI

If the remote server is using SNI (that is, sharing multiple SSL hosts on a single IP address) you will need to send the correct hostname in order to get the right certificate.

openssl s_client -showcerts -servername www.example.com -connect www.example.com:443 </dev/null

Without SNI

If the remote server is not using SNI, then you can skip -servername parameter:

openssl s_client -showcerts -connect www.example.com:443 </dev/null

To view the full details of a site’s cert you can use this chain of commands as well:

$ echo | \
    openssl s_client -servername www.example.com -connect www.example.com:443 2>/dev/null | \
    openssl x509 -text



Converting Using OpenSSL

These commands allow you to convert certificates and keys to different formats to make them compatible with specific types of servers or software.

  • Convert a DER file (.crt .cer .der) to PEM
    openssl x509 -inform der -in certificate.cer -out certificate.pem
  • Convert a PEM file to DER
    openssl x509 -outform der -in certificate.pem -out certificate.der
  • Convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM
    openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes
    You can add -nocerts to only output the private key or add -nokeys to only output the certificates.
  • Convert a PEM certificate file and a private key to PKCS#12 (.pfx .p12)
    openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
  • Convert PEM to CRT (.CRT file)
    openssl x509 -outform der -in certificate.pem -out certificate.crt

OpenSSL Convert PEM

  • Convert PEM to DER
    openssl x509 -outform der -in certificate.pem -out certificate.der
  • Convert PEM to P7B
    openssl crl2pkcs7 -nocrl -certfile certificate.cer -out certificate.p7b -certfile CACert.cer
  • Convert PEM to PFX
    openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt

OpenSSL Convert DER

  • Convert DER to PEM
    openssl x509 -inform der -in certificate.cer -out certificate.pem

OpenSSL Convert P7B

  • Convert P7B to PEM
    openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
  • Convert P7B to PFX
    openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
    openssl pkcs12 -export -in certificate.cer -inkey privateKey.key -out certificate.pfx -certfile CACert.cer

OpenSSL Convert PFX

  • Convert PFX to PEM
    openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes

Generate rsa keys by OpenSSL

  • Using OpenSSL on the command line you’d first need to generate a public and private key, you should password protect this file using the -passout argument, there are many different forms that this argument can take so consult the OpenSSL documentation about that.
    openssl genrsa -out private.pem 1024
  • This creates a key file called private.pem that uses 1024 bits. This file actually have both the private and public keys, so you should extract the public one from this file:
    openssl rsa -in private.pem -out public.pem -outform PEM -pubout
    openssl rsa -in private.pem -pubout > public.pem
    openssl rsa -in private.pem -pubout -out public.pem

    You’ll now have public.pem containing just your public key, you can freely share this with 3rd parties. You can test it all by just encrypting something yourself using your public key and then decrypting using your private key, first we need a bit of data to encrypt:

  • Example file :
    echo 'too many secrets' > file.txt
  • You now have some data in file.txt, lets encrypt it using OpenSSL and the public key:
    openssl rsautl -encrypt -inkey public.pem -pubin -in file.txt -out file.ssl
  • This creates an encrypted version of file.txt calling it file.ssl, if you look at this file it’s just binary junk, nothing very useful to anyone. Now you can unencrypt it using the private key:
    openssl rsautl -decrypt -inkey private.pem -in file.ssl -out decrypted.txt
  • You will now have an unencrypted file in decrypted.txt:
    cat decrypted.txt
    |output -> too many secrets

RSA TOOLS Options in OpenSSL

  • NAME

    rsa – RSA key processing tool


    openssl rsa [-help] [-inform PEM|NET|DER] [-outform PEM|NET|DER] [-in filename] [-passin arg] [-out filename] [-passout arg] [-aes128] [-aes192] [-aes256] [-camellia128] [-camellia192] [-camellia256] [-des] [-des3] [-idea] [-text] [-noout] [-modulus] [-check] [-pubin] [-pubout] [-RSAPublicKey_in] [-RSAPublicKey_out] [-engine id]


    The rsa command processes RSA keys. They can be converted between various forms and their components printed out. Note this command uses the traditional SSLeay compatible format for private key encryption: newer applications should use the more secure PKCS#8 format using the pkcs8 utility.


    Print out a usage message.

    -inform DER|NET|PEM

    This specifies the input format. The DER option uses an ASN1 DER encoded form compatible with the PKCS#1 RSAPrivateKey or SubjectPublicKeyInfo format. The PEM form is the default format: it consists of the DER format base64 encoded with additional header and footer lines. On input PKCS#8 format private keys are also accepted. The NET form is a format is described in the NOTES section.

    -outform DER|NET|PEM

    This specifies the output format, the options have the same meaning as the -inform option.

    -in filename

    This specifies the input filename to read a key from or standard input if this option is not specified. If the key is encrypted a pass phrase will be prompted for.

    -passin arg

    the input file password source. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.

    -out filename

    This specifies the output filename to write a key to or standard output if this option is not specified. If any encryption options are set then a pass phrase will be prompted for. The output filename should not be the same as the input filename.

    -passout password

    the output file password source. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.


    These options encrypt the private key with the specified cipher before outputting it. A pass phrase is prompted for. If none of these options is specified the key is written in plain text. This means that using the rsa utility to read in an encrypted key with no encryption option can be used to remove the pass phrase from a key, or by setting the encryption options it can be use to add or change the pass phrase. These options can only be used with PEM format output files.


    prints out the various public or private key components in plain text in addition to the encoded version.


    this option prevents output of the encoded version of the key.


    this option prints out the value of the modulus of the key.


    this option checks the consistency of an RSA private key.


    by default a private key is read from the input file: with this option a public key is read instead.


    by default a private key is output: with this option a public key will be output instead. This option is automatically set if the input is a public key.

    -RSAPublicKey_in, -RSAPublicKey_out

    like -pubin and -pubout except RSAPublicKey format is used instead.

    -engine id

    specifying an engine (by its unique id string) will cause rsa to attempt to obtain a functional reference to the specified engine, thus initialising it if needed. The engine will then be set as the default for all available algorithms.

  • NOTESThe PEM private key format uses the header and footer lines:
    -----END RSA PRIVATE KEY-----

    The PEM public key format uses the header and footer lines:

    -----BEGIN PUBLIC KEY-----
    -----END PUBLIC KEY-----

    The PEM RSAPublicKey format uses the header and footer lines:

    -----BEGIN RSA PUBLIC KEY-----
    -----END RSA PUBLIC KEY-----

    The NET form is a format compatible with older Netscape servers and Microsoft IIS .key files, this uses unsalted RC4 for its encryption. It is not very secure and so should only be used when necessary.

    Some newer version of IIS have additional data in the exported .key files. To use these with the utility, view the file with a binary editor and look for the string “private-key”, then trace back to the byte sequence 0x30, 0x82 (this is an ASN1 SEQUENCE). Copy all the data from this point onwards to another file and use that as the input to the rsa utility with the -inform NET option.


    To remove the pass phrase on an RSA private key:

     openssl rsa -in key.pem -out keyout.pem

    To encrypt a private key using triple DES:

     openssl rsa -in key.pem -des3 -out keyout.pem

    To convert a private key from PEM to DER format:

      openssl rsa -in key.pem -outform DER -out keyout.der

    To print out the components of a private key to standard output:

      openssl rsa -in key.pem -text -noout

    To just output the public part of a private key:

      openssl rsa -in key.pem -pubout -out pubkey.pem

    Output the public part of a private key in RSAPublicKey format:

      openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem



Disable Server verification:
# openssl s_client -showcerts -connect <server_url>:8883 -verify false


Retrieve openssl CA configuration:

# openssl version -d
WARNING: can’t open config file: /etc/openssl/openssl.cnf
OPENSSLDIR: “/etc/openssl”



SUSE Linux Enterprise Server


How to create a .pem File for SSL Certificate Installations


Privacy Enhanced Mail (PEM) files are concatenated certificate containers frequently used in certificate installations when multiple certificates that form a complete chain are being imported as a single file. They are a defined standard in RFCs 1421 through 1424. They can be thought of as a layered container of chained certificates. A .pem file is a container format that may just include the public certificate or the entire certificate chain (private key, public key, root certificates):

  • Private Key
  • Server Certificate (crt, puplic key)
  • (optional) Intermediate CA and/or bundles if signed by a 3rd party

How to create a self-signed PEM file:
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem

How to create a PEM file from existing certificate files that form a chain:

  • (optional) Remove the password from the Private Key by following the steps listed below:
    • Type openssl rsa -in server.key -out nopassword.key and press Enter.
    • Enter the pass phrase of the Private Key.
  • Combine the private key, public certificate and any 3rd party intermediate certificate files:
    • cat nopassword.key > server.pem
    • cat server.crt >> server.pem
      • Repeat this step as needed for third-party certificate chain files, bundles, etc:
        cat intermediate.crt >> server.pem

Additional Information

How to create a PEM file with the help of an automated script:

  • Download NetIQ Cool Tool OpenSSL-Toolkit.
  • Select Create Certificates | PEM with key and entire trust chain
  • Provide the full path to the directory containing the certificate files.
  • Provide the filenames of the following:
    • private key
    • public key (server crt)
    • (conditional) password for private key
    • (conditional) any intermediate certificate chain file(s)

For additional information, please see TID 7015502 – Common Mistakes in SSL Certificate Management & Implementation.

The following details the structure of a typical .pem file (including the entire certificate chain):
(Private Key: domain_name.key contents)
(Primary SSL certificate: domain_name.crt contents)
(Intermediate certificate: certChainCA.crt contents)













remove printChaser

echo Start
echo #
echo ######################## Default dirctory for x86 x64 ########################
echo #
echo this command is default system32 directory for x86 OS or x64 OS
cd %windir% & cd system32
reg delete “HKCU\Software\Microsoft\Windows\CurrentVersion\Run” /v “PcAgent64” /f
reg delete “HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run” /v “PcAgent64” /f
echo #
echo ######################## Change the dirctory for x64 ########################
echo #
echo this command is x86 application’s registry for x64 OS
cd %windir% & cd syswow64
reg delete “HKCU\Software\Microsoft\Windows\CurrentVersion\Run” /v “PcAgent64” /f
reg delete “HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run” /v “PcAgent64” /f
echo End


TO remove the PrintChaser, need to modify the bat above.

anyway, the Information need to change is following:

C:\Program Files\PrintChaser\PCLoginAgent.exe

C:\Program Files\PrintChaser\PROXTRAC.EXE

reg delete “HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run” /v “PcAgent64” /f





git related tips


  • git add -A stages All
  • git add . stages new and modified, without deleted
  • git add -u stages modified and deleted, without new


git add -A is equivalent to git add .; git add -u.

The important point about git add . is that it looks at the working tree and adds all those paths to the staged changes if they are either changed or are new and not ignored, it does not stage any ‘rm’ actions.

git add -u looks at all the already tracked files and stages the changes to those files if they are different or if they have been removed. It does not add any new files, it only stages changes to already tracked files.

git add -A is a handy shortcut for doing both of those.

You can test the differences out with something like this (note that for Git version 2.x your output for git add .git statuswill be different):

git init
echo Change me > change-me
echo Delete me > delete-me
git add change-me delete-me
git commit -m initial

echo OK >> change-me
rm delete-me
echo Add me > add-me

git status
# Changed but not updated:
#   modified:   change-me
#   deleted:    delete-me
# Untracked files:
#   add-me

git add .
git status

# Changes to be committed:
#   new file:   add-me
#   modified:   change-me
# Changed but not updated:
#   deleted:    delete-me

git reset

git add -u
git status

# Changes to be committed:
#   modified:   change-me
#   deleted:    delete-me
# Untracked files:
#   add-me

git reset

git add -A
git status

# Changes to be committed:
#   new file:   add-me
#   modified:   change-me
#   deleted:    delete-me


Git Version 1.xenter image description here

Git Version 2.xenter image description here

Long-form flags:

  • git add -A is equivalent to git add --all
  • git add -u is equivalent to git add --update

Further reading:


How to Add Route in Linux

In the 1st part of the IP Routing series, we learned the fundamentals of Linux IP Routing.

Route command is used to show/manipulate the IP routing table. It is primarily used to setup static routes to specific host or networks via an interface.

In this article we will see how to manipulate the routing tables in Linux using route command.

We’ll first explain how routing is done with some basic route command examples, and then we’ll explain using a sample network architecture about how to setup routes in your network.

I. How Routing is Done?

1. Display Existing Routes

route command by default will show the details of the kernel routing table entries. In this example, the ip-address of the system where the route command is being executed is

$ route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface     *        U     0      0        0 eth0

The above command shows that if the destination is within the network range –, then the gateway is *, which is

When packets are sent within this IP range, then the MAC address of the destination is found through ARP Protocol and the packet will be sent to the MAC address.

If you don’t know what ARP is, you should first understand how ARP protocol works.

In order to send packets to destination which is not within this ip range, the packets will be forwarded to a default gateway, which decides further routing for that packet. We will see this shortly.

By default route command displays the host name in its output. We can request it to display the numerical IP address using -n option as shown below.

$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface   U     0      0        0 eth0         UG    0      0        0 eth0

2. Adding a Default Gateway

We can specify that the packets that are not within the network has to be forwarded to a Gateway address.

The following route add command will set the default gateway as

$ route add default gw

Now the route command will display the following entries.

$ route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface     *        U     0      0        0 eth0
default         gateway.co.in         UG    0      0        0 eth0

Now we have just added a default gateway to our machine. To verify whether it is working properly, ping some external host (for example, google.com) to send ICMP packet.

$ ping www.google.com

The following is the sequences of evets that happens when the above ping command is executed.

  1. First it will query the DNS server to obtain the ip-address of google.com ( for example: )
  2. The destination address ( ) is not within the network range.
  3. So, in Layer-3 (IP header) the DESTINATION IP will be set as “”.
  4. In Layer-2, the DESTINATION MAC address will be the filled in as the MAC address of the default gateway (’s MAC ). The MAC will be found by using ARP as described earlier.
  5. When the packet is sent out, the network switch ( which works on Layer-2 ), send the packet to the default gateway since the destination MAC is that of the gateway.
  6. Once the gateway receives the packet, based on its routing table, it will forward the packets further.

The above 2 examples would have given a good idea about how routing is done within a network. Now we will see other command line options available with route command.

3. List Kernel’s Routing Cache Information

Kernel maintains the routing cache information to route the packets faster. We can list the kernel’s routing cache information by using the -C flag.

$ route -Cn
Kernel IP routing cache
Source          Destination     Gateway         Flags Metric Ref    Use Iface          0      0        1 eth0          0      0        0 eth0

4. Reject Routing to a Particular Host or Network

Sometimes we may want to reject routing the packets to a particular host/network. To do that, add the following entry.

$ route add -host reject

As you see below, we cannot access that particular host (i.e .51 host that we just rejected).

$ ping
connect: Network is unreachable

However we can still access other hosts in the network (for example, .52 host is still accessible).

$ ping
PING ( 56(84) bytes of data.
64 bytes from icmp_seq=1 ttl=64 time=7.77 ms

If you want to reject an entire network ( – ), then add the following entry.

$ route add -net netmask reject

Now, you cannot access any of the host in that network (for example: .51, .52, .53, etc.)

$ ping
connect: Network is unreachable

$ ping
connect: Network is unreachable

$ ping
connect: Network is unreachable

II. A Sample Network Architecture (to understand routing)

Let us use the following sample network architecture for the rest of the examples.

In the diagram below, we have 2 individual networks ( and, with subnet mask of ).

We also have a “GATEWAY” machine with 3 network cards. 1st card is connected to, 2nd card is connected to, and the 3rd card is connected to the external world.

5. Make 192.168.3.* Accessible from 192.168.1.*

Now we need to add a routing entry such that we are able to ping 192.168.3. series ip-addresses from 192.168.1. series. The common point we have is the GATEWAY machine.

So, on each machine in 192.168.1.* network a default gateway will be added as shown below.

$ route add default gw

Now when pings, it will go to the GATEWAY via

In GATEWAY, add the following routing entry.

$ route add -net netmask gw

Now all the packets addressed to 192.168.3.* network will be forwarded via the interface, which then delivers the packets to the addressed machine.

6. Make 192.168.1.* Accessible from 192.168.3.*

It is very similar to what we did earlier.

So, on each machine in 192.168.3.* network a default gateway will be added as shown below.

$ route add default gw

In GATEWAY, add the following routing entry.

$ route add -net netmask gw

Now 192.168.3.* machines can ping 192.168.1.* machines.

7. Allow Internet Access ( External World )

In the previous two example, we have interconnected the 2 different networks.

Now we need to access the internet from these 2 different networks. For that, we can add a default routing ( when no routing rule matches ) to the which is connected to the external world as follows.

$ route add default gw

This is how it works:

  1. Now when you try to access the internet (for example: ping google.com) from any of these machines (for example, from, the following is the sequence of events that happens.
  2. Since the destination (google.com) is not within 3.* series, it will be forwarded to GATEWAY via 3.10 interface
  3. In GATEWAY, it checks whether the destination is within 1.* range. In this example, it is not.
  4. It then checks whether the destination is within 2.* range. IN this example, it is not
  5. Finally, it takes the default route to forward the packets (i.e using the interface, which is connected to the external world).





Further read:




Port-forwarding in QNX

For some reason, I needed to forward certain packets from 8080 to 9021 in local,

In linux, you can simply use the iptable command to do it.

In FREEBSD based system like QNX, you need to use pf (Packet Filter pseudo-device).


Packet filtering takes place in io-pkt. A pseudo-device, /dev/pf, lets user processes control the behavior of the packet filter through an ioctl() interface. There are commands to enable and disable the filter, load rule sets, add and remove individual rules or state table entries, and retrieve statistics. The most commonly used functions are covered by pfctl.

  1. write pf.conf as follow:
    rdr proto tcp from any to any port 8080 -> port 9021
  2. type following command:
    # pfctl -f /etc/pf.conf
    # pfctl -e
    OR in one line:
    # pfctl -F all ; pfctl -vvvvvef /etc/pf.conf



 Useful pfctl Options
Command Purpose
pfctl -e Enable PF.
pfctl -d Disable PF.
pfctl -F all -f /etc/pf.conf Flush all NAT, filter, state, and table rules and reload /etc/pf.conf.
pfctl -s [ rules | nat | states ] Report on the filter rules, NAT rules, or state table.
pfctl -vnf /etc/pf.conf Check /etc/pf.conf for errors, but do not load ruleset.


# Show Firewall Rules:
pfctl -sr
# Show NAT rules
pfctl -sn
# Show all
pfctl -sa

For more verbose output including rule counters, ID numbers, and so on, use:

pfctl -vvsr
Basic FreeBSD PF firewall for web server – /etc/pf.conf:
# vim: set ft=pf
# /etc/pf.conf</pre>

webports = "{http, https}"
int_tcp_services = "{domain, ntp, smtp, www, https, ftp}"
int_udp_services = "{domain, ntp}"

set skip on lo
set loginterface $ext_if

# Normalization
scrub in all random-id fragment reassemble

block return in log all
block out all

antispoof quick for $ext_if

# Block 'rapid-fire brute force attempts
table <bruteforce> persist
block quick from <bruteforce>

# ftp-proxy needs to have an anchor
anchor "ftp-proxy/*"

# SSH is listening on port 26
pass in quick proto tcp to $ext_if port 26 keep state (max-src-conn 15, max-src-conn-rate 5/3, overload <bruteforce> flush global)

# Webserver
pass proto tcp from any to $ext_if port $webports

# Allow essential outgoing traffic
pass out quick on $ext_if proto tcp to any port $int_tcp_services
pass out quick on $ext_if proto udp to any port $int_udp_services

To permanently block outgoing traffic to specific domains and/or ports you should create a new anchor file and add it to pf.conf.

  1. Create an anchor file org.user.block.out in /private/etc/pf.anchors
    sudo touch /private/etc/pf.anchors/org.user.block.out

    with the following content and a trailing empty line

    mybadtcphosts = "{ www.domain.com, domain.com,, }"
    mybadtcpports = "{ 443, 80 }"
    mybadudphosts = "{ www.domain3.com, domain3.com,, }"
    mybadudpports = "{ 53, 5353 }"
    block drop out proto tcp from any to $mybadtcphosts port $mybadtcpports
    block drop out proto udp from any to $mybadudphosts port $mybadudpports

    The additional domain names/IP addresses in mybad*hosts are just an example how to add additional domains. The same goes for the ports 80/5353 in mybad*ports.

    A simple but less flexible solution is:

    block drop out proto tcp from any to domain.com port 80
  2. Modify the file /private/etc/pf.conf but keep a trailing empty lineoriginal file:
    scrub-anchor "com.apple/*"
    nat-anchor "com.apple/*"
    rdr-anchor "com.apple/*"
    dummynet-anchor "com.apple/*"
    anchor "com.apple/*"
    load anchor "com.apple" from "/etc/pf.anchors/com.apple"


    scrub-anchor "com.apple/*"
    nat-anchor "com.apple/*"
    rdr-anchor "com.apple/*"
    dummynet-anchor "com.apple/*"
    anchor "com.apple/*"
    anchor "org.user.block.out"
    load anchor "com.apple" from "/etc/pf.anchors/com.apple"
    load anchor "org.user.block.out" from "/etc/pf.anchors/org.user.block.out"
  3. Parse and test your anchor file to make sure there are no errors:
    sudo pfctl -vnf /etc/pf.anchors/org.user.block.out
  4. Now modify /System/Library/LaunchDaemons/com.apple.pfctl.plist from



    You have to disable System Integrity Protection if El Capitan is installed to accomplish this. After editing the file reenable SIP. After rebooting your Mac pf will be enabled (that’s the -e option).

    Alternatively you may create your own launch daemon similar to the answer here: Using Server 5.0.15 to share internet WITHOUT internet sharing.

After a system update or upgrade some of the original files above may have been replaced and you have to reapply all changes.

Sample /etc/pf.conf

#### First declare a couple of variables ####
### Outgoing tcp / udp port ####
### 43 - whois, 22 - ssh ###
tcp_services = "{ ssh, smtp, domain, www, https, 22, ntp, 43,ftp, ftp-data}"
udp_services = "{ domain, ntp }"
### allow ping / pong ####
icmp_types = "{ echoreq, unreach }"

#### define tables. add all subnets and ips to block
table <blockedip> persist file "/etc/pf.block.ip.conf"

martians = "{,,,,,,, }"

### admin server ranges ###
adminrange = ""

# connected to internet
ext_if = "em1"
# connected to vpn / lan
int_if = "em0"

##### ftp proxy

#### Normalization
#scrub provides a measure of protection against certain kinds of attacks based on incorrect handling of packet fragments
scrub in all

#### NAT and RDR start
#nat-anchor "ftp-proxy/*"
#rdr-anchor "ftp-proxy/*"

# redirect ftp traffic
#rdr pass proto tcp from any to any port ftp -> $proxy port $proxyport

# Drop incoming everything
block in all
block return

# keep stats of outgoing connections
pass out keep state

# We need to have an anchor for ftp-proxy
#anchor "ftp-proxy/*"

# unlimited traffic for loopback and lan / vpn
set skip on {lo0, $int_if}

# activate spoofing protection for all interfaces
block in quick from urpf-failed

#antispoof is a common special case of filtering and blocking. This mechanism protects against activity from spoofed or forged IP addresses
antispoof log for $ext_if

#Block RFC 1918 addresses
block drop in log (all) quick on $ext_if from $martians to any
block drop out log (all) quick on $ext_if from any to $martians


# Block all ips
# pfctl -t blockedip -T show
block drop in log (all) quick on $ext_if from <blockedip> to any
block drop out log (all) quick on $ext_if from any to <blockedip>

# allow outgoing
pass out on $ext_if proto tcp to any port $tcp_services
pass out on $ext_if proto udp to any port $udp_services

# Allow trace route
pass out on $ext_if inet proto udp from any to any port 33433 >< 33626 keep state

# Allow admin to get into box
pass in on $int_if from $adminrange to any

# Allow incoming ssh, http, bind traffic
# pass in on $ext_if proto tcp from any to any port 25
pass in on $ext_if proto tcp from any to any port ssh flags S/SA synproxy state
pass in on $ext_if proto udp from any to any port domain
pass in on $ext_if proto tcp from any to any port domain flags S/SA synproxy state
pass in on $ext_if proto tcp from any to any port http flags S/SA synproxy modulate state
pass inet proto icmp all icmp-type $icmp_types keep state
## add your rule below ##

PF sample configuration

To setup PF you will first need enable PF and define where the rules file will reside. This can be done by editing /etc/rc.conf and adding the following lines:
Next, you must define the rule set which you will put in /etc/pf.conf. Below is an example which essentially allows all outgoing traffic and blocks anything other than TCP ports 22, 80, and 443. It will also allow incoming ICMP unreachable and echo requests.
# PF Rules Example
## definitions
## make sure to set these for your environment
public_int = “em0”                      # public interface
tcp_svcs = “{ 22 80 443 }”              # tcp service ports
icmp_types = “{ echoreq, unreach }”     # icmp types
## ignore loopback interface
set skip on lo
## restrict incoming traffic / unrestrict outgoing traffic
block in all
pass out all
## allow tcp ports specified by $tcp_svcs
pass in quick on $public_int proto tcp from any to any port $tcp_svcs
## allow icmp request types specified by $icmp_types
pass in inet proto icmp all icmp-type $icmp_types
You can now start PF by rebooting. Or you can load it manually, without rebooting, by running the following:
/etc/rc.d/pf restart
If you want to verify the PF rule set has been loaded, use the command:
pfctl -s rules
Which should output something similar to:
block drop in all
pass out all flags S/SA keep state
pass in quick on em0 proto tcp from any to any port = ssh flags S/SA keep state
pass in quick on em0 proto tcp from any to any port = http flags S/SA keep state
pass in quick on em0 proto tcp from any to any port = https flags S/SA keep state
pass in inet proto icmp all icmp-type echoreq keep state
pass in inet proto icmp all icmp-type unreach keep state


rdr only monitors in-coming packets,
nat monitors out-going packets, but only changes source NAT.

cross-compile libdmclient for QNX

download the source:

# git clone https://github.com/01org/libdmclient.git

autoconf the source:

# autoconf –install

set the qnx compile environment:

# source ~/qnx70/qnxsdp-env.sh

create the compile.sh file as follow:

export CC="qcc -V5.4.0,gcc_ntoaarch64le"
export CXX="q++ -V5.4.0,gcc_ntoaarch64le"

export LIBCURL_CFLAGS=-I/home/jiafei427/qnx70/target/qnx7/usr/include/curl
export LIBCURL_LIBS=-L/home/jiafei427/qnx70/target/qnx7/aarch64le/usr/lib
export SQLITE3_CFLAGS=-I/home/jiafei427/qnx70/target/qnx7/usr/include
export SQLITE3_LIBS=-L/home/jiafei427/qnx70/target/qnx7/aarch64le/usr/lib

echo "-- cleaning...."
make clean

./configure --prefix=/home/jiafei427/tmp/test/oma-dm/libdmclient/output --host=aarch64-nto-qnx CFLAGS="-I/home/jiafei427/qnx70/target/qnx7/usr/include/io-pkt/machine/ -I/home/jiafei427/qnx70/target/qnx7/usr/include/io-pkt/"

echo "-- Building"

make VERBOSE=1

echo "-- finish building"
make install

then it will compile the libdmclient to the output folder. 🙂


I tried to compile the test programs too, but there was some errors, so I just gave up.


Hope it can help others.