Saturday, May 23, 2020

CSP (Content Security Policy) - Part 2

About 3 years ago, I had a blog to talk about the same topic regarding CSP. Now, I want to revisit this to do a refresh as the security team recently enforced this adoption in products. The following knowledge and information are based on google developer document

CSP defines the Content-Security-Policy HTTP header, which allows you to create a whitelist of sources of trusted content, and instructs the browser to only execute or render resources from those sources.

CSP provides a rich set of policy directives that enable fairly granular control over the resources that a page is allowed to load

By default, directives are wide open. CSP provides a default-src directive to allow you override this default behavior. script-src, style-src, img-src, media-src, font-src, connect-src, object-src, child-src etc *-src directives will take this default as a fallback.

CSP preferred delivery mechanism is an HTTP header. It can be useful, however, to set a policy on a page directly in the html markup.
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; child-src 'none'; object-src 'none'">
Content-Security-Policy-Report-Only header
The policy specified in report-only mode won't block restricted resources, but it will send violation reports to the location you specify.

You can use as many or as few of these directives as makes sense for your specific application, simply listing each in the HTTP header, separating directives with semicolons.

Content-Security-Policy: default-src 'none'; script-src https://cdn.mybank.net; style-src https://cdn.mybank.net; img-src https://cdn.mybank.net; connect-src https://api.mybank.com; child-src 'self'

Content-Security-Policy: default-src https://cdn.example.net; child-src 'none'; object-src 'none'


Use openssl to check SSL Certificate

Modern browsers provide the GUI to quickly check SSL certificate details

Sometimes in Linux environment, we need to use command line to check SSL certificate, then openssl comes to the picture.

$ echo | openssl s_client -servername NAME -connect HOST:PORT 2>/dev/null | openssl x509
$ echo | openssl s_client -servername NAME -connect HOST:PORT 2>/dev/null | openssl x509 -noout -${param}
  • -text: print ssl certificate in text format, like echo | openssl s_client -connect www.google.com:443 2>/dev/null | openssl x509 -text
  • -fingerprint: print certificate fingerprints
  • -dates: print notBefor and notAfter date and time
  • -subject: print subject name
  • -issuer: print certificate issuer CA
Run man s_client to see the all available options.
Run man x509 to see the all available options.

Use below command to check ssl cert chain
openssl s_client -showcerts -connect example.com:443 -servername example.com

SSL certificate formats

There are 3 SSL Certificate Formats and Encodings
  1. The most commonly used encoding schema for X.509 certificate files is the PEM (Privacy Enhanced Mail) encoding
  2. DER (Distinguished Encoding Rules) is another popular encoding used to store X.509 certificate files.
  3. PKCS refers to a group of public-key cryptography standards devised and published by RSA Security. 

What is inside an SSL certificate?

An SSL certificate usually contains a name, public key, the digital signature of the certificate issuer, the name of the issuer, certificate serial number, expiration date and additional information.

X.509 Version 3 certificates support the following fields:
Subject: Provides the entity details that the CA issues the certificate to.
Issuer: Provides a distinguished name for the CA that issued the certificate.
Validity: Provides the date and time when the certificate becomes valid, and becomes invalid. The date when an application evaluates the certificate must fall between the Valid From and Valid To fields.
Serial Number: Provides a unique identifier for each certificate that a CA issues.
Public Key: Contains the public key of the key pair that is associated with the certificate
Signature Algorithm: The algorithm used to sign the certificate, like SHA-256 with RSA Encryption
Signature: Bit string containing the digital signature, like 512 bytes : 0D 60 34 91 79 92 CE 50 AE xx xx .....
Fingerprints: Provides the unique identifier of the certificate. In X.509-based PKI system, fingerprints are primarily used to authenticate root keys. 

X.509 version 3 certificates also include optional extensions:
Subject Alternative Name: This extension allows multiple hostnames to be protected by a single certificate. SAN certificate is also known as Unified Communication Certificate (UCC) or a multi-domain certificate.

