Password store paradigm

The very first thing

We should always remind ourself is that, we should not store passwords yourself. At least, we should try out best to avoid it.

As a User

Password manager and 2FA is strongly suggested. However, it is not the thing I want to discuss today.

As a develop

As a developer, we are unavoidably need to store user’s password.

Storing in plain text

The most naive way is to store user’s password in plain text. Once the database is leaked or have insider, all user’s password is leaked. Sadly, many people in the world are using the same username and password in different website. And thats why we should use password manager as a user.

Encrypt the password

It is a little bit better than store it as plain text. However, it still incredibly easy to get things wrong. Imagine that the database is leaked therefore Hacker have the whole database offline. They can see the encrypted code aka the ciphertext. Under lots of encryption algorithm, same text will generate same ciphertext. If it is a very large database, it most likely have many same password (especially for some easy, common passwords). The scariest part is that, some times the reset password system may also store “hints” of the password. Imagine there are 20 same encrypted password, that means I will have 20 different hints point to a same password.

Hashing (without salts)

hash(m)

Hashing and store the hashed password almost get the things right. However, it still can go wrong with some old hashing algorithm. let me introduce a idea, rainbow table: pre-computed hash chains. Improve on the dictionary attack to trade time for space. It is a common and strong approach to crack hash nowadays. By matching the hashed cipher text and rainbow table, hacker can easily find some of the correct match of password. If the database is compromised. Although it is the intruder who gets the hash value, it is also easy to restore the password plaintext in bulk due to the existence of rainbow tables.

Hashing (with salts)

The rainbow table is generated for a specific function H. If H changes, the existing rainbow table data is completely unusable. If using salt value, then a different rainbow table must be generated for each user. It greatly increases the difficulty of cracking. And the best practice is to use a different salt for each user since it is worth mentioning that, the tensor computing provided by display card to highly speed up the hack cask. Which make it even more danger now and in the future.

A practices that I have implement is make use of the fact that username is usually cannot change. Use username for as the salt.

Upgrading the old method from the past

It is common that we need to upgrade the hashing algorithm form the past but at the same time do not want to affect the user. For plain text, it just need to hash the password. And so is the encryption, it is just need to decrypt the password before hashing.

What if we already have hashed password? The fact that we cannot restore the password because hashing is a many-to-one compression. The solution is salt and pepper.

  • m: message, password in this case
  • h1: the outdated hash algorithm
  • h2: the modern hash algorithm
  • salt: salt is not secret (merely unique) and can be stored alongside the hashed output
  • pepper: pepper is secret and must not be stored with the output.

h2(h1(m)+pepper) , salt is optional in this case. the h1 might have salted already.

hash(m+salt)
it must be safe to ensure that each user’s salt is different.

Manage multiple jdks in macos, M1

First, install jenv by using Homebrew

1
brew install jenv

After that, need to config the zsh

1
2
3
echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(jenv init -)"' >> ~/.zshrc
source ~/.zshrc

It only found the system default Java:

1
jenv versions

Add the jdk you installed to the jenv. Personally my jdks are installed at /Users/klam/Library/Java/JavaVirtualMachines/

For example:

jenv add /Users/klam/Library/Java/JavaVirtualMachines/azul-17.0.3/Contents/Home/

jenv global 17 to swap between different jdk for the default jdk

you can also use jenv local 17 to specifies the Java version of a folder

Spring Boot notes1 - Database and CURD

This notes is the learning process of Spring boot. Follow the https://www.udemy.com/course/spring-hibernate-tutorial/learn/lecture/12940996#overview

Connect to database

in the Resource path, there are a application.properties

input the JDBC properties

1
2
3
4
5
6
#
# JDBC properties

spring.datasource.url=jdbc:mysql://localhost:3306/employee_directory?useSSL=false&serverTimezone=UTC
spring.datasource.username=<username>
spring.datasource.password=<assword>

