Skip to content

Blog

Socket-first exploration


tags: - The-Ccategories: - Codingdate:# created: 2025-02-26# updated: 2025-02-26—

1. Socket() function### (1). domain protocol family: 1. AF_INET 2. AF_INET6 3. AF_LOCAL(AF_UNIX) 4. AF_ROUTE### (2). Type socket type 1. SOCK_STREAM 2. SOCK_DGRAM 3. SOCK_RAW 4. SOCK_PACKET 5. SOCK_SEQPACKET### (3). Protocol 1. IPPROTO_TCP 2. IPPROTO_UDP 3. IPPROTO_STCP 4. IPPROTO_TIPC## 2. Bind() function```

Section titled “1. Socket() function### (1). domain protocol family: 1. AF_INET 2. AF_INET6 3. AF_LOCAL(AF_UNIX) 4. AF_ROUTE### (2). Type socket type 1. SOCK_STREAM 2. SOCK_DGRAM 3. SOCK_RAW 4. SOCK_PACKET 5. SOCK_SEQPACKET### (3). Protocol 1. IPPROTO_TCP 2. IPPROTO_UDP 3. IPPROTO_STCP 4. IPPROTO_TIPC## 2. Bind() function```”
Int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
- Sockfd: socket descriptor, uniquely identifies a socket- addrlen: address length- addr: an address pointer pointing to the protocol address to be bound to sockfd
For example, ipv4 corresponds to:```
struct sockaddr_in {
sa_family_t sin_family;
in_port_t sin_port;
struct in_addr sin_addr;
};
struct in_addr {
uint32_t s_addr;
};

Corresponding to ipv6 is:``` struct sockaddr_in6 {
sa_family_t sin6_family;
in_port_t sin6_port;
uint32_t sin6_flowinfo;
struct in6_addr sin6_addr;
uint32_t sin6_scope_id;
};

struct in6_addr {
unsigned char s6_addr[16];
};
The Unix domain corresponds to:```
#define UNIX_PATH_MAX 108
struct sockaddr_un {
sa_family_t sun_family;
char sun_path[UNIX_PATH_MAX];
};

Int listen(int sockfd, int backlog)Int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen)

  • The listen function changes the active type created by the socket into a passive type and waits for the client to connect.

Int socket(int domain, int type, int protocol)

## 5. setsockopt function```
Int setsockopt(SOCKET s, int level, int optname, const char FAR *optval, int optlen)
  • s:socket descriptor- Level: option level, SOL_SOCKET/IPPROTO_TCP- Optname: Options that need to be set- optval: just want to store the pointer of the option- Optlen: buffer length

[2]. OSI model

SSH Authentication with GPG Keys on Linux


tags: - GnuPG - SSHcategories: - Linux date:created: 2025-04-05updated: 2024-06-05—

Here are the steps on how to set up SSH authentication using GPG on Linux:

  • GPG (GNU Privacy Guard): A cryptographic tool commonly used for signing and encrypting data. We can leverage GPG key pairs for authentication.* SSH (Secure Shell): An encrypted network protocol used to securely execute commands and transfer files over unsecured networks.* gpg-agent: A daemon that manages your GPG private keys to avoid having to enter a password every time you use them.* ssh-agent: A daemon that manages your SSH private keys and also avoids password re-entering.* libpam-gnome-keyring(optional but recommended): A PAM module that automatically startsgpg-agentandssh-agentwhen you log in.* gnupg-agent: Provides the functionality required for SSH authentication using GPG keys.

1. Install the necessary packages:Depending on your Linux distribution, install the following packages: * Debian/Ubuntu: ```bash

Section titled “1. Install the necessary packages:Depending on your Linux distribution, install the following packages: * Debian/Ubuntu: ```bash”
sudo apt update
sudo apt install gnupg2 gpg-agent openssh-server openssh-client libpam-gnome-keyring
```
* **Fedora/CentOS/RHEL:** ```bash
sudo dnf install gnupg2 gpg-agent openssh-server openssh-clients pam_gnome_keyring
```
* **Arch Linux:** ```bash
sudo pacman -S gnupg openssh libgnome-keyring
```

2. Generate or import a GPG key pair:If you don’t have a GPG key pair yet, you can generate a new one using the following command: ```bash

Section titled “2. Generate or import a GPG key pair:If you don’t have a GPG key pair yet, you can generate a new one using the following command: ```bash”
gpg --full-generate-key
```

Follow the prompts to select the key type, key length, expiration date, and set your real name, email address, and comment. Please remember your password.If you already have a GPG key pair, you can skip this step.