CRL distribution points (CDP): When a server presents a certificate, an application or client must determine whether the certificate has been revoked. The CDP extension provides one or more URLs where the application or service can retrieve the certificate revocation list (CRL) from.

Authority Information Access (AIA): When validating a certificate, the certificate of the CA that issued the certificate, also referred to as the parent CA, must also be evaluated for revocation and validity. This extension provides one or more URLs from where an application can retrieve the issuing CA certificate.

Enhanced Key Usage (EKU): This attribute includes an object identifier (OID) for each application  a certificate can be used for. Each OID is a unique sequence of numbers from a worldwide registry.

Certificate policies: Describes what measures an organization takes to validate the identity of a certificate requestor before it issues a certificate. An OID is used to represent the validation process and can include a policy-qualified URL that fully describes the measures taken to validate the identity.

What is an SSL certificate?

An SSL certificate is a digital certificate that authenticates the identity of a website or a server. The most widely accepted format for certificates is X.509.

A CA (Certification Authority) is a trusted third party that vouches for the identity of individuals and organizations.  Essentially the certificate authorities maintain a large database of public keys which are distributed as requested. For instance, Godaddy, DigiCert, Verisign etc are popular CAs.

A Certificate Request is used to obtain a CA signed Server Certificate or Client Certificate from a Certification Authority.

A Server Certificate is digital certificate used to identify the server to clients when they connect.  The public and private keys associated with the server certificate are also used to encrypt the SSL session key information.

A Client Certificate is a digital certificate used to identify individuals when they connect to an SSL server.

Self-Signed Server Certificates are as cryptographically secure as CA signed certificates but are generally not "trusted" by client programs (e.g. browsers).

A Signing Certificate is used to digitally sign a client or server certificate during the certificate generation process. It is part of the certificate chain.

A Root Certificate is the starting certificate in a certificate hierarchy.  All certificates contain information tracing their origin back to a Root Certificate.  A Trusted Root Certificate is one where the root certificate is known to the requester.  The Trusted Root Certificate must be installed at the client when authenticating a Server Certificate.  A Trusted Root Certificate must be installed at the server when authenticating a Client Certificate. (See Mutual TLS authentication)

A Certificate Private Key is used to decrypt messages encrypted using the Certificate Public Key contained in a digital certificate.  The Private Key is generally password protected using the Private Key Password (passphrase) to prevent unauthorized use of the Private Key.  If the Private Key Password is compromised, the Certificate must be revoked and a new one generated.

How does the client (e.g. browser) know when to trust an SSL certificate?

The connection is trusted if:
  • The root certificate for your website matches the pre-installed root certificate in the browser
  • None of the certificates in the chain on the server are invalid, expired or revoked.
  • The domain name in your certificate matches the domain name in the URL.

Wednesday, May 20, 2020

ESPP 101

Employee Stock Purchase Plans (ESPP) usually gives employee the opportunity to buy company stock at a discount, usually it is 15%.

Two dates to remember:
Grant date (offering date)
Purchase date (exercise date)

Two price to remember for tax purpose:Grant price
Purchase price

Two years to remember for qualified disposition:
2 years since grant date
1 years since purchase date

When the company buys the shares for you, you do not owe any taxes.
When you sell the stock, the discount that you received when you bought the stock is generally considered additional compensation to you, so you have to pay taxes on it as regular income.  The 15% discount applies to the lower price, and the discount amount will be considered ordinary income in sale year's w2 for qualified disposition. (Remember to adjust the cost basis in tax return)

To get favorable long-term capital gains treatment, you have to hold the shares purchased more than one year from the purchase date and more than two years from the grant date.

Friday, May 15, 2020

读书笔记 - The Lessons of History

This book is a collections of essays from Will & Ariel Durant, winners of the pulitzer prize.

1. Hesitations
The present is the past rolled up for action, and the past is the present unrolled for understanding.
We can learn enough from history to bear reality patiently, and to respect one another's delusions.
Only a fool would try to compress a hundred centuries into a hundred pages of hazardous conclusions.

