командная строка и оболочка unix linux

часть .. третья вроде

соединение между компьютерами, используя unix shell ssh с запросом пароля и не спрашивая пароль, проверяя ключи.

обычно нужно для доступа к сайту или серверу vps , там и описание есть и примеры настройки.

чтобы расшифровать статью с непонятных слов на чужом языке ее надо скормить яндекс переводчику. А если срочно – отнести в бюро переводов за 5000р распечатав на 30 листах бумаги.

еще более правильно – выучить язык на котором разговаривают программисты. Чаще это русский и китайский уже, не только индийский вариант инглиш.. так во многих профессиях.

  • с шифрованием доигрались – цепочкой операций теперь расшифровывается бухгалтерская книга у криптовалют.. а если – хакер смотрит на старую сидюшку года 2006 на которой шариковой ручкой подписано резольвер ша 256, она из за этого с третьего раза читается. надеюсь что как говорят наши заокеанские друзья конкуренты что фейк. (иначе первой крипте каюк или кранты)

причина изменения нескольких настроек – новые версии программ, и повышеная безопасность по большей части из за перестраховки. в третьем и четвертом абзаце не считая оглавление причина почему разные типы серверов например 2014 года и 2022 вроде бы linux а не связываются.

SSH keys

Tango-view-fullscreen.pngThis article or section needs expansion.

Tango-view-fullscreen.png Reason: The intro and Background section ignore the server perspective. (Discuss in Talk:SSH keys) SSH keys can serve as a means of identifying yourself to an SSH server using public-key cryptography and challenge-response authentication. The major advantage of key-based authentication is that, in contrast to password authentication, it is not prone to brute-force attacks, and you do not expose valid credentials if the server has been compromised (see RFC 4251 9.4.4).

Furthermore, SSH key authentication can be more convenient than the more traditional password authentication. When used with a program known as an SSH agent, SSH keys can allow you to connect to a server, or multiple servers, without having to remember or enter your password for each system.

Key-based authentication is not without its drawbacks and may not be appropriate for all environments, but in many circumstances it can offer some strong advantages. A general understanding of how SSH keys work will help you decide how and when to use them to meet your needs.

This article assumes you already have a basic understanding of the Secure Shell protocol and have installed the openssh package.

Contents

better – install FreeBSD and read the .. manual.

FreeBSD Manual Pages

home | help


SSH-KEYGEN(1)		FreeBSD	General	Commands Manual		 SSH-KEYGEN(1)

NAME
     ssh-keygen	-- OpenSSH authentication key utility

SYNOPSIS
     ssh-keygen	[-q] [-a rounds] [-b bits] [-C comment]	[-f output_keyfile]
		[-m format] [-N	new_passphrase]	[-O option]
		[-t dsa	| ecdsa	| ecdsa-sk | ed25519 | ed25519-sk | rsa]
		[-w provider] [-Z cipher]
     ssh-keygen	-p [-a rounds] [-f keyfile] [-m	format]	[-N new_passphrase]
		[-P old_passphrase] [-Z	cipher]
     ssh-keygen	-i [-f input_keyfile] [-m key_format]
     ssh-keygen	-e [-f input_keyfile] [-m key_format]
     ssh-keygen	-y [-f input_keyfile]
     ssh-keygen	-c [-a rounds] [-C comment] [-f	keyfile] [-P passphrase]
     ssh-keygen	-l [-v]	[-E fingerprint_hash] [-f input_keyfile]
     ssh-keygen	-B [-f input_keyfile]
     ssh-keygen	-D pkcs11
     ssh-keygen	-F hostname [-lv] [-f known_hosts_file]
     ssh-keygen	-H [-f known_hosts_file]
     ssh-keygen	-K [-a rounds] [-w provider]
     ssh-keygen	-R hostname [-f	known_hosts_file]
     ssh-keygen	-r hostname [-g] [-f input_keyfile]
     ssh-keygen	-M generate [-O	option]	output_file
     ssh-keygen	-M screen [-f input_file] [-O option] output_file
     ssh-keygen	-I certificate_identity	-s ca_key [-hU]	[-D pkcs11_provider]
		[-n principals]	[-O option] [-V	validity_interval]
		[-z serial_number] file	...
     ssh-keygen	-L [-f input_keyfile]
     ssh-keygen	-A [-a rounds] [-f prefix_path]
     ssh-keygen	-k -f krl_file [-u] [-s	ca_public] [-z version_number]
		file ...
     ssh-keygen	-Q [-l]	-f krl_file file ...
     ssh-keygen	-Y find-principals [-O option] -s signature_file -f
		allowed_signers_file
     ssh-keygen	-Y check-novalidate [-O	option]	-n namespace -s	signature_file
     ssh-keygen	-Y sign	-f key_file -n namespace file ...
     ssh-keygen	-Y verify [-O option] -f allowed_signers_file -I
		signer_identity	-n namespace -s	signature_file
		[-r revocation_file]

