Preface

This is a follow up to the Enabling multiple SSH Keys for Bitbucket Cloud article, have you ever wanted to use a specific SSH key for a particular CIDR range? During my time working across various network CIDR ranges both personal and workplace related, I've seen the need to specify a specific key say for example a key for Pre-Production and Production environments. This a guide to talk through some of the various ways this can be achieved using the ~/.ssh/config file.

Specifying a wildcard CIDR block

The example below shows the two methods I've used to wildcard different CIDR blocks to use a specific SSH key.

Example 1 below shows how you can specify a key for an entire 10.0.0.0/24 CIDR range, this is done by using the * wildcard operator. This matches everything within CIDR range so IP addresses ranging from 10.0.0.0 - 10.0.0.255 inclusive.

Example 2 below shows how you can specify a key for every host within a limited CIDR range, this is done by using the ? wildcard operator. This matches a single character length so 0 - 9, this means it will catch every address from 10.0.0.0 - 10.0.9.255 inclusive.

# Example 1
# 10.0.0.[0-255]
Host 10.0.0.*
	IdentityFile ~/.ssh/id_rsa_10_0_0_X
  
# Example 2
# 10.0.[0-9].[0-255]
Host 10.0.?.*
	IdentityFile ~/.ssh/id_rsa_10_0_X_Y
 	
# Default
Host *
  IdentityFile ~/.ssh/id_rsa
Examples of the wildcarding methods in the SSH Config file

Real world example

# 10.0.0.[0-255]
Host 10.0.0.*
	IdentityFile ~/.ssh/id_rsa_10_0_0_0
    
# 10.50.50.[0-255] and 10.75.75.[0-255]
Host 10.50.50.*, 10.75.75.*
	IdentityFile ~/.ssh/id_rsa_10_50_50_0
    
# Default
Host *
  IdentityFile ~/.ssh/id_rsa
Real world example of wildcarding method in the SSH Config file

The real world example above is similar to how I've had mine setup in the past, this means for everything in the 10.0.0.0/24 range (say my home network VMs) I would use the key id_rsa_10_0_0_0. Then for anything on the corporate network 10.50.50.0/24 and 10.75.75.0/24, would then use the id_rsa_10_50_50_0 key. Then everything else uses the standard id_rsa key.

The wildcard patterns above are using Regular Expressions (Regex) which is a form of pattern matching, more about this can be found in the ssh_config man page linked at the end of this article. Or further reading through the Wikipedia link about regular expressions.

In Conclusion

I've shown you how to how to configure your user ssh config file.

By default, SSH listens on port 22. Changing the default SSH port adds an extra layer of security to your server by reducing the risk of automated attacks.