2. History and the Earth
Human history is a brief spot in space, and its first lesson is modesty.
History is subject to geology.
Geography is the matrix of history, its nourishing mother and disciplining home.
The development of the airplane will again alter the map of civilization.
The influence of geographic factors diminishes as technology grows.
Man, not the earth, makes civilization.

3. Biology and History
History is a fragment of biology: the life of man is a portion of the vicissitudes of organisms on land and sea.
The laws of biology are the fundamental lessons of history.
The first biological lesson of history is that life is competition.
The second biological lesson of history is that life is selection.
The third biological lesson of history is that life must breed.

4. Race and History
The rise, success, decline, and fall of a civilization depend upon the inherent quality of the race.
The degeneration of a civilization is what the word itself indicates - a falling away from the genus, stock, or race.
Some weaknesses in the race theory are obvious.
Difficulties remain even if the race theory is confined to the white man.
The ancient cultures of Egypt, Greece, and Rome were evidently the product of geographical opportunity and economic and political development rather than of racial constitution, and much of their civilization had an oriental source.
A knowledge of history may teach us that civilization is a co-operative product, that nearly all peoples have contributed to it; it is our common heritage and debt; and the civilized soul will reveal itself in treating every man or woman.

5. Character and History
Society is founded not on the ideals but on the nature of man, and the constitution of man rewrites the constitutions of states.
Known history shows little alteration in the conduct of mankind.
Evolution in man during recorded time has been social rather than biological.
The initiative individual - the great man, the hero, the genius, - regains his place as a formative force in history.
Intellect is therefore a vital force in history, but it can also be a dissolve and destructive power.
The conservative who resists change is as valuable as the radical who proposes it.

6. Morals and History
Morals are the rules by by which a society exhorts its members and associations to behavior consistent with its order, security, and growth.
Moral codes differ because they adjust themselves to historical and environmental conditions.
History as usually written is quite different from history as usually lived; the history records the exceptional because it is interesting.

7. Religion and History
Religion does not seem at first to have had any connection with morals.
Does history support a belief in God?
One lesson of history is that religion has many lives, and a habit of resurrection.
There is no significant example in history of a society successfully maintaining moral life without the aid of religion.

8. Economics and History
History is economics in action - the contest, among individuals, groups, classes, and states, for food, fuel, materials, and economic power.
Every economic system must sooner or later rely upon some form of the profit motive to stir individuals and groups to productivity.
All economic history is the slow heartbeat of the social organism, a vast systole and diastole of concentrating wealth and compulsive recirculation.

9. Socialism and History
The struggle of socialism against capitalism is part of the historic rhythm in the concentration and dispersion of wealth.
The fear of capitalism has compelled socialism to widen freedom, and the fear of socialism has compelled capitalism to increase equality.

10. Government and History
Does history justify revolutions?
Democracy is the most difficult of all forms of government.
Democracy has done less harm, and more good, than any other form of government. It gave to human existence a zest and camaraderie that outweighed its pitfalls and defects.
If our economy of freedom fails to distribute wealth as ably as it has created it, the road to dictatorship will be open to any man and a martial government will engulf the democratic world.

11. History and War
War is one of the constants of history, and has not diminished with civilization or democracy.
The causes of war are the same as the causes of competition among individuals: acquisitiveness, pugnacity, and pride; the desire for food, land, materials, fuels, mastery.

12. Growth and Decay
Civilization is social order promoting cultural creation.
History repeats itself, but only in outline and in the large.
Civilizations begin, flourish, decline, and disappear.
Civilizations are the generations of the racial soul. As life overrides death with reproduction, so an aging culture hands its patrimony down to its heirs across the years and the seas.

13. Is progress real?
Our progress in science and technique has involved some tincture of evil with god.
We must not demand of progress that it should be continuous or universal.
In the debate between ancients and moderns it is not at all clear that the ancients carry off the prize.
If education is the transmission of civilization, we are unquestionably progressing.
We should not be greatly disturbed by the probability that one civilization will die like any other.
The heritage that we can now more fully transmit is richer than ever before.
History is the creation and recording of that heritage; progress is its increasing abundance, preservation, transmission, and use.