DESCRIPTION
     ssh-keygen	generates, manages and converts	authentication keys for
     ssh(1).  ssh-keygen can create keys for use by SSH	protocol version 2.

     The type of key to	be generated is	specified with the -t option.  If in-
     voked without any arguments, ssh-keygen will generate an RSA key.

     ssh-keygen	is also	used to	generate groups	for use	in Diffie-Hellman
     group exchange (DH-GEX).  See the MODULI GENERATION section for details.

     Finally, ssh-keygen can be	used to	generate and update Key	Revocation
     Lists, and	to test	whether	given keys have	been revoked by	one.  See the
     KEY REVOCATION LISTS section for details.

     Normally each user	wishing	to use SSH with	public key authentication runs
     this once to create the authentication key	in ~/.ssh/id_dsa,
     ~/.ssh/id_ecdsa, ~/.ssh/id_ecdsa_sk, ~/.ssh/id_ed25519,
     ~/.ssh/id_ed25519_sk or ~/.ssh/id_rsa.  Additionally, the system adminis-
     trator may	use this to generate host keys,	as seen	in /etc/rc.

     Normally this program generates the key and asks for a file in which to
     store the private key.  The public	key is stored in a file	with the same
     name but ".pub" appended.	The program also asks for a passphrase.	 The
     passphrase	may be empty to	indicate no passphrase (host keys must have an
     empty passphrase),	or it may be a string of arbitrary length.  A
     passphrase	is similar to a	password, except it can	be a phrase with a se-
     ries of words, punctuation, numbers, whitespace, or any string of charac-
     ters you want.  Good passphrases are 10-30	characters long, are not sim-
     ple sentences or otherwise	easily guessable (English prose	has only 1-2
     bits of entropy per character, and	provides very bad passphrases),	and
     contain a mix of upper and	lowercase letters, numbers, and	non-alphanu-
     meric characters.	The passphrase can be changed later by using the -p
     option.

     There is no way to	recover	a lost passphrase.  If the passphrase is lost
     or	forgotten, a new key must be generated and the corresponding public
     key copied	to other machines.

     ssh-keygen	will by	default	write keys in an OpenSSH-specific format.
     This format is preferred as it offers better protection for keys at rest
     as	well as	allowing storage of key	comments within	the private key	file
     itself.  The key comment may be useful to help identify the key.  The
     comment is	initialized to "user@host" when	the key	is created, but	can be
     changed using the -c option.

     It	is still possible for ssh-keygen to write the previously-used PEM for-
     mat private keys using the	-m flag.  This may be used when	generating new
     keys, and existing	new-format keys	may be converted using this option in
     conjunction with the -p (change passphrase) flag.

     After a key is generated, ssh-keygen will ask where the keys should be
     placed to be activated.

     The options are as	follows:

     -A	     For each of the key types (rsa, dsa, ecdsa	and ed25519) for which
	     host keys do not exist, generate the host keys with the default
	     key file path, an empty passphrase, default bits for the key
	     type, and default comment.	 If -f has also	been specified,	its
	     argument is used as a prefix to the default path for the result-
	     ing host key files.  This is used by /etc/rc to generate new host
	     keys.

     -a	rounds
	     When saving a private key,	this option specifies the number of
	     KDF (key derivation function, currently bcrypt_pbkdf(3)) rounds
	     used.  Higher numbers result in slower passphrase verification
	     and increased resistance to brute-force password cracking (should
	     the keys be stolen).  The default is 16 rounds.

     -B	     Show the bubblebabble digest of specified private or public key
	     file.

     -b	bits
	     Specifies the number of bits in the key to	create.	 For RSA keys,
	     the minimum size is 1024 bits and the default is 3072 bits.  Gen-
	     erally, 3072 bits is considered sufficient.  DSA keys must	be ex-
	     actly 1024	bits as	specified by FIPS 186-2.  For ECDSA keys, the
	     -b	flag determines	the key	length by selecting from one of	three
	     elliptic curve sizes: 256,	384 or 521 bits.  Attempting to	use
	     bit lengths other than these three	values for ECDSA keys will
	     fail.  ECDSA-SK, Ed25519 and Ed25519-SK keys have a fixed length
	     and the -b	flag will be ignored.

     -C	comment
	     Provides a	new comment.

     -c	     Requests changing the comment in the private and public key
	     files.  The program will prompt for the file containing the pri-
	     vate keys,	for the	passphrase if the key has one, and for the new
	     comment.

     -D	pkcs11
	     Download the public keys provided by the PKCS#11 shared library
	     pkcs11.  When used	in combination with -s,	this option indicates
	     that a CA key resides in a	PKCS#11	token (see the CERTIFICATES
	     section for details).

     -E	fingerprint_hash
	     Specifies the hash	algorithm used when displaying key finger-
	     prints.  Valid options are: "md5" and "sha256".  The default is
	     "sha256".

     -e	     This option will read a private or	public OpenSSH key file	and
	     print to stdout a public key in one of the	formats	specified by
	     the -m option.  The default export	format is "RFC4716".  This op-
	     tion allows exporting OpenSSH keys	for use	by other programs, in-
	     cluding several commercial	SSH implementations.

     -F	hostname | [hostname]:port
	     Search for	the specified hostname (with optional port number) in
	     a known_hosts file, listing any occurrences found.	 This option
	     is	useful to find hashed host names or addresses and may also be
	     used in conjunction with the -H option to print found keys	in a
	     hashed format.

     -f	filename
	     Specifies the filename of the key file.

     -g	     Use generic DNS format when printing fingerprint resource records
	     using the -r command.

     -H	     Hash a known_hosts	file.  This replaces all hostnames and ad-
	     dresses with hashed representations within	the specified file;
	     the original content is moved to a	file with a .old suffix.
	     These hashes may be used normally by ssh and sshd,	but they do
	     not reveal	identifying information	should the file's contents be
	     disclosed.	 This option will not modify existing hashed hostnames
	     and is therefore safe to use on files that	mix hashed and non-
	     hashed names.

     -h	     When signing a key, create	a host certificate instead of a	user
	     certificate.  Please see the CERTIFICATES section for details.

     -I	certificate_identity
	     Specify the key identity when signing a public key.  Please see
	     the CERTIFICATES section for details.

     -i	     This option will read an unencrypted private (or public) key file
	     in	the format specified by	the -m option and print	an OpenSSH
	     compatible	private	(or public) key	to stdout.  This option	allows
	     importing keys from other software, including several commercial
	     SSH implementations.  The default import format is	"RFC4716".

     -K	     Download resident keys from a FIDO	authenticator.	Public and
	     private key files will be written to the current directory	for
	     each downloaded key.  If multiple FIDO authenticators are at-
	     tached, keys will be downloaded from the first touched authenti-
	     cator.

     -k	     Generate a	KRL file.  In this mode, ssh-keygen will generate a
	     KRL file at the location specified	via the	-f flag	that revokes
	     every key or certificate presented	on the command line.
	     Keys/certificates to be revoked may be specified by public	key
	     file or using the format described	in the KEY REVOCATION LISTS
	     section.

     -L	     Prints the	contents of one	or more	certificates.

     -l	     Show fingerprint of specified public key file.  For RSA and DSA
	     keys ssh-keygen tries to find the matching	public key file	and
	     prints its	fingerprint.  If combined with -v, a visual ASCII art
	     representation of the key is supplied with	the fingerprint.

     -M	generate
	     Generate candidate	Diffie-Hellman Group Exchange (DH-GEX) parame-
	     ters for eventual use by the `diffie-hellman-group-exchange-*'
	     key exchange methods.  The	numbers	generated by this operation
	     must be further screened before use.  See the MODULI GENERATION
	     section for more information.

     -M	screen
	     Screen candidate parameters for Diffie-Hellman Group Exchange.
	     This will accept a	list of	candidate numbers and test that	they
	     are safe (Sophie Germain) primes with acceptable group genera-
	     tors.  The	results	of this	operation may be added to the
	     /etc/moduli file.	See the	MODULI GENERATION section for more in-
	     formation.

     -m	key_format
	     Specify a key format for key generation, the -i (import), -e (ex-
	     port) conversion options, and the -p change passphrase operation.
	     The latter	may be used to convert between OpenSSH private key and
	     PEM private key formats.  The supported key formats are:
	     "RFC4716" (RFC 4716/SSH2 public or	private	key), "PKCS8" (PKCS8
	     public or private key) or "PEM" (PEM public key).	By default
	     OpenSSH will write	newly-generated	private	keys in	its own	for-
	     mat, but when converting public keys for export the default for-
	     mat is "RFC4716".	Setting	a format of "PEM" when generating or
	     updating a	supported private key type will	cause the key to be
	     stored in the legacy PEM private key format.

     -N	new_passphrase
	     Provides the new passphrase.

     -n	principals
	     Specify one or more principals (user or host names) to be in-
	     cluded in a certificate when signing a key.  Multiple principals
	     may be specified, separated by commas.  Please see	the
	     CERTIFICATES section for details.

     -O	option
	     Specify a key/value option.  These	are specific to	the operation
	     that ssh-keygen has been requested	to perform.

	     When signing certificates,	one of the options listed in the
	     CERTIFICATES section may be specified here.

	     When performing moduli generation or screening, one of the	op-
	     tions listed in the MODULI	GENERATION section may be specified.

	     When generating a key that	will be	hosted on a FIDO authentica-
	     tor, this flag may	be used	to specify key-specific	options.
	     Those supported at	present	are:

	     application
		     Override the default FIDO application/origin string of
		     "ssh:".  This may be useful when generating host or do-
		     main-specific resident keys.  The specified application
		     string must begin with "ssh:".

	     challenge=path
		     Specifies a path to a challenge string that will be
		     passed to the FIDO	token during key generation.  The
		     challenge string may be used as part of an	out-of-band
		     protocol for key enrollment (a random challenge is	used
		     by	default).

	     device  Explicitly	specify	a fido(4) device to use, rather	than
		     letting the token middleware select one.

	     no-touch-required
		     Indicate that the generated private key should not	re-
		     quire touch events	(user presence)	when making signa-
		     tures.  Note that sshd(8) will refuse such	signatures by
		     default, unless overridden	via an authorized_keys option.

	     resident
		     Indicate that the key should be stored on the FIDO	au-
		     thenticator itself.  Resident keys	may be supported on
		     FIDO2 tokens and typically	require	that a PIN be set on
		     the token prior to	generation.  Resident keys may be
		     loaded off	the token using	ssh-add(1).

	     user    A username	to be associated with a	resident key, overrid-
		     ing the empty default username.  Specifying a username
		     may be useful when	generating multiple resident keys for
		     the same application name.

	     verify-required
		     Indicate that this	private	key should require user	veri-
		     fication for each signature.  Not all FIDO	tokens support
		     this option.  Currently PIN authentication	is the only
		     supported verification method, but	other methods may be
		     supported in the future.

	     write-attestation=path
		     May be used at key	generation time	to record the attesta-
		     tion data returned	from FIDO tokens during	key genera-
		     tion.  Please note	that this information is potentially
		     sensitive.	 By default, this information is discarded.

	     When performing signature-related options using the -Y flag, the
	     following options are accepted:

	     print-pubkey
		     Print the full public key to standard output after	signa-
		     ture verification.

	     verify-time=timestamp
		     Specifies a time to use when validating signatures	in-
		     stead of the current time.	 The time may be specified as
		     a date in YYYYMMDD	format or a time in YYYYMMDDHHMM[SS]
		     format.

	     The -O option may be specified multiple times.

     -P	passphrase
	     Provides the (old)	passphrase.

     -p	     Requests changing the passphrase of a private key file instead of
	     creating a	new private key.  The program will prompt for the file
	     containing	the private key, for the old passphrase, and twice for
	     the new passphrase.

     -Q	     Test whether keys have been revoked in a KRL.  If the -l option
	     is	also specified then the	contents of the	KRL will be printed.

     -q	     Silence ssh-keygen.

     -R	hostname | [hostname]:port
	     Removes all keys belonging	to the specified hostname (with	op-
	     tional port number) from a	known_hosts file.  This	option is use-
	     ful to delete hashed hosts	(see the -H option above).

     -r	hostname
	     Print the SSHFP fingerprint resource record named hostname	for
	     the specified public key file.

     -s	ca_key
	     Certify (sign) a public key using the specified CA	key.  Please
	     see the CERTIFICATES section for details.

	     When generating a KRL, -s specifies a path	to a CA	public key
	     file used to revoke certificates directly by key ID or serial
	     number.  See the KEY REVOCATION LISTS section for details.

     -t	dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk |	rsa
	     Specifies the type	of key to create.  The possible	values are
	     "dsa", "ecdsa", "ecdsa-sk", "ed25519", "ed25519-sk", or "rsa".

	     This flag may also	be used	to specify the desired signature type
	     when signing certificates using an	RSA CA key.  The available RSA
	     signature variants	are "ssh-rsa" (SHA1 signatures,	not recom-
	     mended), "rsa-sha2-256", and "rsa-sha2-512" (the default).

     -U	     When used in combination with -s, this option indicates that a CA
	     key resides in a ssh-agent(1).  See the CERTIFICATES section for
	     more information.

     -u	     Update a KRL.  When specified with	-k, keys listed	via the	com-
	     mand line are added to the	existing KRL rather than a new KRL be-
	     ing created.

     -V	validity_interval
	     Specify a validity	interval when signing a	certificate.  A	valid-
	     ity interval may consist of a single time,	indicating that	the
	     certificate is valid beginning now	and expiring at	that time, or
	     may consist of two	times separated	by a colon to indicate an ex-
	     plicit time interval.

	     The start time may	be specified as	the string "always" to indi-
	     cate the certificate has no specified start time, a date in
	     YYYYMMDD format, a	time in	YYYYMMDDHHMM[SS] format, a relative
	     time (to the current time)	consisting of a	minus sign followed by
	     an	interval in the	format described in the	TIME FORMATS section
	     of	sshd_config(5).

	     The end time may be specified as a	YYYYMMDD date, a YYYYMMD-
	     DHHMM[SS] time, a relative	time starting with a plus character or
	     the string	"forever" to indicate that the certificate has no ex-
	     piry date.

	     For example: "+52w1d" (valid from now to 52 weeks and one day
	     from now),	"-4w:+4w" (valid from four weeks ago to	four weeks
	     from now),	"20100101123000:20110101123000"	(valid from 12:30 PM,
	     January 1st, 2010 to 12:30	PM, January 1st, 2011),	"-1d:20110101"
	     (valid from yesterday to midnight,	January	1st, 2011),
	     "-1m:forever" (valid from one minute ago and never	expiring).

     -v	     Verbose mode.  Causes ssh-keygen to print debugging messages
	     about its progress.  This is helpful for debugging	moduli genera-
	     tion.  Multiple -v	options	increase the verbosity.	 The maximum
	     is	3.

     -w	provider
	     Specifies a path to a library that	will be	used when creating
	     FIDO authenticator-hosted keys, overriding	the default of using
	     the internal USB HID support.

     -Y	find-principals
	     Find the principal(s) associated with the public key of a signa-
	     ture, provided using the -s flag in an authorized signers file
	     provided using the	-f flag.  The format of	the allowed signers
	     file is documented	in the ALLOWED SIGNERS section below.  If one
	     or	more matching principals are found, they are returned on stan-
	     dard output.

     -Y	check-novalidate
	     Checks that a signature generated using ssh-keygen	-Y sign	has a
	     valid structure.  This does not validate if a signature comes
	     from an authorized	signer.	 When testing a	signature, ssh-keygen
	     accepts a message on standard input and a signature namespace us-
	     ing -n.  A	file containing	the corresponding signature must also
	     be	supplied using the -s flag.  Successful	testing	of the signa-
	     ture is signalled by ssh-keygen returning a zero exit status.

     -Y	sign
	     Cryptographically sign a file or some data	using a	SSH key.  When
	     signing, ssh-keygen accepts zero or more files to sign on the
	     command-line - if no files	are specified then ssh-keygen will
	     sign data presented on standard input.  Signatures	are written to
	     the path of the input file	with ".sig" appended, or to standard
	     output if the message to be signed	was read from standard input.

	     The key used for signing is specified using the -f	option and may
	     refer to either a private key, or a public	key with the private
	     half available via	ssh-agent(1).  An additional signature name-
	     space, used to prevent signature confusion	across different do-
	     mains of use (e.g.	file signing vs	email signing) must be pro-
	     vided via the -n flag.  Namespaces	are arbitrary strings, and may
	     include: "file" for file signing, "email" for email signing.  For
	     custom uses, it is	recommended to use names following a NAME-
	     SPACE@YOUR.DOMAIN pattern to generate unambiguous namespaces.

     -Y	verify
	     Request to	verify a signature generated using ssh-keygen -Y sign
	     as	described above.  When verifying a signature, ssh-keygen ac-
	     cepts a message on	standard input and a signature namespace using
	     -n.  A file containing the	corresponding signature	must also be
	     supplied using the	-s flag, along with the	identity of the	signer
	     using -I and a list of allowed signers via	the -f flag.  The for-
	     mat of the	allowed	signers	file is	documented in the ALLOWED
	     SIGNERS section below.  A file containing revoked keys can	be
	     passed using the -r flag.	The revocation file may	be a KRL or a
	     one-per-line list of public keys.	Successful verification	by an
	     authorized	signer is signalled by ssh-keygen returning a zero
	     exit status.

     -y	     This option will read a private OpenSSH format file and print an
	     OpenSSH public key	to stdout.

     -Z	cipher
	     Specifies the cipher to use for encryption	when writing an
	     OpenSSH-format private key	file.  The list	of available ciphers
	     may be obtained using "ssh	-Q cipher".  The default is
	     "aes256-ctr".

     -z	serial_number
	     Specifies a serial	number to be embedded in the certificate to
	     distinguish this certificate from others from the same CA.	 If
	     the serial_number is prefixed with	a `+' character, then the se-
	     rial number will be incremented for each certificate signed on a
	     single command-line.  The default serial number is	zero.

	     When generating a KRL, the	-z flag	is used	to specify a KRL ver-
	     sion number.