3. Confirm GPG key usage and obtain fingerprint:Make sure you have a GPG key or subkey with purpose set toAuthenticate. Confirm and obtain the fingerprint (40-digit HEX) of the key or subkey with the following command: ```bash

Section titled “3. Confirm GPG key usage and obtain fingerprint:Make sure you have a GPG key or subkey with purpose set toAuthenticate. Confirm and obtain the fingerprint (40-digit HEX) of the key or subkey with the following command: ```bash”
gpg --with-keygrip -K
```

4. Add the GPG key fingerprint to thesshcontrolfile:Put the fingerprint obtained in the previous step into the~/.gnupg/sshcontrolfile. Place one fingerprint per line. ```

Section titled “4. Add the GPG key fingerprint to thesshcontrolfile:Put the fingerprint obtained in the previous step into the~/.gnupg/sshcontrolfile. Place one fingerprint per line. ```”
# 示例 (将 YOUR_FINGERPRINT 替换为实际的指纹)
YOUR_FINGERPRINT
```

5. Configuregpg-agent:Edit or create the~/.gnupg/gpg-agent.conffile and add the following lines: ```

Section titled “5. Configuregpg-agent:Edit or create the~/.gnupg/gpg-agent.conffile and add the following lines: ```”
enable-ssh-support
default-cache-ttl 3600
max-cache-ttl 7200
```
* `enable-ssh-support`: Enable SSH support. * `default-cache-ttl`: Set the default password cache time in seconds. * `max-cache-ttl`: Set the maximum password cache time.

6. Configure PAM (optional but recommended):If you havelibpam-gnome-keyring(or a similar package) installed, you can configure PAM to automatically startgpg-agentandssh-agentat login.Edit the/etc/pam.d/loginand/etc/pam.d/sshdfiles and add the following lines if they do not exist:In theauthsection add: ```

Section titled “6. Configure PAM (optional but recommended):If you havelibpam-gnome-keyring(or a similar package) installed, you can configure PAM to automatically startgpg-agentandssh-agentat login.Edit the/etc/pam.d/loginand/etc/pam.d/sshdfiles and add the following lines if they do not exist:In theauthsection add: ```”
auth optional pam_gnome_keyring.so skel
```

In thesessionsection add: session optional pam_gnome_keyring.so auto_start Note: The exact files and lines may vary depending on your Linux distribution and PAM configuration. You may need to make similar changes in other PAM configuration files such assudoor the graphical login manager.

7. Export the SSH public key:Use the following command to export the SSH public key from your GPG private key. ReplaceYOUR_GPG_KEY_IDwith your GPG key ID. You can find your key ID using thegpg --list-secret-keys --keyid-format longcommand. ```bash

Section titled “7. Export the SSH public key:Use the following command to export the SSH public key from your GPG private key. ReplaceYOUR_GPG_KEY_IDwith your GPG key ID. You can find your key ID using thegpg --list-secret-keys --keyid-format longcommand. ```bash”
gpg --export-ssh-key YOUR_GPG_KEY_ID > ~/.ssh/id_ed25519.pub
```

Notice: * The exported public key is saved as~/.ssh/id_ed25519.pubby default. You can change the file name as needed. * Make sure your GPG private key is password protected.

8. Copy the SSH public key to the remote server:Copy the contents of your exported SSH public key (~/.ssh/id_ed25519.pub) into the~/.ssh/authorized_keysfile on the remote server you want to SSH authenticate.You can use thessh-copy-idcommand to simplify this process (if your local machine is already configured for password- or key-based SSH access): ```bash

Section titled “8. Copy the SSH public key to the remote server:Copy the contents of your exported SSH public key (~/.ssh/id_ed25519.pub) into the~/.ssh/authorized_keysfile on the remote server you want to SSH authenticate.You can use thessh-copy-idcommand to simplify this process (if your local machine is already configured for password- or key-based SSH access): ```bash”
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@remote_server
```

Alternatively, you can manually append the contents of~/.ssh/id_ed25519.pubto the~/.ssh/authorized_keysfile on the remote server: bash cat ~/.ssh/id_ed25519.pub | ssh user@remote_server "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