Create Entity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@Entity
@Table(name="employee")
public class Employee {

// define fields

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;

@Column(name="first_name")
private String firstName;

@Column(name="last_name")
private String lastName;

@Column(name="email")
private String email;


// define constructors

public Employee() {

}

public Employee(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}

//define getter setter toString...
}

Hibernate implementation

Create a interface in src/java/projectname/dao/EmployeeDAO

DAO aka Data Access Object, is the “model” of MVC.

1
2
3
4
5
6
7
8
9
10
11
public interface EmployeeDAO {

public List<Employee> findAll();

public Employee findById(int theId);

public void save(Employee theEmployee);

public void delete(Employee theEmployee);

}

Implementing the interface in src/java/projectname/dao/EmployeeDAOHibernateImpl

@Repository

contains the api to control the database;
-. createQuery(…)

  • .get(…)
  • etc…

@Transactional

transaction is atom unit of the DBMS, Provides a way for database operation sequences to recover from failure to a normal state.
DBMS needs to ensure that all operations in the transaction are completed successfully and the results are permanently stored in the database.
IF some operations in the transaction are not completed successfully, all operations in the transaction need to be rolled back to the state before the transaction has no effect on the database or the execution of other transactions, and all transactions needs to be executed independently.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

// repository contains the api to control the database;
@Repository
public class EmployeeDAOHibernateImpl implements EmployeeDAO {

// define field for entitymanager
private EntityManager entityManager;

// set up constructor injection
@Autowired
public EmployeeDAOHibernateImpl(EntityManager theEntityManager) {
entityManager = theEntityManager;
}


@Override
@Transactional
public List<Employee> findAll() {

// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);

// create a query
Query<Employee> theQuery =
currentSession.createQuery("select e from Employee e", Employee.class);

// execute query and get result list
List<Employee> employees = theQuery.getResultList();

// return the results
return employees;
}

@Override
public Employee findById(int theId) {
Session currentSession = entityManager.unwrap(Session.class);

Employee theEmployee = currentSession.get(Employee.class, theId);
return theEmployee;
}

@Override
public void save(Employee theEmployee) {
Session currentSession = entityManager.unwrap(Session.class);

currentSession.saveOrUpdate(theEmployee);
}

@Override
public void delete(Employee theEmployee) {
Session currentSession = entityManager.unwrap(Session.class);

currentSession.delete(theEmployee);
}

}

Service

Mostly similar to the dao, first create a interface, then implementing the interface.

1
2
3
4
5
6
7
8
9
10
public interface EmployeeService {

public List<Employee> findAll();

public Employee findById(int theId);

public void save(Employee theEmployee);

public void deleteById( int theId);
}
1
2
3
4
5

@Service
public class EmployeeServiceImpl implements EmployeeService {
...
}

Rest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RestController
@RequestMapping("/api")
public class EmployeeRestController {
private EmployeeService employeeService;

@Autowired
public EmployeeRestController(EmployeeService theEmployeeService) {
employeeService = theEmployeeService;
}

@GetMapping("/employees")...
@PostMapping("/employees")...
@GetMapping("/employees/{employeeId}")
@PutMapping("/employees")
@DeleteMapping("/employees/{employeeId}")
...
}

Blockchain key takeaway

Cryptography

  • Symmetric encryption (base on substitution and permutation): a secret key and an encryption algorithm
  • Asymmetric encryption (base on exponential): public key and private key system.
  • Public-key: provide confidentiality(encryption/decryption) and authentication (signature)
  • Both of them are secure and useful in diff scenarios
  • RSA algorithm is based on the difficulty of factoring problem.
  • Hash function can be applied to any sized message and produce fixed length message digest.
  • Sign the message digest instead of the message itself.
    • first hash the message
    • Then encrypt(sign) the hashed value
    • The message usually longer than the key size
  • DSA signature is based on the difficulty of discrete logarithms problem.

AES

permutation (shift rows)