MODULI GENERATION
     ssh-keygen	may be used to generate	groups for the Diffie-Hellman Group
     Exchange (DH-GEX) protocol.  Generating these groups is a two-step
     process: first, candidate primes are generated using a fast, but memory
     intensive process.	 These candidate primes	are then tested	for suitabil-
     ity (a CPU-intensive process).

     Generation	of primes is performed using the -M generate option.  The de-
     sired length of the primes	may be specified by the	-O bits	option.	 For
     example:

	   # ssh-keygen	-M generate -O bits=2048 moduli-2048.candidates

     By	default, the search for	primes begins at a random point	in the desired
     length range.  This may be	overridden using the -O	start option, which
     specifies a different start point (in hex).

     Once a set	of candidates have been	generated, they	must be	screened for
     suitability.  This	may be performed using the -M screen option.  In this
     mode ssh-keygen will read candidates from standard	input (or a file spec-
     ified using the -f	option).  For example:

	   # ssh-keygen	-M screen -f moduli-2048.candidates moduli-2048

     By	default, each candidate	will be	subjected to 100 primality tests.
     This may be overridden using the -O prime-tests option.  The DH generator
     value will	be chosen automatically	for the	prime under consideration.  If
     a specific	generator is desired, it may be	requested using	the -O
     generator option.	Valid generator	values are 2, 3, and 5.

     Screened DH groups	may be installed in /etc/moduli.  It is	important that
     this file contains	moduli of a range of bit lengths.

     A number of options are available for moduli generation and screening via
     the -O flag:

     lines=number
	     Exit after	screening the specified	number of lines	while perform-
	     ing DH candidate screening.

     start-line=line-number
	     Start screening at	the specified line number while	performing DH
	     candidate screening.

     checkpoint=filename
	     Write the last line processed to the specified file while per-
	     forming DH	candidate screening.  This will	be used	to skip	lines
	     in	the input file that have already been processed	if the job is
	     restarted.

     memory=mbytes
	     Specify the amount	of memory to use (in megabytes)	when generat-
	     ing candidate moduli for DH-GEX.

     start=hex-value
	     Specify start point (in hex) when generating candidate moduli for
	     DH-GEX.

     generator=value
	     Specify desired generator (in decimal) when testing candidate
	     moduli for	DH-GEX.

