stateful firewall with inbound outbound traffic


I have worked as Devops for cloud migration in the recent 3 months without really writing much code. Even though being exposed to many AWS services like EMR/EC2/ASG(auto scaling group)/LC(launch config)/CF(cloud formation) etc.. with the need of setting up security groups(SG), i find myself still a bit confusing with inbound and outbound traffic rules. Was wondering if i allow inbound traffic, i have to send response back to client which means i have to allow outbound traffic? Did some google search with the question and get the keyword stateful firewall.

So basically with a stateful firewall, when a connection is established, the firewall will automatically let packets out back to the client’s port. You don’t need to create rules for that because the firewall knows.


Before the development of stateful firewalls, firewalls were stateless. A stateless firewall treats each network frame or packet individually. Such packet filters operate at the OSI Network Layer (layer 3) and function more efficiently because they only look at the header part of a packet.They do not keep track of the packet context such as the nature of the traffic. Such a firewall has no way of knowing if any given packet is part of an existing connection, is trying to establish a new connection, or is just a rogue packet. Modern firewalls are connection-aware (or state-aware), offering network administrators finer-grained control of network traffic.

Early attempts at producing firewalls operated at the application layer, which is the very top of the seven-layer OSI model. This method required exorbitant amounts of computing power and is not commonly used in modern implementations.


A stateful firewall keeps track of the state of network connections (such as TCP streams or UDP communication) and is able to hold significant attributes of each connection in memory. These attributes are collectively known as the state of the connection, and may include such details as the IP addresses and ports involved in the connection and the sequence numbers of the packets traversing the connection. Stateful inspection monitors incoming and outgoing packets over time, as well as the state of the connection, and stores the data in dynamic state tables. This cumulative data is evaluated, so that filtering decisions would not only be based on administrator-defined rules, but also on context that has been built by previous connections as well as previous packets belonging to the same connection.

The most CPU intensive checking is performed at the time of setup of the connection. Entries are created only for TCP connections or UDP streams that satisfy a defined security policy. After that, all packets (for that session) are processed rapidly because it is simple and fast to determine whether it belongs to an existing, pre-screened session. Packets associated with these sessions are permitted to pass through the firewall. Sessions that do not match any policy are denied, as packets that do not match an existing table entry.

In order to prevent the state table from filling up, sessions will time out if no traffic has passed for a certain period. These stale connections are removed from the state table. Many applications therefore send keepalive messages periodically in order to stop a firewall from dropping the connection during periods of no user-activity, though some firewalls can be instructed to send these messages for applications.

Depending on the connection protocol, maintaining a connection’s state is more or less complex for the firewall. For example, TCP is inherently a stateful protocol as connections are established with a three-way handshake (“SYN, SYN-ACK, ACK”) and ended with a “FIN, ACK” exchange. This means that all packets with “SYN” in their header received by the firewall are interpreted to open new connections. If the service requested by the client is available on the server, it will respond with a “SYN-ACK” packet which the firewall will also track. Once the firewall receives the client’s “ACK” response, it transfers the connection to the “ESTABLISHED” state as the connection has been authenticated bidirectionally. This allows tracking of future packets through the established connection. Simultaneously, the firewall drops all packets which are not associated with an existing connection recorded in its state table (or “SYN” packets), preventing unsolicited connections with the protected machine by black hat hacking.

By keeping track of the connection state, stateful firewalls provide added efficiency in terms of packet inspection. This is because for existing connections the firewall need only check the state table, instead of checking the packet against the firewall’s rule set, which can be extensive. Additionally, in the case of a match with the state table, the firewall does not need to perform deep packet inspection.

DNS原理以及A/NS Record Cname

阮一峰 老师的一篇关于DNS的好博客,尤其喜欢里面对于分级查询以及A-Record, NS-Record, CNAME的解释, 简单明了, 所以转载了这一部分如下:







根域名的下一级,叫做”顶级域名”(top-level domain,缩写为TLD),比如;再下一级叫做”次级域名”(second-level domain,缩写为SLD),比如http://www.example.com里面的.example,这一级域名是用户可以注册的;再下一级是主机名(host),比如http://www.example.com里面的www,又称为”三级域名”,这是用户在自己的域里面为服务器分配的名称,是用户可以任意分配的。



# 即






  1. 从”根域名服务器”查到”顶级域名服务器”的NS记录和A记录(IP地址)
  2. 从”顶级域名服务器”查到”次级域名服务器”的NS记录和A记录(IP地址)
  3. 从”次级域名服务器”查出”主机名”的IP地址








$ dig +trace









七、NS 记录的查询


$ dig ns com
$ dig ns


$ dig +short ns com
$ dig +short ns




(1) A:地址记录(Address),返回域名指向的IP地址。