AES key will be expanded(x11)
16bytes -> 176bytes
The chiper consists of N rounds, N depends on the key length:

  • 16bytes: 10rounds
  • 24bytes: 12rounds
  • 14bytes: 14rounds

Certification Authority (CA)

Sign certificate that bind subscriber’s name and his public key.
Indicates that the subscriber has sole control and access to the corresponding private key.

Public Key Infarstructure (PKI)

A set of policy, processes, server platforms, software etc…
to administer certificates

  • issue
  • maintain
  • revoke

Bitcoin

  • Merkle Tree Root is public for Verification
  • Merkle Tree Root for txs, and store in the block header
  • non-singular elliptic curve is the set of points and the point at infinity O
  • The point at infinity O is the identity elements
  • Bitcoin use Mudulo p - secp256k1, ECDSA

Bitcoin structure

Header:

  • Version Number
  • Hash of prev block header (by SHA256 double hash)
  • Hash of Transactions(merkle tree)
  • timestamp
  • Threshold(difficulty)
  • Nonce any value

Body:

  • Number of TXs
  • Coinbase
  • Regulars etc

Hash function Requirment

  • Easy to compute but diffcult to invert
  • Collision resistant

New diffculty caluate

Bitcoin create once every 10 minutes
Update the diffculty every 2016 blocks
T-new = T-sum/(2016*10*60) * T

Simple Payment Verification Node (SPV)

only stores the block header, contact full nodes when information needed.

Mining

read my code

Probability that the block hash falls below the target threshold T:
p= T+1/2^256

Lock Time

>= 510^8, it is a Unix time
< 5
10^8, it is a block blockHeight

  • Bitcoin prevents double spending(verifty every single node) and tampering(unless 51%)
  • Mining difficulty adjucted to regulate coin supply
  • Bitcoin address are shared over the internet

ETH

Account based model instead of UTXO. Main a global state to record the account balance

Accounts in ETH

Externally owned Accounts(EOA)

  • Controlled by private key
  • Has an Ether balance
  • no code

Contract Accounts

  • Has balance
  • Has code (smart contract)
  • has own permanent state

ETH Contact Transaction

  1. Create new contract
  2. Message the contract to execute it

Gas fee, Gas limit

Gas fee is the price per gas unit. Different operation cost different unit of gas.
Gas limit is the most you are willing to paid. The remainer will refund

ETH storage management - Radix Trie and Patricia Trie

—— Skip ——

  • State Trie
  • Transaction Trie
  • Receipts Trie

ETH consensus - simpler GHOST

Uncle Block: floked block. Give reward to honest but unlucky minor.

intrinsic reward = 5

If include a uncle block, minor can get extra 1/32 intrinsic reward.
Uncle can get depands on block height
(Uncle + 8 - block that include uncle)* intrinsic reward/8

Incentive: reward unluck but honest miners. Make it more fair.

Solidity simplest form notes

  • require The require function call defines conditions that reverts all changes if not met
  • emit an event after successful money transfer

Token

can be programmed to provide different functions

Initial Coin Offering (ICO)

raise funds for a company to create a new coins. similar to IPO

Consensus

PoW

  • the longest chain wins
  • the one growing fastest will be the longest and most trustworthy
  • take a lot of time to generate a block
  • if too easy, the chain can be DDoS attack
  • Huge Energy Consumption

PoS

  • creator of a block chosen in a random way, depending on the user’s wealth
  • In order to validate, forger must first put their own coin at “stake”.
  • When folk, pos vote

Randomized Block Selection

randomizaion to generate the following forger. Not true random in computer world. So is usually able to predict which user will be selected to forge the next block.

Coin Age Based selection

coin age = time * amount

Target * CoinAge = the hash difficulty.

To join the PoS, you might load your coins to other or join the pool youself.

Nothing at stake

when folk, vote for both because it gains most benefits. Always win, nothing to lose.
The blockchain might never reach Consensus
Use casper: punish

DPoS Delegated Proof of stake