CERTIFICATES
     ssh-keygen	supports signing of keys to produce certificates that may be
     used for user or host authentication.  Certificates consist of a public
     key, some identity	information, zero or more principal (user or host)
     names and a set of	options	that are signed	by a Certification Authority
     (CA) key.	Clients	or servers may then trust only the CA key and verify
     its signature on a	certificate rather than	trusting many user/host	keys.
     Note that OpenSSH certificates are	a different, and much simpler, format
     to	the X.509 certificates used in ssl(8).

     ssh-keygen	supports two types of certificates: user and host.  User cer-
     tificates authenticate users to servers, whereas host certificates	au-
     thenticate	server hosts to	users.	To generate a user certificate:

	   $ ssh-keygen	-s /path/to/ca_key -I key_id /path/to/user_key.pub

     The resultant certificate will be placed in /path/to/user_key-cert.pub.
     A host certificate	requires the -h	option:

	   $ ssh-keygen	-s /path/to/ca_key -I key_id -h	/path/to/host_key.pub

     The host certificate will be output to /path/to/host_key-cert.pub.

     It	is possible to sign using a CA key stored in a PKCS#11 token by	pro-
     viding the	token library using -D and identifying the CA key by providing
     its public	half as	an argument to -s:

	   $ ssh-keygen	-s ca_key.pub -D libpkcs11.so -I key_id	user_key.pub

     Similarly,	it is possible for the CA key to be hosted in a	ssh-agent(1).
     This is indicated by the -U flag and, again, the CA key must be identi-
     fied by its public	half.

	   $ ssh-keygen	-Us ca_key.pub -I key_id user_key.pub

     In	all cases, key_id is a "key identifier"	that is	logged by the server
     when the certificate is used for authentication.

     Certificates may be limited to be valid for a set of principal
     (user/host) names.	 By default, generated certificates are	valid for all
     users or hosts.  To generate a certificate	for a specified	set of princi-
     pals:

	   $ ssh-keygen	-s ca_key -I key_id -n user1,user2 user_key.pub
	   $ ssh-keygen	-s ca_key -I key_id -h -n host.domain host_key.pub

     Additional	limitations on the validity and	use of user certificates may
     be	specified through certificate options.	A certificate option may dis-
     able features of the SSH session, may be valid only when presented	from
     particular	source addresses or may	force the use of a specific command.

     The options that are valid	for user certificates are:

     clear   Clear all enabled permissions.  This is useful for	clearing the
	     default set of permissions	so permissions may be added individu-
	     ally.

     critical:name[=contents]
     extension:name[=contents]
	     Includes an arbitrary certificate critical	option or extension.
	     The specified name	should include a domain	suffix,	e.g.
	     "name@example.com".  If contents is specified then	it is included
	     as	the contents of	the extension/option encoded as	a string, oth-
	     erwise the	extension/option is created with no contents (usually
	     indicating	a flag).  Extensions may be ignored by a client	or
	     server that does not recognise them, whereas unknown critical op-
	     tions will	cause the certificate to be refused.

     force-command=command
	     Forces the	execution of command instead of	any shell or command
	     specified by the user when	the certificate	is used	for authenti-
	     cation.

     no-agent-forwarding
	     Disable ssh-agent(1) forwarding (permitted	by default).

     no-port-forwarding
	     Disable port forwarding (permitted	by default).

     no-pty  Disable PTY allocation (permitted by default).

     no-user-rc
	     Disable execution of ~/.ssh/rc by sshd(8) (permitted by default).

     no-x11-forwarding
	     Disable X11 forwarding (permitted by default).

     permit-agent-forwarding
	     Allows ssh-agent(1) forwarding.

     permit-port-forwarding
	     Allows port forwarding.

     permit-pty
	     Allows PTY	allocation.

     permit-user-rc
	     Allows execution of ~/.ssh/rc by sshd(8).

     permit-X11-forwarding
	     Allows X11	forwarding.

     no-touch-required
	     Do	not require signatures made using this key include demonstra-
	     tion of user presence (e.g. by having the user touch the authen-
	     ticator).	This option only makes sense for the FIDO authentica-
	     tor algorithms ecdsa-sk and ed25519-sk.

     source-address=address_list
	     Restrict the source addresses from	which the certificate is con-
	     sidered valid.  The address_list is a comma-separated list	of one
	     or	more address/netmask pairs in CIDR format.

     verify-required
	     Require signatures	made using this	key indicate that the user was
	     first verified.  This option only makes sense for the FIDO	au-
	     thenticator algorithms ecdsa-sk and ed25519-sk.  Currently	PIN
	     authentication is the only	supported verification method, but
	     other methods may be supported in the future.

     At	present, no standard options are valid for host	keys.

     Finally, certificates may be defined with a validity lifetime.  The -V
     option allows specification of certificate	start and end times.  A	cer-
     tificate that is presented	at a time outside this range will not be con-
     sidered valid.  By	default, certificates are valid	from the UNIX Epoch to
     the distant future.

     For certificates to be used for user or host authentication, the CA pub-
     lic key must be trusted by	sshd(8)	or ssh(1).  Please refer to those man-
     ual pages for details.