9. Configure the SSH client:Edit or create the~/.ssh/configfile and add the following to configure your SSH client to use GPG for authentication: ```

Section titled “9. Configure the SSH client:Edit or create the~/.ssh/configfile and add the following to configure your SSH client to use GPG for authentication: ```”
Host remote_server_alias # 您可以为远程服务器设置一个别名
Hostname remote_server_ip_or_hostname
User your_username
IdentityFile ~/.ssh/id_ed25519
PubkeyAcceptedKeyTypes +ssh-ed25519-cert-v01@openssh.com,ssh-ed25519
```
* `Host`: The alias you set for the remote server. * `Hostname`: The IP address or hostname of the remote server. * `User`: Your username on the remote server. * `IdentityFile`: The path to the SSH public key file you exported (without the`.pub`extension). * `PubkeyAcceptedKeyTypes`: Specifies the accepted public key types. Add`+ssh-ed25519-cert-v01@openssh.com`to enable certificate-based authentication.

10. Startgpg-agentandssh-agent:If you do not configure PAM, you need to startgpg-agentandssh-agentmanually after logging in. Add the following to your shell configuration file (e.g.~/.bashrc,~/.zshrc): ```bash

Section titled “10. Startgpg-agentandssh-agent:If you do not configure PAM, you need to startgpg-agentandssh-agentmanually after logging in. Add the following to your shell configuration file (e.g.~/.bashrc,~/.zshrc): ```bash”
if [ -z "$SSH_AUTH_SOCK" ]; then
eval "$(ssh-agent -s)"
fi
if ! gpg-connect-agent /bye > /dev/null 2>&1; then
eval "$(gpg-agent --daemon --enable-ssh-support)"
fi
export SSH_AUTH_SOCK="$(gpgconf --list-dirs agent-ssh-socket)"
```

Then, reload your shell profile: bash source ~/.bashrc # 或 source ~/.zshrc

11. Add the GPG private key togpg-agent:You may need to add your GPG private key togpg-agent. This will prompt you for your password: ```bash

Section titled “11. Add the GPG private key togpg-agent:You may need to add your GPG private key togpg-agent. This will prompt you for your password: ```bash”
gpg --import-ownertrust
gpg --card-status # 如果您使用智能卡
```

Alternatively, you can enter your password the first time you attempt an SSH connection.

12. Test the SSH connection:You should now be able to SSH to the remote server using the configured alias without entering a password (unless your GPG private key is not already unlocked): ```bash

Section titled “12. Test the SSH connection:You should now be able to SSH to the remote server using the configured alias without entering a password (unless your GPG private key is not already unlocked): ```bash”
ssh remote_server_alias
```

If this is your first time using this GPG key for an SSH connection, you may be asked to enter the password for the GPG key. Afterwards, the password will be cached ingpg-agentuntil the cache expires.

  • Security: Make sure your GPG private key is protected by a strong password.* Backup: Be sure to back up your GPG private key.* gpg-agentandssh-agent: Make sure these two agents are running. You can check this using theps aux | grep gpg-agentandps aux | grep ssh-agentcommands.* Permissions: Make sure the permissions for the~/.sshdirectory and~/.ssh/authorized_keysfiles are set correctly (usually700for~/.sshand600for~/.ssh/authorized_keys).* Server Configuration: Ensure that public key authentication (PubkeyAuthentication yes) is enabled in thesshd_configfile on the remote server. With the above steps, you should be able to successfully configure your Linux system to use GPG keys for SSH authentication, improving security and streamlining your workflow.

[2]. OpenPGP-a preliminary study

TCP Over DNS to bypass campus network billing


tags: - TCPcategories: - Network - Linuxdate:created: 2020-08-20# updated: 2024-01-19—

TCP Over DNS to bypass campus network billing

Section titled “TCP Over DNS to bypass campus network billing”

1. Requirements- VPS -> Take CentOS as an example-> IP is represented by 123.123.123.123- Domain name -> represented by domain.com-> Subdomain names are represented by tunnels

Section titled “1. Requirements- VPS -> Take CentOS as an example-> IP is represented by 123.123.123.123- Domain name -> represented by domain.com-> Subdomain names are represented by tunnels”

2. Set up domain name resolution|host record|Record|value|

Section titled “2. Set up domain name resolution|host record|Record|value|”

| –– | —– | —– | |NS|d2t|tunnel.domain.com| |A|tunnel|123.123.123.123 |

git clone https://github.com/yarrick/iodine.git
cd iodine
make
make install
  • Compilation and installation require GCC environment

(2). Run iodineiodined -f -c -P password 10.0.0.1 d2t.domain.com

Section titled “(2). Run iodineiodined -f -c -P password 10.0.0.1 d2t.domain.com”
  • Note:> -f runs in the foreground> -c disables checking the client IP address of all incoming requests; by default, requests from non-matching IPs will be rejected.> -P sets authentication password> 10.0.0.1 is a reserved address