(2) NS:域名服务器记录(Name Server),返回保存下一级域名信息的服务器地址。该记录只能设置为域名,不能设置为IP地址。

(3)MX:邮件记录(Mail eXchange),返回接收电子邮件的服务器地址。

(4)CNAME:规范名称记录(Canonical Name),返回另一个域名,即当前查询的域名是另一个域名的跳转,详见下文。

(5)PTR:逆向查询记录(Pointer Record),只用于从IP地址查询域名,详见下文。



$ dig


;; ANSWER SECTION: 3370    IN  CNAME  600 IN  A




$ dig -x






$ dig a
$ dig ns
$ dig mx

bcrypt 加密算法

The prefix “$2a$” or “$2b$” (or “$2y$”) in a hash string in a shadow password file indicates that hash string is a bcrypt hash in modular crypt format.[3] The rest of the hash string includes the cost parameter, a 128-bit salt (base-64 encoded as 22 characters), and B184 bits of the resulting hash value (base-64 encoded as 31 characters).[4] The cost

Bcrypt basic

parameter specifies a key expansion iteration count as a power of two, which is an input to the crypt algorithm.

For example, the shadow password record :


specifies a cost parameter of 10, indicating 210 key expansion rounds. The salt is N9qo8uLOickgx2ZMRZoMye and the resulting hash is IjZAgcfl7p92ldGxad68LJZdL17lhWy. Per standard practice, the user’s password itself is not stored.



Bcrypt  vs Hash+salt

Both Bcrypt and hash+salt could prevent rainbow-table attack(which made the MD5 very vulnerable). In the Hash world, SHA(4 flavors) is better than MD5 in that it almost does not have collisions(collision is one of import reason MD5 is not secure since it is quite easy to generate collision in MD5).

Speed wise, bcrypt is ms level which is kind of slow if you have a lot of user login concurrently. hash+salt will be much faster though less secure.


如何生成安全的密码 Hash:MD5, SHA, PBKDF2, BCrypt 示例

2015 in review

The stats helper monkeys prepared a 2015 annual report for this blog.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 31,000 times in 2015. If it were a concert at Sydney Opera House, it would take about 11 sold-out performances for that many people to see it.

Click here to see the complete report.

Create an alias for your gmail without creating a new account

When I apply my google account, I did not include my name in the user name. In some scenarios this might be not easy for others to recognize my email address like for example in the church’s mailing list. However I donot want another gmail account since it is too much to manage 2 email account. So the alias comes into play:

There are at least two ways you can modify your Gmail address and still get your mail. You can set up filters to automatically direct received messages to Trash, apply a label or star, skip the Inbox, or forward to another email account.

1) Plus-addressing

Gmail supports plus-addressing of emails. Messages can be sent to addresses in the where extratext can be any string. Plus-addressing allows users to sign up for different services with different aliases and then easily filter all e-mails from those services. It does not appear, however, that the +string feature works when sending email from a gmail account to itself. Additionally (in some cases) the string appended to the e-mail address may not be longer than six characters.

For example, if your name was, you could send mail or

The plus (“+”) sign is not simply a Gmail feature, but one of the valid characters in email addresses as specified by RFC-5233 ( Although it’s true that many email validation tools don’t take this into account.

Here is the step-by-step instruction on how to filter incoming emails using Gmail plus-addressing:

2) Dot within username

Gmail doesn’t recognize dots (“.”) as characters within usernames, you can add or remove the dots from a Gmail address without changing the actual destination address; they’ll all go to your inbox, and only yours. In short: = = =

All these addresses belong to the same person. You can see this if you try to sign in with your username, but adding or removing a dot from it. You’ll still go to your account.

git pull fetch merge


In the simplest terms, git pull does a git fetch followed by a git merge.

You can do a git fetch at any time to update your remote-tracking branches under refs/remotes/<remote>/. This operation never changes any of your own local branches under refs/heads, and is safe to do without changing your working copy. I have even heard of people running git fetch periodically in a cron job in the background (although I wouldn’t recommend doing this).

A git pull is what you would do to bring a local branch up-to-date with its remote version, while also updating your other remote-tracking branches.

Git documentation: git pull


It is important to contrast the design philosophy of git with the philosophy of a more traditional source control tool like svn.

Subversion was designed and built with a client/server model. There is a single repository that is the server, and several clients can fetch code from the server, work on it, then commit it back to the server. The assumption is that the client can always contact the server when it needs to perform an operation.

Git was designed to support a more distributed model with no need for a central repository (though you can certainly use one if you like.) Also git was designed so that the client and the “server” don’t need to be online at the same time. Git was designed so that people on an unreliable link could exchange code via email, even. It is possible to work completely disconnected and burn a CD to exchange code via git.