KEY REVOCATION LISTS
     ssh-keygen	is able	to manage OpenSSH format Key Revocation	Lists (KRLs).
     These binary files	specify	keys or	certificates to	be revoked using a
     compact format, taking as little as one bit per certificate if they are
     being revoked by serial number.

     KRLs may be generated using the -k	flag.  This option reads one or	more
     files from	the command line and generates a new KRL.  The files may ei-
     ther contain a KRL	specification (see below) or public keys, listed one
     per line.	Plain public keys are revoked by listing their hash or con-
     tents in the KRL and certificates revoked by serial number	or key ID (if
     the serial	is zero	or not available).

     Revoking keys using a KRL specification offers explicit control over the
     types of record used to revoke keys and may be used to directly revoke
     certificates by serial number or key ID without having the	complete orig-
     inal certificate on hand.	A KRL specification consists of	lines contain-
     ing one of	the following directives followed by a colon and some direc-
     tive-specific information.

     serial: serial_number[-serial_number]
	     Revokes a certificate with	the specified serial number.  Serial
	     numbers are 64-bit	values,	not including zero and may be ex-
	     pressed in	decimal, hex or	octal.	If two serial numbers are
	     specified separated by a hyphen, then the range of	serial numbers
	     including and between each	is revoked.  The CA key	must have been
	     specified on the ssh-keygen command line using the	-s option.

     id: key_id
	     Revokes a certificate with	the specified key ID string.  The CA
	     key must have been	specified on the ssh-keygen command line using
	     the -s option.

     key: public_key
	     Revokes the specified key.	 If a certificate is listed, then it
	     is	revoked	as a plain public key.

     sha1: public_key
	     Revokes the specified key by including its	SHA1 hash in the KRL.

     sha256: public_key
	     Revokes the specified key by including its	SHA256 hash in the
	     KRL.  KRLs	that revoke keys by SHA256 hash	are not	supported by
	     OpenSSH versions prior to 7.9.

     hash: fingerprint
	     Revokes a key using a fingerprint hash, as	obtained from a
	     sshd(8) authentication log	message	or the ssh-keygen -l flag.
	     Only SHA256 fingerprints are supported here and resultant KRLs
	     are not supported by OpenSSH versions prior to 7.9.

     KRLs may be updated using the -u flag in addition to -k.  When this op-
     tion is specified,	keys listed via	the command line are merged into the
     KRL, adding to those already there.

     It	is also	possible, given	a KRL, to test whether it revokes a particular
     key (or keys).  The -Q flag will query an existing	KRL, testing each key
     specified on the command line.  If	any key	listed on the command line has
     been revoked (or an error encountered) then ssh-keygen will exit with a
     non-zero exit status.  A zero exit	status will only be returned if	no key
     was revoked.