ClientThe client is Ubuntu20.04 LTS in WSL2

Section titled “ClientThe client is Ubuntu20.04 LTS in WSL2”

(1). Install iodinesudo apt-get install iodine

Section titled “(1). Install iodinesudo apt-get install iodine”

(2). Run iodinesudo iodine -f -P password d2t.domain.com

Section titled “(2). Run iodinesudo iodine -f -P password d2t.domain.com”

(3). Open a new Terminal, connect to the server through SSH, and use 9999 as the forwarding port.ssh USER@10.0.0.1 -p1234 -D 9999

Section titled “(3). Open a new Terminal, connect to the server through SSH, and use 9999 as the forwarding port.ssh USER@10.0.0.1 -p1234 -D 9999”
  • Note:> USER represents the username of the VPS> 1234 represents the port of SSH on the VPS

(1). Install the plug-in [SwitchyOmega][SwitchyOmega] in the browser

Section titled “(1). Install the plug-in [SwitchyOmega][SwitchyOmega] in the browser”

(2). Create a new Proxy Profile|Protocol|Server|Port|

Section titled “(2). Create a new Proxy Profile|Protocol|Server|Port|”

|––––|—— |––| |Socks5|localhost|9999|

(3). Click on SwitchyOmega in the upper right corner of the browser to select the proxy created in the previous step to access the Internet.

Section titled “(3). Click on SwitchyOmega in the upper right corner of the browser to select the proxy created in the previous step to access the Internet.”

[1]. https://fanqxu.github.io/2019/03/20/Bypass-campusNet/

[2].OSI model [SwitchyOmega]:https://chrome.google.com/webstore/detail/proxy-switchyomega/padekgcemlokbadohgkifijomclgjgif

VM CPP QT Compiling Environment with VSCode

VM CPP QT Compiling Environment with VSCode

Section titled “VM CPP QT Compiling Environment with VSCode”

First of all, the latest version of VSCode should be installed on one PC running Windows/Linux/MacOS.

Secondly, the following Extensions should be installed:

C/C++

Remote-SSH

Remote-SSH:Editing-Configuration-Files

(2). With VMWare Workstation installed including a Virtual machine configured.

Section titled “(2). With VMWare Workstation installed including a Virtual machine configured.”

Firstly, the virtual machine should run properly.

Also, the network goes OK (PING from host to the VMs, and the reverse).

Open “REMOTE EXPLORER” window -> “Add NEW”, and type the following command in the dialog:

ssh USER@192.xxx.xxx.xxx -A

Type in the password and leave the popup options default.

USER is the user of VMs’ username

192.xxx.xxx.xxx is the IP address of the VM.

Then choose a proper path as the compiling default path, the Home path is recommended.

(2). Upload the Source Code to the virtual machine

Section titled “(2). Upload the Source Code to the virtual machine”

In this step, many tools can be applyed, including scp、sftp、xshell.

ATTENTION! You should upload the code with a proper user to avoid the permission error.

Step1. Open the path of source code in VSCode.

Step2. Add a new directory named .vscode if no such directory exist.

Add c_cpp_properties.json in the .vscode folder. The content as follow:

{
"configurations": [
{
"name": "RHEL7.2->Linux",
"includePath": [
"${workspaceFolder}/**",
"/opt/scadacom/current/**"
],
"forcedInclude": [],
"defines": [],
"compilerPath": "/usr/bin/g++",
"cStandard": "c11",
"cppStandard": "c++11",
"intelliSenseMode": "linux-gcc-x64",
"compilerArgs": [ //Release
"-std=c++11",
"-w",
"-O2",
"-pipe",
"-m64",
"-D_REENTRANT",
"-DQT_SHARED",
"-DQT_NO_DEBUG_OUTPUT",
"-DQT_NO_DEBUG",
"-DQT_GUI_LIB",
"-DQT_NETWORK_LIB",
"-DQT_CORE_LIB",
"-DQT_SHARED"
]
},
{
"name": "RHEL7.2-WindowsLocal",
"includePath": [
"${workspaceFolder}/**",
"~/Documents/Codes/include/RHEL7.2S5.8.10/**",
"C:/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/x86_64-w64-mingw32/include"
],
"forcedInclude": [],
"defines": [],
"compilerPath": "C:/ProgramData/chocolatey/bin/g++.exe",
"cStandard": "c11",
"cppStandard": "c++11",
"intelliSenseMode": "linux-gcc-x64",
"compilerArgs": [ //Release
"-std=c++11",
"-w",
"-O2",
"-pipe",
"-m64",
"-D_REENTRANT",
"-DQT_SHARED",
"-DQT_NO_DEBUG_OUTPUT",
"-DQT_NO_DEBUG",
"-DQT_GUI_LIB",
"-DQT_NETWORK_LIB",
"-DQT_CORE_LIB",
"-DQT_SHARED"
],
"mergeConfigurations": false,
"browse": {
"path": [
"${workspaceFolder}/**",
"~/Documents/Codes/include/RHEL7.2S5.8.10/**"
],
"limitSymbolsToIncludedHeaders": true
}
}
],
"version": 4
}

