Ethereum supports RPC mode, which allows an Ethereum account to automate certain operations, such as transferring coins from a mining pool to a wallet. Attackers mainly use RPC to open ports, so they can be protected by limiting RPC ports.
I. Analysis of main means of attack:
- 1. Batch scan common open RPC ports such as port 8545 or port 18545
- 2. After an open port is detected, run the eth. GetBlockByNumber command (querying block height), eth. Accounts command (querying wallet address), and eth.
- 3. Keep trying to send the eth. SendTransaction command, which if effective will transfer the balance in the wallet to the attacker’s wallet. Some people ask, how can a hacker get around a key when a transfer requires a key?
It turns out that Ethereum accounts support the unlockAccount command, which is provided to facilitate certain mechanized transactions. In token trading, some people use computers to do high-frequency trading to capture volatile spreads. (The same is true of stocks, sometimes bought and sold dozens of times a minute.) Ethereum in HFT (or mine pool autopay) can be set to password-free for a specified period of time. If a hacker sends a “balance transfer” order within that time, the Ethereum account (wallet or Web account) will automatically perform the operation, transferring the ethereum from the wallet to the hacker wallet.
I have been attacked in both my private and public ethereum chains. I hope you can pay attention to this.
How should users prevent such attacks?
2.1 Port Restrictions
-
1. Change the default RPC API port, such as –rpcport 18545 or –wsport 18546; If docker container is used to deploy the node, the port can be modified when the container starts port mapping (port scanning cannot take effect).
-
2. Change the LISTENING address of RPC API to a fixed IP address or network segment as follows: — rpcADDR 192.168.1.100 or — wsADDR 192.168.1.100, — rpcADDR 192.168.1.100/24 or — wsADDR 192.168.1.100/24
Note: rpcADDR: http-RPC server listening address, wsADDR: Websocket server listening address
Note: This method applies IP restrictions at ethereum nodes
- 3. Configure a firewall or security group to restrict the access to the RPC API port. For example, only 192.168.1.100 is allowed to access port 8545.
Iptables -a INPUT -s 192.168.1.101 -p TCP --dport 8545 -j ACCEPT iptables -A INPUT -p TCP --dport 8545 -j DROPCopy the code
You can also use the UFW Firewall. UFW or Uncomplicated Firewall is an interface to iptables to simplify the Firewall configuration process. It is commonly used in Ubuntu
$sudo apt-get install UFW 2 Default policy $sudo Ufw default deny Incoming $sudo Ufw default allow outgoing 3. Allow Ethernet P2P network ports We will also enable the Ethereum network so that our nodes can communicate and synchronize with the public blockchain network. For example, the Ethereum network port is 30303 $sudo Ufw allow 30303Copy the code
Note: This method limits IP addresses and ports on the servers where nodes are deployed. Physical servers can be restricted by using iptables firewalls, and cloud servers can be restricted by using security groups
- 4. Enable RPC port We only allow connections from our trusted nodes to our Ethereum client. The default RPC port for the Ethereum port is 8545.
$ sudo ufw allow from <IP addr> to any port 8545
Copy the code
For example, if my external server IP address is 192.168.1.101, you should also specify the corresponding port if you are using a different RPC port than 8545.
Sudo ufw allow from 192.168.1.101 to any port 8545Copy the code
Note: To set the preceding rules, enable the UFW command, sudo UFW enable
In summary, it is recommended that you configure it to allow everyone to connect to ethereum RPC and network ports. Be sure to allow any other incoming connections the server needs in a firewall or security group, while limiting any unnecessary connections for your server to function and be secure.
2.2 Private Key Security
- 1. Do not store the account information (keystore) on the node (because the account is not on the node, so the unlockAccount is not used)
Note: Normally, the account information should not be stored in the node, but if you need to flush the transaction of an account, it may be manually operated by the node. At this time, make sure that your node RPC port can only be connected to the TRUSTED IP address, otherwise the account funds may be transferred.
- 2. SendTransaction signed by private key using web3 sendTransaction and sendRawTransaction for any transfer (limit insecure transfer commands)
- 3. The private key is physically isolated (such as cold wallet or manual transcription) or stored in high-intensity encryption to ensure the security of the key
Note: The security configuration of the private key, in addition to the above points, there is a special need to pay attention to the place, because this article is about the network security of RPC port, so the private key security is not described here.
3. RPC port access encryption and access control
If the GETH node has to be exposed to the public network, it will face many security risks. One possible remedy is to encrypt RPC access. With NGINx’s HTTP Basic Auth(HTTP Basic Authentication) technology, you can achieve higher security.
How it works: By configuring Nginx’s reverse proxy and encryption technology, you can assign a new URL to an application running on Linux. Accessing an application is equivalent to accessing this URL. External users who want to access this URL must enter a username and password, otherwise access will be denied. In the CASE of geTH nodes, RPC ports must be exposed to all users before using NBHA technology. Then, geth is assigned a url that requires a user name and password to access the GETH node. In this case, the GETH node does not have to open its RPC port to the public.
3.1 nginx configuration
Nginx uses the docker deployment method, please refer to my previous article [three minutes tutorial] Docker rapid deployment of nginx service
After deploying the nginx service, do the following:
- Install the htpasswd tool
# docker exec -it nginx bash
# apt-get update
# apt-get install apache2-utils -y
Copy the code
- Create an authentication user name and password
# htpasswd -c /etc/nginx/geth.htpasswd eth New password: enter the password re-type New password: Enter the password again: Adding password for user ethCopy the code
3.2 Configuring HTTP Requests
Create a password file named geth.htpasswd in /etc/nginx and set the user name to eth. Enter the above command, the user will be prompted to enter the password twice. To modify the nginx configuration, open the /etc/nginx/sites-enabled/default file and change the contents of the file to the following:
server {
listen 80 default_server;
server_name localhost;
location / {
try_files $uri $uri/ =404;
}
location /eth {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/geth.htpasswd;
proxy_pass http://localhost:8545;
}
access_log /var/log/nginx/localhost.log main;
}
Copy the code
The name of the server is set to localhost, the URL for geth is localhost/eth, and the password file is specified by the auth_basic_user_file directive.
You can use the browser to see what the effect, the effect should appear:
Visit: http://localhost/, a 404 page appears
Access: http://localhost/eth After entering the correct user name and password, click OK. If no error occurs, the configuration is successful.
So far, nginx has successfully built a layer of security for GEth and mapped geth to an external URL. Now, geth is not accessed through http://:, but directly to the mapped URL. Geth attach http://username:password@ip/eth so now is the time to disable external access to the RPC port exposed by GEth. Tencent Cloud Ali cloud has a security group can achieve this operation.
curl -H "Content-Type: Application/json "- X POST -- data '{" jsonrpc" : "2.0", "method" : "eth_syncing", "params" : [], "id" : 1}' http://eth:[email protected]/ethCopy the code
3.3 ios Access Configuration for Android Devices
Web3j uses the Http module OkHttp3. The user name and password required for authentication can be added in the same way that OkHttp3 adds authentication. When Http authentication is not used, web3J constructs the Admin object as follows:
Admin ethClient; ethClient = Admin.build(new HttpService(url));
How to add the authentication user name and password:
private static OkHttpClient buildBasicAuthClient() { return new OkHttpClient.Builder().authenticator(new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { String credential = okhttp3.Credentials.basic(Define.userName, Define.passwd); return response.request().newBuilder().header("Authorization", credential).build(); } }).build(); } Admin ethClient; ethClient = Admin.build(new HttpService(url,buildBasicAuthClient(),false));Copy the code
3.4 Nginx Cross-domain Configuration
OK, now you can use Web3j to access geTH nodes with Http authentication protection. The preceding command is suitable for Android clients. However, the ios client calls web3.js to access Http Basic Authentication protected resources. The way of accessing GEth on ios clients is different from that on Android. Because there is no open source mature OC language similar to web3J library, ios terminal only through the way of webView to establish an Html page, in the page through JS to call web3.js API functions to access GEth. An error is reported when accessing the GEth node with Http Basic Authentication in the browser. This is because the browser is reporting cross-domain access to JS. A Google post mimics the online solution to CROS by adding the configuration to the nginx configuration file. The final configuration:
server { listen 80 default_server; server_name localhost; location / { try_files $uri $uri/ =404; } location /eth { auth_basic "Restricted Area"; auth_basic_user_file /etc/nginx/geth.htpasswd; proxy_pass http://localhost:8545; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Auth orization'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain charset=UTF-8'; add_header 'Content-Length' 0; return 204; } } access_log /var/log/nginx/localhost.log main; }Copy the code
3.5 Nginx HTTPS Configuration
Of course, in addition to HTTP basic authentication, you can also configure Https with certificate protection, which is more secure. Http transmission is in plain text, so it is very insecure to use Http to transmit privacy information. HTTPS is a network protocol that uses SSL and HTTP to encrypt transmission and authenticate identities. It is more secure than HTTP. It can encrypt the transmitted content. HTTPS requires a CA certificate. Aliyun can apply for a free Symantec certificate. Ali Cloud certificate requires an available domain name first, which maps to the IP of the node. After applying for the certificate, download it to the node and configure it in the nginx configuration file.
Nginx configures HTTPS as follows:
server{ listen 443 ssl; server_name localhost; charset utf-8; ssl_certificate /etc/nginx/cert/xxx.pem; ssl_certificate_key /etc/nginx/cert/xxx.key; ssl_session_timeout 5m; Ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers AESGCM:ALL:! DH:! EXPORT:! RC4:+HIGH:! MEDIUM:! LOW:! aNULL:! eNULL; ssl_prefer_server_ciphers on; location / { try_files $uri $uri/ =404; } location /eth { auth_basic "Restricted Area"; auth_basic_user_file /etc/nginx/geth.htpasswd; proxy_pass http://localhost:8545; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain charset=UTF-8'; add_header 'Content-Length' 0; return 204; } } access_log /var/log/nginx/localhost.log main; }Copy the code
Restart the nginx service to use HTTPS
3.6 Nginx Access control Configuration
At some point, we may also need to allow access only to some IP addresses. Of course, this requirement can be realized on the security group of Ali Cloud or Tencent Cloud, or using the iptables firewall of the server. The following method is implemented using access control features in Nginx. Nginx configuration is as follows:
server{ listen 443 ssl; server_name localhost; charset utf-8; ssl_certificate /etc/nginx/cert/xxx.pem; ssl_certificate_key /etc/nginx/cert/xxx.key; ssl_session_timeout 5m; Ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers AESGCM:ALL:! DH:! EXPORT:! RC4:+HIGH:! MEDIUM:! LOW:! aNULL:! eNULL; ssl_prefer_server_ciphers on; location / { try_files $uri $uri/ =404; } location /eth { auth_basic "Restricted Area"; auth_basic_user_file /etc/nginx/geth.htpasswd; proxy_pass http://localhost:8545; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain charset=UTF-8'; add_header 'Content-Length' 0; return 204; } # # # # # limit only part of the IP access # # # # # # # # # # # # # # allow 49.7.66.132; Allow 124.65.8.139; deny all; # # # # # # limit only part of the IP access # # # # # # # # # # # # # #} access_log/var/log/nginx/localhost. Log the main; }Copy the code
For example, if the IP addresses in Allow are accessible, the status code 403 is displayed when the IP addresses not in Allow access https://localhost/eth.
And that’s it for today.
I hope you can solve your actual needs and solve your current problems through the above means.
If you have any questions in the configuration process, you can add my personal wechat. Note: region – career direction – nickname, welcome to join the blockchain technology exchange group, and learn to communicate with more blockchain technology leaders.
Original is not easy, code word is not easy. If you think this article is useful to you, please give it a thumbs up, leave a comment or forward it, because this will be my motivation to output more high-quality articles, thank you!