In order to support this model git maintains a local repository with your code and also an additional local repository that mirrors the state of the remote repository. By keeping a copy of the remote repository locally, git can figure out the changes needed even when the remote repository is not reachable. Later when you need to send the changes to someone else, git can transfer them as a set of changes from a point in time known to the remote repository.

  • git fetch is the command that says “bring my local copy of the remote repository up to date.”
  • git pull says “bring the changes in the remote repository where I keep my own code.”

Normally “git pull” does this by doing a “git fetch” to bring the local copy of the remote repository up to date, and then merging the changes into your own code repository and possibly your working copy.

The take away is to keep in mind that there are often at least three copies of a project on your workstation. One copy is your own repository with your own commit history. The second copy is your working copy where you are editing and building. The third copy is your local “cached” copy of a remote repository.

A good article on Aha! Moments When Learning Git

Security Stocks Bond Equities Shares 区别


An instrument representing ownership (stocks), a debt agreement (bonds) or the rights to ownership (derivatives).

A security is essentially a contract that can be assigned a value and traded. Examples of a security include a note, stock, preferred share, bond, debenture, option, future, swap, right, warrant, or virtually any other financial asset.

Securities are traditionally divided into debt securities and equities:

(1)Debt securities may be called debentures, bonds, deposits, notes or commercial paper depending on their maturity and certain other characteristics. The holder of a debt security is typically entitled to the payment of principal and interest, together with other contractual rights under the terms of the issue, such as the right to receive certain information.

(2)An equity security is a share in the capital stock of a company. The holder of an equity is a shareholder, owning a share, or fractional part of the issuer. Unlike debt securities, which typically require regular payments (interest) to the holder, equity securities are not entitled to any payment. In bankruptcy, they share only in the residual interest of the issuer after all obligations have been paid out to creditors.







In finance, a bond is a debt security, in which the authorized issuer owes the holders a debt and, depending on the terms of the bond, is obliged to pay interest (the coupon) and/or to repay the principal at a later date, termed maturity. It is a formal contract to repay borrowed money with interest at fixed intervals.

Thus a bond is like a loan: the issuer is the borrower, the bond holder is the lender, and the coupon is the interest. Bonds provide the borrower with external funds to finance long-term investments, or, in the case of government bonds, to finance current expenditure. Certificates of deposit (CDs) or commercial paper are considered to be money market instruments and not bonds.

Bonds and stocks are both securities, but the major difference between the two is that stock-holders are the owners of the company (i.e., they have an equity stake), whereas bond holders are lenders to the issuers. Another difference is that bonds usually have a defined term, or maturity, after which the bond is redeemed, whereas stocks may be outstanding indefinitely. An exception is a consol bond, which is a perpetuity (i.e., bond with no maturity).



It’s type of security that signifies ownership in a corporation and represents a claim on part of the corporation’s assets and earnings.

There are two main types of stock: common and preferred. Common stock usually entitles the owner to vote at shareholders’ meetings and to receive dividends. Preferred stock generally does not have voting rights, but has a higher claim on assets and earnings than the common shares. For example, owners of preferred stock receive dividends before common shareholders and have priority in the event that a company goes bankrupt and is liquidated.

Also known as “shares” or “equity”.

Thus, a holder of stock (a shareholder) has a claim to a part of the corporation’s assets and earnings. In other words, a shareholder is an owner of a company. Ownership is determined by the number of shares a person owns relative to the number of outstanding shares. For example, if a company has 1,000 shares of stock outstanding and one person owns 100 shares, that person would own and have claim to 10% of the company’s assets.


A unit of ownership interest in a corporation or financial asset. While owning shares in a business does not mean that the shareholder has direct control over the business’s day-to-day operations, being a shareholder does entitle the possessor to an equal distribution in any profits, if any are declared in the form of dividends. The two main types of shares are common shares and preferred shares.

Stock 是股票(证劵)的统称。

I own stocks. (我拥有股票)

I have ten stocks in my portfolio. (我的投资组合内有十只股票)

Microsoft’s stock hits a recent high. (微软的股票达到近来的高位)

Share 是一股股票,每一股有一个投票权

I own a share of Microsoft. (我拥有一股微软)

I own two hundred shares of Microsoft. (我有二百股微软)

I own two hundred shares of Microsoft’s stock. (我有二百股微软的股票)

Some stocks are divided into A, B, and C shares. (有些股票分为A/B/C股)


In terms of investment strategies, equity (stocks) is one of the principal asset classes. The other two are fixed-income (bonds) and cash/cash-equivalents. These are used in asset allocation planning to structure a desired risk and return profile for an investor’s portfolio.

In finance, in general, you can think of equity as ownership in any asset after all debts associated with that asset are paid off. For example, a car or house with no outstanding debt is considered the owner’s equity because he or she can readily sell the item for cash. Stocks are equity because they represent ownership in a company.