Qmake and g++ compile configuration need configured in a tasks.json file. The content as follow:

{
"version": "2.0.0",
// "windows": {
// "options": {
// "shell": {
// "executable": "bash.exe",
// "args": ["-c"]
// }
// }
// },
"tasks": [
{
"label": "Qmake",
"type": "shell",
"command": "/usr/local/Trolltech/Qt-4.8.4/bin/qmake",
"args": [],
"group": "build",
"presentation": {
"reveal": "silent",
"clear": true
}
},
{
"label": "Clean",
"type": "shell",
"command": "make",
"args": [
"clean"
],
"group": "build",
"presentation": {
"reveal": "silent",
"clear": true
}
},
{
"label": "MakeCompile",
"type": "shell",
"dependsOrder": "sequence",
"dependsOn": [
"Clean",
"Qmake"
],
"command": "/usr/bin/make",
"args": [
],
"group": "build",
"presentation": {
// "reveal": "silent",
"clear": true
}
},
]
}

After task configured, you can launch build task from vscode edit window by press CTRL+Shift+B.

The manual as follow:

Qmake: runing command /usr/local/Trolltech/Qt-4.8.4/bin/qmake

Release: running command /usr/bin/make -f Makefile.Release after running Qmake automatically.

Debug: running command /usr/bin/make -f Makefile.Debug after running Qmake automatically.

Clean: delete files generate by Qmake and g++

Clean-Release: running command make -f Makefile.Release clean

Clean-Debug: running command make -f Makefile.Debug clean

GNU gdb tool will be used as the debug tool, you can debug the code with such launch.json configuration:

{
"version": "0.2.0",
"configurations": [
{
"name": "QT-CPPGDB",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/wg_modbus_ats",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/debug/",
"environment": [],
//"symbolSearchPath": "C:\\Symbols",
"externalConsole": false,
"linux": {
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
"windows": {
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
"osx": {
"miDebuggerPath": "/Applications/Xcode.app/Contents/Developer/usr/bin/lldb-mi",
"MIMode": "lldb"
},
// "logging": {
// "moduleLoad": false,
// "trace": true
// },
"visualizerFile": "my.natvis"
},
{
"name": "CMake-CPPGDB",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/${workspaceFolderBasename}",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/build",
"environment": [],
//"symbolSearchPath": "C:\\Symbols",
"externalConsole": false,
"linux": {
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
"windows": {
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
"osx": {
"miDebuggerPath": "/Applications/Xcode.app/Contents/Developer/usr/bin/lldb-mi",
"MIMode": "lldb"
},
// "logging": {
// "moduleLoad": false,
// "trace": true
// },
"visualizerFile": "my.natvis"
}
]
}

However, the debug can not change the target automatically, the debug flow should be as follow:

Running Clean or Clean-Debug -> Running Debug -> Change TARGETS -> Set BreakPoint -> press F5.

The TARGETS is the executable file generate by g++.

All Configuration files can be found Here.

[1]. https://blog.dashdreams.com

[2]. C/C++

[3]. Remote-SSH

[4]. Remote-SSH:Editing-Configuration-Files

[5]. VSCode-C-CPP-Environment

[6]. Qmake-Pro

Linux Text Processing Commands

Linux command-line text processing usually combines small tools through pipelines. The most commonly used tools are:

  • cat: print file content.
  • grep: filter lines by pattern.
  • sed: edit text streams.
  • awk: process structured text by fields.
  • cut: extract columns from each line.
  • sort: sort lines.
  • uniq: remove or count adjacent duplicate lines.
  • tr: translate or delete characters.

Example pipeline:

Terminal window
cat access.log | grep "ERROR" | awk '{print $1}' | sort | uniq -c

This command filters error lines, extracts the first field, sorts the result, and counts repeated values.

[1]. Shell字符串截取