vote to elect witnesses
21-100 elected witnesses in a DPoS. time slots are given to each witness to publish their block.
Longest chain wins
Much faster than POW and POS

Byzantine Fault Torlerance

  1. Commander -> all traitor
  2. traitor boardcast -> other traitor
  3. consensus

Consensus if at least 3m+1 nodes can achieve consensus. M is malicious nodes

Oral Message

  1. All messages are delivered correctly
  2. Know who this message is from
  3. Missing messages can be detected

Permissioned Blockchain

  • Regulation
  • Complete control of their data
  • Can be fully centralizated. Members negotiate.

Membership Service Providers (MSPs)

PKI and CA

Endorsement and validation policy can be adjusted as need.

  1. Client -> Endorser (proposal)
  2. Endorser check the certificate and others to validate the transactions
  3. Executes the chaincode
  4. Enderser -> Client
  5. Client -> Orderer
  6. Orderer include the transaction and generate blocks
  7. Orderer -> Anchor
  8. Anchor -> boardcast the block
  9. Peer verify the new block
  10. Peer -> Client

Channel

Maintan a Ledger, only nodes in channel can access this ledger.

Collection

The data on the chain can be said to be “permanent” and “public” to be shared among the participants. However, in the real application scenario, many data are not “publicly” stored in the blockchain due to privacy.
Only the header is stored on chain for verification.

Config wireguard with csf

Config wireguard with csf

csfpre.sh

CSF blocks Wireguard traffic, so we need to add some rules to iptables. Here are the instructions on how to do it.

Create a csfpre.sh file in the CSF path, for example, /etc/csf/csfpre.sh.
csfpre.sh adds iptable rules to CSF before it launches.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
# iptables -A INPUT -p all -m set --match-set hkip src -j ACCEPT

iptables -A INPUT -i wg0 -j ACCEPT
iptables -A OUTPUT -o wg0 -j ACCEPT
iptables -A FORWARD -i wg0 -o ens3 -j ACCEPT
iptables -A FORWARD -i ens3 -o wg0 -j ACCEPT
iptables -t nat -A POSTROUTING -s 10.7.0.2/24 -o ens3 -j MASQUERADE

# For ipv6, opional
ip6tables -A INPUT -i wg0 -j ACCEPT
ip6tables -A OUTPUT -o wg0 -j ACCEPT
ip6tables -A FORWARD -i wg0 -o ens3 -j ACCEPT
ip6tables -A FORWARD -i ens3 -o wg0 -j ACCEPT
ip6tables -t nat -A POSTROUTING -s fddd:2c4:2c4:2c4::2/64 -o ens3 -j MASQUERADE

en3 is your network interface
10.7.0.2/24 and fddd:2c4:2c4:2c4::2/64 is your wireguard internal ip.

Don’t forget to give permission to the script: chmod +x /etc/csf/csfpre.sh.

Finally, run:

csf -ra

wg0 configuration

add the follow line to the wg0.conf

1
2
PostUp = iptables -w -t nat -A POSTROUTING -o ens3 -j MASQUERADE; ip6tables -w -t nat -A POSTROUTING -o ens3 -j MASQUERADE
PostDown = iptables -w -t nat -D POSTROUTING -o ens3 -j MASQUERADE; ip6tables -w -t nat -D POSTROUTING -o ens3 -j MASQUERADE

Bitcoin implementation in typescript

Introduction

I am responsible for the transaction part in a group project about blockchain and bitcoin, and here is my code. Just for archive.

library

Bitcoin is using elliptic and secp256k1

1
2
3
4
import { SHA256 } from 'crypto-js';

var EC = require('elliptic').ec;
var ec = new EC('secp256k1');
1
2
3
4
5
6
7
8
9
10
11
12
export class Signature {
static sign(priKey: string, msg: string): string {
const key = ec.keyFromPrivate(priKey, 'hex');
const signature = key.sign(msg).toDER();
return signature;
}

static verify(pubKey: string, sig: string, msg: string): boolean {
const key = ec.keyFromPublic(pubKey, 'hex');
return key.verify(msg, sig);
}
}