ALLOWED	SIGNERS
     When verifying signatures,	ssh-keygen uses	a simple list of identities
     and keys to determine whether a signature comes from an authorized
     source.  This "allowed signers" file uses a format	patterned after	the
     AUTHORIZED_KEYS FILE FORMAT described in sshd(8).	Each line of the file
     contains the following space-separated fields: principals,	options, key-
     type, base64-encoded key.	Empty lines and	lines starting with a `#' are
     ignored as	comments.

     The principals field is a pattern-list (see PATTERNS in ssh_config(5))
     consisting	of one or more comma-separated USER@DOMAIN identity patterns
     that are accepted for signing.  When verifying, the identity presented
     via the -I	option must match a principals pattern in order	for the	corre-
     sponding key to be	considered acceptable for verification.

     The options (if present) consist of comma-separated option	specifica-
     tions.  No	spaces are permitted, except within double quotes.  The	fol-
     lowing option specifications are supported	(note that option keywords are
     case-insensitive):

     cert-authority
	     Indicates that this key is	accepted as a certificate authority
	     (CA) and that certificates	signed by this CA may be accepted for
	     verification.

     namespaces=namespace-list
	     Specifies a pattern-list of namespaces that are accepted for this
	     key.  If this option is present, the signature namespace embedded
	     in	the signature object and presented on the verification com-
	     mand-line must match the specified	list before the	key will be
	     considered	acceptable.

     valid-after=timestamp
	     Indicates that the	key is valid for use at	or after the specified
	     timestamp,	which may be a date in YYYYMMDD	format or a time in
	     YYYYMMDDHHMM[SS] format.

     valid-before=timestamp
	     Indicates that the	key is valid for use at	or before the speci-
	     fied timestamp.

     When verifying signatures made by certificates, the expected principal
     name must match both the principals pattern in the	allowed	signers	file
     and the principals	embedded in the	certificate itself.

     An	example	allowed	signers	file:

	# Comments allowed at start of line
	user1@example.com,user2@example.com ssh-rsa AAAAX1...
	# A certificate	authority, trusted for all principals in a domain.
	*@example.com cert-authority ssh-ed25519 AAAB4...
	# A key	that is	accepted only for file signing.
	user2@example.com namespaces="file" ssh-ed25519	AAA41...

ENVIRONMENT
     SSH_SK_PROVIDER
	     Specifies a path to a library that	will be	used when loading any
	     FIDO authenticator-hosted keys, overriding	the default of using
	     the built-in USB HID support.

FILES
     ~/.ssh/id_dsa
     ~/.ssh/id_ecdsa
     ~/.ssh/id_ecdsa_sk
     ~/.ssh/id_ed25519
     ~/.ssh/id_ed25519_sk
     ~/.ssh/id_rsa
	     Contains the DSA, ECDSA, authenticator-hosted ECDSA, Ed25519, au-
	     thenticator-hosted	Ed25519	or RSA authentication identity of the
	     user.  This file should not be readable by	anyone but the user.
	     It	is possible to specify a passphrase when generating the	key;
	     that passphrase will be used to encrypt the private part of this
	     file using	128-bit	AES.  This file	is not automatically accessed
	     by	ssh-keygen but it is offered as	the default file for the pri-
	     vate key.	ssh(1) will read this file when	a login	attempt	is
	     made.

     ~/.ssh/id_dsa.pub
     ~/.ssh/id_ecdsa.pub
     ~/.ssh/id_ecdsa_sk.pub
     ~/.ssh/id_ed25519.pub
     ~/.ssh/id_ed25519_sk.pub
     ~/.ssh/id_rsa.pub
	     Contains the DSA, ECDSA, authenticator-hosted ECDSA, Ed25519, au-
	     thenticator-hosted	Ed25519	or RSA public key for authentication.
	     The contents of this file should be added to
	     ~/.ssh/authorized_keys on all machines where the user wishes to
	     log in using public key authentication.  There is no need to keep
	     the contents of this file secret.

     /etc/moduli
	     Contains Diffie-Hellman groups used for DH-GEX.  The file format
	     is	described in moduli(5).

SEE ALSO
     ssh(1), ssh-add(1), ssh-agent(1), moduli(5), sshd(8)

     The Secure	Shell (SSH) Public Key File Format, RFC	4716, 2006.

AUTHORS
     OpenSSH is	a derivative of	the original and free ssh 1.2.12 release by
     Tatu Ylonen.  Aaron Campbell, Bob Beck, Markus Friedl, Niels Provos, Theo
     de	Raadt and Dug Song removed many	bugs, re-added newer features and cre-
     ated OpenSSH.  Markus Friedl contributed the support for SSH protocol
     versions 1.5 and 2.0.

FreeBSD	13.0			August 11, 2021			  FreeBSD 13.0

NAME | SYNOPSIS | DESCRIPTION | MODULI GENERATION | CERTIFICATES | KEY REVOCATION LISTS | ALLOWED SIGNERS | ENVIRONMENT | FILES | SEE ALSO | AUTHORS

Want to link to this manual page? Use this URL:
<https://www.freebsd.org/cgi/man.cgi?query=ssh-keygen&sektion=1&manpath=FreeBSD+13.1-RELEASE+and+Ports>home | help

Skip site navigation (1)Skip section navigation (2)

FreeBSD

Donate to FreeBSD

FreeBSD Manual Pages

home | help


MODULI(5)		  FreeBSD File Formats Manual		     MODULI(5)

NAME
     moduli -- Diffie-Hellman moduli

DESCRIPTION
     The /etc/ssh/moduli file contains prime numbers and generators for	use by
     sshd(8) in	the Diffie-Hellman Group Exchange key exchange method.

     New moduli	may be generated with ssh-keygen(1) using a two-step process.
     An	initial	candidate generation pass, using ssh-keygen -G,	calculates
     numbers that are likely to	be useful.  A second primality testing pass,
     using ssh-keygen -T, provides a high degree of assurance that the numbers
     are prime and are safe for	use in Diffie-Hellman operations by sshd(8).
     This moduli format	is used	as the output from each	pass.

     The file consists of newline-separated records, one per modulus, contain-
     ing seven space-separated fields.	These fields are as follows:

	   timestamp	The time that the modulus was last processed as	YYYYM-
			MDDHHMMSS.

	   type		Decimal	number specifying the internal structure of
			the prime modulus.  Supported types are:

			0     Unknown, not tested.
			2     "Safe" prime; (p-1)/2 is also prime.
			4     Sophie Germain; 2p+1 is also prime.

			Moduli candidates initially produced by	ssh-keygen(1)
			are Sophie Germain primes (type	4).  Further primality
			testing	with ssh-keygen(1) produces safe prime moduli
			(type 2) that are ready	for use	in sshd(8).  Other
			types are not used by OpenSSH.

	   tests	Decimal	number indicating the type of primality	tests
			that the number	has been subjected to represented as a
			bitmask	of the following values:

			0x00  Not tested.
			0x01  Composite	number - not prime.
			0x02  Sieve of Eratosthenes.
			0x04  Probabilistic Miller-Rabin primality tests.

			The ssh-keygen(1) moduli candidate generation uses the
			Sieve of Eratosthenes (flag 0x02).  Subsequent
			ssh-keygen(1) primality	tests are Miller-Rabin tests
			(flag 0x04).

	   trials	Decimal	number indicating the number of	primality tri-
			als that have been performed on	the modulus.

	   size		Decimal	number indicating the size of the prime	in
			bits.

	   generator	The recommended	generator for use with this modulus
			(hexadecimal).

	   modulus	The modulus itself in hexadecimal.

     When performing Diffie-Hellman Group Exchange, sshd(8) first estimates
     the size of the modulus required to produce enough	Diffie-Hellman output
     to	sufficiently key the selected symmetric	cipher.	 sshd(8) then randomly
     selects a modulus from /etc/ssh/moduli that best meets the	size require-
     ment.

SEE ALSO
     ssh-keygen(1), sshd(8)

     Diffie-Hellman Group Exchange for the Secure Shell	(SSH) Transport	Layer
     Protocol, RFC 4419, 2006.

FreeBSD	13.0			 July 19, 2012			  FreeBSD 13.0

NAME | DESCRIPTION | SEE ALSO

Want to link to this manual page? Use this URL:
<https://www.freebsd.org/cgi/man.cgi?query=moduli&sektion=5&manpath=FreeBSD+13.1-RELEASE+and+Ports>home | help


Legal Notices | © 1995-2022 The FreeBSD Project. All rights reserved.
Contact

How to Set Up SSH Keys on CentOS 8

Last Updated: Fri, Mar 13, 2020 CentOS Linux Guides System Admin

Introduction

This guide explains how to create SSH keys, add the public key to your CentOS 8 server, and configure sshd for passwordless login. The IP address 192.0.2.123 is an example.

1. Create an SSH key pair

Create an SSH key pair on your computer with ssh-keygen.

$ ssh-keygen 

After running this command, you should see the following prompt:

Output
Generating public/private rsa key pair.
Enter file in which to save the key (/your_home/.ssh/id_rsa):

Press ENTER to save this SSH key pair into the ./ssh subdirectory of your home directory, or specify an alternate path if you want.

After this you should see the following output:

Output
Your identification has been saved in ~/.ssh/id_rsa.
Your public key has been saved in ~/.ssh/id_rsa.pub.
The key fingerprint is:
your_fingerprint_key username@remote_host
The key's randomart image is:
+--[ RSA 2048]----+
|     ..o         |
|   E o= .        |
|    o. o         |
|        ..       |
|      ..S        |
|     o o.        |
|   =o.+.         |
|. =++..          |
|o=++.            |
+-----------------+

You have created a public and private key pair. To view your public key:

$ cat ~/.ssh/id_rsa.pub

You will see a very long string that starts with ssh-rsa.

2. Add SSH key to CentOS server

SSH to the server and create the .ssh directory, if it doesn’t already exist:

$ mkdir -p ~/.ssh

Add the public key from step 1 to ~/.ssh/authorized_keys. Replace public_key with the contents of id_rsa.pub from step 1.

$ echo public_key >> ~/.ssh/authorized_keys

Log out of the server, then log back in:

$ ssh root@192.0.2.123

You will be prompted for your server root password.

3. Disable Password Authentication

Your SSH key-based authentication is configured, but password authentication is still active. To change this you need to make some changes to the file sshd_config which is located in /etc/ssh directory. You can open that file with this command:

sudo vi /etc/ssh/sshd_config

In the file, you need to find and change several lines Permit Root Login should be set to yes

...
PermitRootLogin   yes
...

Password Authentication should be set to no

...
PasswordAuthentication  no
...

Challenge-Response Authentication should be set to no

...
ChallengeResponseAuthentication  no
...  

Using of Password Authentication Method (PAM) should be set to yes

...
UsePAM yes
...

After making these changes, press ESC and then :WQ. For this change to take effect, restart the sshd service:

sudo systemctl restart sshd.service

Before closing your terminal, open a new terminal window and run this command

ssh root@192.0.2.123

You should connect to the server without a password. SSH-based authentication is successfully configured and password authentication is disabled.

по – русски

Описание параметров файла конфигурации sshd config

sshd config это файл конфигурации SSH-сервера openssh-server.
Обычное местоположение файла /etc/ssh/sshd_config, но может быть указано и другое в параметрах запуска программы.

Описание параметров

  Port                        ПОРТ
       порт на котором создаётся сервера, по умолчанию 22
  ListenAddress               АДРЕС
       указание адреса на котором создаётся сервер, по умолчанию сервер принимает подключения на всех сетевых интерфейсах.
       Возможные варианты
          ListenAddress ::
          ListenAddress 0.0.0.0                - создание на всех IP4 адресах
          ListenAddress 192.168.0.1            - создание только на одном сетевом интерфёйсе
          ListenAddress 192.168.10.0:48675     - создание только на одном сетевом интерфейсе вместе с портом
  Protocol                    2
       указание версии протокола SSH, по умолчанию 2
       Внимание! Первая версия протокола SSH небезопасна!
  HostKey                     /etc/ssh/ssh_host_rsa_key
  HostKey                     /etc/ssh/ssh_host_dsa_key
       (для версии протокола 2) указание названия файлов RSA/DSA ключей и их расположение.
  UsePrivilegeSeparation      yes
     установка разделения привилегий.
     Если указано yes - то сначала создаётся непривилегированный дочерний процесс для входящего сетевого трафика.
     После успешной авторизации запускается другой процесс с привилегиями вошедшего пользователя.
     Основная цель разделения привилегий - предотвращение превышения прав доступа.
  KeyRegenerationInterval     3600
     (для версии протокола 1) установка временного ключа
  ServerKeyBits               768
     (для версии протокола 1) установка длины ключа
  SyslogFacility              AUTH
     установка типа событий для записи в журнал (/var/log/auth.log)
     Доступны следующие значения: DAEMON, USER, AUTH, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7, где
         AUTH - авторизация на сервере
  LogLevel                    INFO
     установка детализации событий для записи в журнал (/var/log/auth.log), по умолчанию INFO
     Доступны следующие события: SILENT, QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, DEBUG3.
  LoginGraceTime              120
     установка времени разрыва соединения в секундах, если пользователь не осущствит авторизацию, по умолчанию 120 сек
  PermitRootLogin             without-password
     установка разрешения для авторизации суперпользователя
     Доступны следующие значения:
        yes                  - вход суперпользователю разрешён, параметр по умолчанию
        no                   - вход суперпользователю запрещён
        without-password     - авторизация суперпользователя по паролю отключена (но возможна по открытому ключу)
        forced-commands-only - вход суперпользователю по открытому ключу разрешён, но только для выполнения команды
                               (указанному в AuthorizedKeysFile ?!)
  StrictModes                 yes
     установка проверки у пользователя прав на владение пользовательскими файлами и домашним каталогом перед разращением входа
  AllowUsers                  user1 user2 ...
     установка разрешения доступа к серверу по протоколу SSH только для перечисленных пользователей.
     Значениями этого параметра могут выступать имена пользователей (не UID!), отделённые друг от друга пробелами.
     Допускается использование записи вида user@host, что означает разрешёние доступа пользователю user с компьютера host.
     Причём пользователь и компьютер проверяются отдельно, то естть доступ может быть разрешён только
     определенным пользователям с определенных компьютеров.
  DenyUsers                   user1 user2 ...
     установка запрета доступа к серверу по протоколу SSH для перечисленных пользователей.
     Правила формирования имён такие же как у AllowUsers
  AllowGroups                 user1 user2 ...
     установка разрешения доступа к серверу по протоколу SSH только для перечисленных групп пользователей.
  DenyGroups                  user1 user2 ...
     установка запрета доступа к серверу по протоколу SSH для перечисленных групп пользователей.
  RSAAuthentication           yes
     установка типа аутентификации RSA
  PubkeyAuthentication        yes
     включение аутентификации по открытому ключу
  AuthorizedKeysFile          .ssh/authorized_keys
     указание имени файла, в котором содержатся публичные ключи, используемые для аутентификации пользователей по открытому ключу.
     В записи могут присутствовать записи в форме %T, которые заменяются в момент установки соединения, например
     %% заменяется на %, %h означает домашний каталог пользователя,а %u – имя пользователя.
     По умолчанию ".ssh/authorized_keys .ssh/authorized_keys2".
  IgnoreRhosts                yes
     установка игнорирования параметров пользователя из файлов ~/.rhosts and ~/.shosts
     (параметр для совместимости с программой rhosts)
  RhostsRSAAuthentication     no
     включение поддержки аутентификации RSA для rhosts.
     Для работы этого параметра ключи узла должны быть присоединены в /etc/ssh_known_hosts
     (параметр для совместимости с программой rhosts)
  HostbasedAuthentication     no
     включение поддержки аутентификации Hostbased для rhosts.
     (параметр для совместимости с программой rhosts)
  IgnoreUserKnownHosts        yes
     установка игнорирования пользовательскому  ~/.ssh/known_hosts для  RhostsRSAAuthentication
     (параметр для совместимости с программой rhosts)
  PermitEmptyPasswords        no
     установка разрешения входа с пустым паролем.
  ChallengeResponseAuthentication no
     включение PAM интерфейса при авторизации.
     Если задано значение yes, то для всех типов аутентификации помимо обработки модуля сессии и аккаунта PAM,
     будет использоваться аутентификация на основе запроса-ответа (ChallengeResponseAuthentication и PasswordAuthentication).
  PasswordAuthentication      yes
     включение авторизации по паролю.
     Альтернатива аутентификации по ключу хоста.
  Параметры, отвечающие за аутентификацию Kerberos
     #KerberosAuthentication no
     #KerberosGetAFSToken no
     #KerberosOrLocalPasswd yes
     #KerberosTicketCleanup yes
  Параметры, отвечающие за аутентификацию GSSAPI
     #GSSAPIAuthentication no
     #GSSAPICleanupCredentials yes
  X11Forwarding               yes
     установка разрешения перенаправления портов X-системы через ssh-туннель
     Будет работать, если на сервере установлен XServer.
  X11DisplayOffset            10
     установка смещения дисплеев X11 при пробросе портов X-системы через ssh туннель
     Будет работать, если на сервере включён X11Forwarding
  PrintMotd                   no
     включение вывода при создании ssh-сессии информационного сообщения из файла /etc/motd.
  PrintLastLog                yes
     включение добавления к сообщению, установленному параметром PrintMotd, информации о том, когда в последний раз
     и с какого компьютера осуществлялся вход на сервер.
  TCPKeepAlive                yes
     включение поддержания соединения со стороны сервера.
     Внимание! возможно безопасней будет реализация данной функции вручную с помощью параметров
     ClientAliveCountMax и ClientAliveInterval, как указано ниже.
  ClientAliveCountMax         3
     установка количества запросов, которое ssh-сервер отправляет ssh-клиентам через определённые промежутки времени.
     Как только установленное значение запросов достигнуто, а клиент так и не ответил, соединение разрывается.
     Если этого делать, то сессии на сервере будут длиться бесконечно, отбирая его ресурсы.
  ClientAliveInterval         20
     установка интервала отправки запросов ClientAliveCountMax в секундах.
  UseLogin                    no
     установка использования login для интерактивных сессий, значение по умолчанию no.
  MaxStartups                 start:rate:full
     установка количества неавторизованных подключений к серверу ssh, по умолчанию значение данного параметра 10.
     Длительность такого подключения определяется параметром LoginGraceTime.
     Формат записи может быть представлен виде start:rate:full, где
        start – это уже имеющееся количество неавторизованных подключений,
        rate – процент вероятности отклонения попытки подключения,
        full – максимальное количество неавторизованных соединений.
     Например запись в виде
        MaxStartups              2:30:7
     устанавливает что, если уже имеется 2 неавторизованных подключения, то следующее подключение будет отклонено с вероятностью
     30%, а если количество неавторизованных подключений достигнет 7, то все последующие попытки подключения будут отвергнуты.
  Banner                      /etc/issue.net
     установка местоположения файла-баннера, который будет выведен на экран, при попытке подключиться к серверу sshd.
     В Debian по умолчанию параметр имеет значение /etc/motd.tail.
  DebianBanner                no
     включение в строку ответа sshd при обращению к серверу по протоколу TELNET или при сканировании nmap
     информации об операционной системе.
  AcceptEnv                   LANG LC_*
     установка переменных окружения, которые будут переданы клиенту
  Subsystem                   sftp /usr/lib/openssh/sftp-server
     включение внешней подсистемы (например, FTP).
     В качестве параметров передаются имя подсистемы и команда, которая будет выполнена при запросе подсистемы.
     Команда sftp-server, реализует протокол передачи файлов через SSH - SFTP.
  UsePAM                      yes
     установка разрешений на запуск sshd.
     Например если параметр UsePAM включён, то запустить sshd можно будет только от имени root.

пример

#       $OpenBSD: sshd_config,v 1.103 2018/04/09 20:41:22 tj Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

Include /etc/ssh/sshd_config.d/*.conf

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
PermitRootLogin yes
# do not check file permission
## StrictModes #############################################
#                                                          #
# Указывает должен ли sshd проверить режимы доступа и      #
# владения пользовательских папок и файлов перед тем, как  #
# дать пользователю войти. Обычно это объясняется тем, что #
# новички часто делают свои файлы доступными для записи    #
# всем подряд.По умолчанию - “yes”.                        #
#                                                          #
StrictModes no
#        Sep  5 23:45:33 belosnezhka sshd[981]: Server listening on 0.0.0.0 port 22.
#Sep  5 23:45:48 belosnezhka sshd[1384]: Authentication refused: bad ownership or modes for directory /root
#Sep  5 23:45:53 belosnezhka sshd[1384]: Connection closed by authenticating user root 83.167.105.127 port 41556 [preauth]
#  включать только если права на каталог root или другого пользователя не 700 или его использует несколько пользователей например служба почты postfix. есть риск взлома или просмотра данных.
                              
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# Expect .ssh/authorized_keys2 to be disregarded by default in future.
#AuthorizedKeysFile     .ssh/authorized_keys .ssh/authorized_keys2

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
#PrintLastLog yes
#TCPKeepAlive yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

# override default of no subsystems
Subsystem       sftp    /usr/lib/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       PermitTTY no
#       ForceCommand cvs server

смотрим журнал secure – это прошло соединение по открытому ключу. Лучше пароль не набирать так как интернет открытый, подключился кто к провайдеру и слушает весь трафик, а пароли идут открытым текстом. Для этого и придумали ключи.

Sep 6 11:10:08 belosnezhka sshd[6439]: Accepted publickey for www from 83.167.105.127 port 41610 ssh2: RSA SHA256:4tcF6xa9ZbMpvRYrTYaj2pUtUjq6n9jLSX9thL7jWVs
Sep 6 11:10:08 belosnezhka sshd[6439]: pam_unix(sshd:session): session opened for user www by (uid=0)
Sep 6 11:10:11 belosnezhka sshd[6441]: Received disconnect from 83.167.105.127 port 41610:11: disconnected by user

(chmod 500 /root ; chown root:root * ; chmod 700 .ssh ; chmod 644 known_hosts ; chmod 644 id_rsa.pub ; chmod 600 .ssh/authorized_keys ; chmod 600 id_rsa; )

  UsePAM                      yes
     установка разрешений на запуск sshd.
     Например если параметр UsePAM включён, то запустить sshd можно будет только от имени root. * не совсем так все прописано в файле pam.d sshd

#%PAM-1.0
auth<-->   required<--->pam_sepermit.so
auth       include      password-auth
account    required     pam_nologin.so
account    include      password-auth
password   include      password-auth
# pam_selinux.so close should be the first session rule
session    required     pam_selinux.so close
session    required     pam_loginuid.so
# pam_selinux.so open should only be followed by sessions to be executed in the user context
session    required     pam_selinux.so open env_params
session    required     pam_namespace.so
session    optional     pam_keyinit.so force revoke
session    include      password-auth
session    include      postlogin
# Used with polkit to reauthorize users in remote sessions
-session   optional     pam_reauthorize.so prepare

system-auth

#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authselect is run.
auth        required      pam_env.so
auth        required      pam_faildelay.so delay=2000000
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
-session     optional      pam_systemd.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so


read more (learn Russian) http://mydebianblog.blogspot.com/2006/12/ssh.html

еще https://help.ubuntu.ru/wiki/ssh