Class in a Transaction

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

export class RegularTxIn extends TxIn {
txOutId: string;
txOutIndex: number;
signature: string;

constructor(txOutId: string, txOutIndex: number, priKey) {
super();
this.txOutId = txOutId;
this.txOutIndex = txOutIndex;
this.signature = this.createSig(priKey, this.msgHash());
}

createSig(priKey: string, msg: string): string {
return Signature.sign(priKey, msg);
}

msgHash(): string {
return SHA256(SHA256(this.txOutId + this.txOutIndex)).toString();
}
}

export class CoinbaseTxIn extends TxIn {
public blockHeight: number;

constructor(blockHeight: number) {
super();
this.blockHeight = blockHeight;
}
}

export class RegularTxIn extends TxIn {
txOutId: string;
txOutIndex: number;
signature: string;

constructor(txOutId: string, txOutIndex: number, priKey) {
super();
this.txOutId = txOutId;
this.txOutIndex = txOutIndex;
this.signature = this.createSig(priKey, this.msgHash());
}

createSig(priKey: string, msg: string): string {
return Signature.sign(priKey, msg);
}

msgHash(): string {
return SHA256(SHA256(this.txOutId + this.txOutIndex)).toString();
}
}

export class CoinbaseTxIn extends TxIn {
public blockHeight: number;

constructor(blockHeight: number) {
super();
this.blockHeight = blockHeight;
}
}

export class TxOut {
address: string; //public key
amount: number;

constructor(address: string, amount: number) {
this.address = address;
this.amount = amount;
}
}

export class UTXO {
txId: string;
txOut: TxOut;
txIndex: number;

constructor(txId: string, txOut: TxOut, txIndex: number) {
this.txId = txId;
this.txOut = txOut;
this.txIndex = txIndex;
}
}

Transaction Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
export class Transaction {
type: string;
id: string;
txIns: TxIn[];
txOuts: TxOut[];

constructor(ins: TxIn[], outs: TxOut[]) {
this.txIns = ins;
this.txOuts = outs;
this.id = this.setId();
}

setId(): string {
let txInContent: string;
if (this instanceof RegularTx) {
txInContent = this.txIns
.map((regularTxIn: RegularTxIn) => regularTxIn.txOutId + regularTxIn.txOutIndex)
.reduce((a, b) => a + b, '');
} else {
txInContent = this.txIns
.map((coinbaseTxIn: CoinbaseTxIn) => coinbaseTxIn.blockHeight)
.reduce((a, b) => a + b, '');
}

const txOutContent: string = this.txOuts
.map((txOuts: TxOut) => txOuts.address + txOuts.amount)
.reduce((a, b) => a + b, '');

return SHA256(SHA256(txInContent + txOutContent)).toString();
}

public static createRegularTx(
senderPubKey: string,
senderPriKey: string,
receiverPubKey: string,
receiveAmount: number,
fee: number,
) {
const utxo = this.findUTXO(senderPubKey);
let sumUTXO = 0;
const txIns = [];
const txOuts = [];
let i = 0;
utxo.forEach((val) => {
//the sum of UTXO of a pubkey
sumUTXO += val.amount;
// Create input object for each UTXO, sign the input by user private key
i++;
txIns.push(new RegularTxIn(val.id, i, senderPriKey));
});
const totalAmountToSpend = receiveAmount + fee;
if (sumUTXO < totalAmountToSpend) {
// Not enough money
return; //exception
}
for (let n = 0; n < txIns.length; n++) {
// verify the input by signature
const checker = Signature.verify(utxo[i].address, txIns[i].signature, txIns[i].msgHash());
if (!checker) {
return; //exception
}
}
//Create out put to receiver by PP2K
txOuts.push(new TxOut(receiverPubKey, receiveAmount));
//return change to the sender
const change = sumUTXO - receiveAmount - fee;
if (change > 0) {
txOuts.push(new TxOut(senderPubKey, change));
}
const tx = new Transaction(txIns, txOuts);
// tx.setId()
return tx;
}

public static findUTXO(senderPubKey) {
const allBlock = [];
const allTxOut = [];
const allTxIn = [];
allBlock.forEach((block) => {
const txs = block.txs;
txs.forEach((tx) => {
const txOuts = tx.txOuts;
txOuts.forEach((out) => {
if (out.address == senderPubKey) {
allTxOut.push(out);
}
});
});
});
return [];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export class RegularTx extends Transaction {
type: 'regular';
txIns: RegularTxIn[];

constructor(ins: RegularTxIn[], outs: TxOut[]) {
super(ins, outs);
}
}

export class CoinBaseTx extends Transaction {
type: 'coinbase';
txIns: CoinbaseTxIn[];

constructor(ins: CoinbaseTxIn, outs: TxOut[]) {
super([ins], outs);
}
}

Create Transaction and UTXO

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
public async createTx(
senderPubKey: string,
senderPriKey: string,
receiverPubKey: string,
receiveAmount: number,
fee: number,
) {
const utxos = await this.getUXTO(senderPubKey);
let sumUTXO = 0;

const txIns = utxos.map((tx) => {
sumUTXO += tx.txOut.amount;
return new RegularTxIn(tx.txId, tx.txIndex, senderPriKey);
});

const txOuts = [];

const totalAmountToSpend = receiveAmount + fee;

if (sumUTXO < totalAmountToSpend) {
// Not enough money
throw new Error('Insufficient Balance'); //exception
}

for (let i = 0; i < txIns.length; i++) {
// verify the input by signature
// TODO: check if utxos[i].txOut.address is correct or not
const checker = Signature.verify(utxos[i].txOut.address, txIns[i].signature, txIns[i].msgHash());

if (!checker) {
throw new Error('Invalid txIns'); //exception
}
}

//Create out put to receiver by PP2K
txOuts.push(new TxOut(receiverPubKey, receiveAmount));
//return change to the sender
const change = sumUTXO - receiveAmount - fee;
txOuts.push(new TxOut(senderPubKey, change));

const tx = new RegularTx(txIns, txOuts);
tx.setId();

this.broadcast(tx);
await this.transactionPoolService.addTransaction(tx);

return tx;
}

public async getAllUTXO(): Promise<UTXO[]> {
const outs: UTXO[] = [];
// loop all the blocks
for (let i = 0; i < this.blockService.getBlockHeight(); i++) {
const currentBlockHash = this.blockService.getBlockHash(i);
const currentBlock = await this.blockService.getBlock(currentBlockHash);
const currentTx = currentBlock.data.transactions; // need to convert to list of Transaction

// loop all the transaction
currentTx.forEach((currentTx) => {
const txID = currentTx.id;
const txOuts = currentTx.txOuts;
const txIns = currentTx.txIns;

// Create UTXO object for each TxOutPut, push to UTXO
txOuts.forEach((txOut, i) => {
outs.push(new UTXO(txID, txOut, i)); // create UTXO obj that store tx, txid and index
});

// Remove the spent money
txIns.forEach((tx) => {
if (tx instanceof RegularTxIn) {
const outID = tx.txOutId;
const outIndex = tx.txOutIndex;
const indexOfTx = outs.findIndex((obj) => {
return obj.txId == outID && obj.txIndex == outIndex;
});

if (indexOfTx >= 0) {
outs.splice(indexOfTx, 1);
}
}
});
});
}
return outs;
}

public async getUXTO(pubKey: string): Promise<UTXO[]> {
const allUtxo = await this.getAllUTXO();

return allUtxo.filter((tx) => {
return tx.txOut.address === pubKey;
});
}


IT Auditing notes 2

Operation Control

Segregation of Duties

Avoid single person could be responsible for diverse and critical functions. Otherwise, error or misappropriation could occur and not be detected in a timely manner and in normal course of business processes.

Incident handling

identify when where whole

Shadow IT: IT users at an organisation electing to use tools and services that have not been officially sanctioned by said organisation.

  • Converage - insurance?
  • Action - what to do?
  • Evidence
  • Tasks to do during recovery

Management of removable media and system documentation

Monitoring

  • audit logging
  • Clock Synchronize

Logical Controls

Concurrent Sign-on Session

can be very useful, but also a control weaknesses

Suggestion:

  • No or only few user can have concurrent
  • No more than two
  • Logged and reviewed

Remote access Control

  • Deducated leased liveness
  • VPN
  1. Identification process (username?)
  2. Authentication process (password?)
  3. Permitted/denied

Input Control

source document design - arrange fields for ease of use.

Software development Control

  • Business realization: 個system點幫到公司
  • project management
    • Cost and resource/ Deliverable/Time(Duration)
  • System development approach SDLC approaches
    • SDLC: 流水線

IT Auditing notes 1

The structure of an IT Audit

Phase 1 - Audit Planning Phase

In this phase, auditor review controls such as General Controls and application controls. After that, plan tests of controls and substantive testing procedures.

Phase 2 - Test of Control

Perform tests of control -> Evaluate Test result -> Determine degree of reliance on controls.

Phase 3 - Substantive Testing Phase

Perform Substantive Tests -> Evaluate Result -> issue audit report

PDC Control Models

Preventive 預防

Detective 監察

Corrective 執屎

Internal Control Activities

  • Independent verification
  • Transaction Authorization
  • Segregation of duties
  • Supervision
  • Audit trail provision

Physical Control

Provision of a secure area - Security perimeter

Prevent unauthorized access

  • Physical lock : Conventional keys/Electronic access badge system/cipher lock
  • Selection and design of secure areas
  • intruder detection system(Camera)
  • Sperate from 3rd party area and public area detection
  • backup
  • loading area

backup

  • Full backup
  • Incremental backup
    • Cumulative incremental: Since last full backup
    • Differentail incremental: Since last backup(any type)

Resumption programs

Hot Site - full equipped and can be operational in less than 24 hours
Cold site -
Partner with other companies

Risk Analysis

Step 1 - identify Threats and Risks

  • Threat Agents: 觸發threats既人or物 fire/hacker/employee/…
  • Weaknesses: 弱點
  • Risks: weaknesses引致既後果

Step 2 - Quantify Impact of potential Threats

Single Loss Expectancy(SLE) + Annualized frequency = Annual Loss Expectancy(ALE)

Select a counter measurement

Cost/benefits calculation:

ALE before implementing safety measure - ALE after implenting safety measure - annual cost of safeguard = value of safefuard to the company

Javascript callback promise await/async

I have been coding in JavaScript for a while now, but I realized that I didn’t have a solid understanding of how the language works. This was a surprising realization, considering how much time I spend working with it. So, to improve my skills, I decided to do some research and dive deeper into the workings of JavaScript.

JavaScript is a programming language designed to run on client-side browsers. In this context, everything related to the internet is unpredictable. For example, if an image is too large, the browser can get stuck, and that’s where callback functions come in.

A callback function is a function that’s passed as an argument to another function. It’s used to execute code asynchronously, which means that the program doesn’t stop until the function is executed entirely. The concept of a callback is that we put the functions that need time to run into a “Callback Queue” and continue running the following code. This allows us to avoid blocking the program while it waits for the function to finish running.

Another useful feature of JavaScript is the Promise object. A promise is an object that includes a resolve and reject function. The resolve function is called when the code runs successfully, while the reject function is called when the code throws an error. We use try-catch blocks to handle errors in promises.

Async/Await is another feature of JavaScript that’s used for clean code. The await keyword is used in the async function to pause the function until the Promise is resolved or rejected. We can use this feature to write asynchronous code that looks like synchronous code, which makes the code easier to read and understand.

In summary, JavaScript is a powerful language that’s essential for web development. Understanding its features, including callback functions, Promises, and Async/Await, is crucial for writing efficient and clean code.

Callback

The concept of callback is that, we put the functions that needs time to run into a “Callback Queue”, and continue run the following code.

Promise

Promise is object that include resolve and reject, for example,

1
2
3
4
5
6
7
8
9
10
11
12
13
let p = new Promise(function(resolve, reject) {
if(){
resolve();
}else{
reject;
}
})

p.then(function(){
// resolve
}).catch(function() {
// return a exception, and catch the error
})

Async Await

The await must be in the async function

1
2
3
4
5
6
7
8
9
async function getSomething(){
try{
let something = await fetch(url);
console.log(something)
}
catch( exception ){
console.log(exception)
}
}

Async await is usually the better for clean code.

Information Security Notes 7 Wireless LAN Security

Wireless LAN configuration

  • User Mudule (UM)
  • Control Module (CM)
  • Ad Hoc WLAN(without control Mudule)
    • Without communicate with their neighbors directly

IEEE 802 Architecture

  • Physical Layer (PHY)
    • encoding/decoding of signals
  • Media Access Control (MAC)
    • Controlling access to the transmission medium is needed to provide an orderly and efficient use of the network transmission capacity
  • Logical Link Control (LLC)
    • Keep track of which frames

IEEE 802.11 Architecture

802.11 is the Wi-Fi(Wireless Fidelity) Alliance

  • Basic Service Set (BSS)
  • Extended Service Set (ESS)
    • SSID: Service Set Identifier, name of the wifi
  • Independent BSS

802.11 Access Control

  • Reliable Data Delivery
    • Wireless channels are useally unreliable
    • Mechanism is developed for error detection and contention
  • Access Control
    • For deciding which station can send
  • Security
    • Make sure the configentiality and data integrity
    • Disallowing unauthorized station to connect to the network

Threads in Wireless LANs

  • Eavesdropping
    • Due to the broadcast nature of radio communications
    • Signals can be received by any receiver within some transmission range
  • No Physical Protection
    • No physical cables

Protocol of Wireless Security

WEP Wired Equivalent Privacy

The purpose of WEP:

  • Authentication
  • Data confidentiality

Problem of WEP:
WEP is publiced at 1997 and design flawed at 2000
Authentication flaws:

  • auth in WEP is not mutual. AP does not auth itself to clients
  • Auth and encryption use the same secret key
  • Auth only at the time tries to connect to the network. After Auth, everyone can spoofing its MAC address

WPA, WPA2, WPA3 - Wifi Protected Access

New security architecture 802.11i designed to replace WEP during 2003-2004
WPA2/3 should be used

  • WPA
    • intermediate solution which can be implemented by updating the firmware of existing APs
  • WPA2
    • Long term solution
  • WPA3
    • Next generation, all WIFI6 certified routers are required to implement
  1. Phase 1: Discovery
    Discovery phase allows an STA and AP recognize each other
  2. Phase 2: Authentication
  • Only authorized STAs can use the network
  • STA is assured that the network is legitimate
    Extensible Authentication Protocol(EAP) is used
  1. Phase 3: Key Management Phase
  • Pairwise keys used for communication between an STA and an AP
  • Group keys used for multicast communication
  1. Phase 4: Protected Data Transfer Phase
  • TKIP

    • for WPA: Temporal Key Integrity Protocol
    • allows old device update firmware
    • 64-bit message to replace the CRC code
    • Still use RC4 encryption algorithm
  • AES-CCMP

    • for WPA2: Counter mode-CBC MAC protocol
    • Design for new hardware
    • Cipher-block-chaining message Authentication code to provide data integrity
    • AES algorithm for encryption
EAP

Three roles of EAP

  1. Supplicant: STA
  2. Authenticator: AP
  3. Authentication server(AS): a separate device or the AP

Sub-phases:
Connect to AS -> EAP exchange -> Secure key delivery(AS generates a master session key and sends it to STA)