美文网首页
Security中的GPG用法 - TechLead 正式接程序

Security中的GPG用法 - TechLead 正式接程序

作者: Zhoueeer | 来源:发表于2021-03-17 17:34 被阅读0次

我一直以来就想做一个代码帮助类型的网站,今天终于完成了。


课程作业面试辅导
V: aplg6666

简介

GPGGNU Privacy Guard的简写,是GNUPGP技术的实现。PGPPretty Good Privacy的简写,是一套用于加密的软件。

PGP加密过程如下(来自维基百科 PGP):

image.png
PGP同时利用了对称加密和非对称加密,对文件内容的加密用的是对称加密,对称加密的密钥是每次加密时生成的。由于对称密钥要随密文一起传输,采用了非对称加密算法给对称密钥进行了加密。

GPG的安装

linux版本

以 CentOS为例:

$ sudo yum install gpg

或者

$ sudo yum install gnupg

安装成功后,运行 gpg -h测试下:

$ gpg -h
gpg (GnuPG) 2.0.22
libgcrypt 1.5.3
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Home: ~/.gnupg
Supported algorithms:
Pubkey: RSA, ?, ?, ELG, DSA
Cipher: IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, AES256, TWOFISH,
        CAMELLIA128, CAMELLIA192, CAMELLIA256
Hash: MD5, SHA1, RIPEMD160, SHA256, SHA384, SHA512, SHA224
Compression: Uncompressed, ZIP, ZLIB, BZIP2

Syntax: gpg [options] [files]
Sign, check, encrypt or decrypt
Default operation depends on the input data

Commands:

 -s, --sign                 make a signature
     --clearsign            make a clear text signature
 -b, --detach-sign          make a detached signature
 -e, --encrypt              encrypt data
 -c, --symmetric            encryption only with symmetric cipher
 -d, --decrypt              decrypt data (default)
     --verify               verify a signature
 -k, --list-keys            list keys
     --list-sigs            list keys and signatures
     --check-sigs           list and check key signatures
     --fingerprint          list keys and fingerprints
 -K, --list-secret-keys     list secret keys
     --gen-key              generate a new key pair
     --gen-revoke           generate a revocation certificate
     --delete-keys          remove keys from the public keyring
     --delete-secret-keys   remove keys from the secret keyring
     --sign-key             sign a key
     --lsign-key            sign a key locally
     --edit-key             sign or edit a key
     --passwd               change a passphrase
     --export               export keys
     --send-keys            export keys to a key server
     --recv-keys            import keys from a key server
     --search-keys          search for keys on a key server
     --refresh-keys         update all keys from a keyserver
     --import               import/merge keys
     --card-status          print the card status
     --card-edit            change data on a card
     --change-pin           change a card's PIN
     --update-trustdb       update the trust database
     --print-md             print message digests
     --server               run in server mode

Options:

 -a, --armor                create ascii armored output
 -r, --recipient USER-ID    encrypt for USER-ID
 -u, --local-user USER-ID   use USER-ID to sign or decrypt
 -z N                       set compress level to N (0 disables)
     --textmode             use canonical text mode
 -o, --output FILE          write output to FILE
 -v, --verbose              verbose
 -n, --dry-run              do not make any changes
 -i, --interactive          prompt before overwriting
     --openpgp              use strict OpenPGP behavior

(See the man page for a complete listing of all commands and options)

Examples:

 -se -r Bob [file]          sign and encrypt for user Bob
 --clearsign [file]         make a clear text signature
 --detach-sign [file]       make a detached signature
 --list-keys [names]        show keys
 --fingerprint [names]      show fingerprints

GUI版本

GUI版本可用gpg4win

其余命令行下gpg的使用可以参考阮一峰老师的 GPG入门教程
举个简单小列子:

gpg --list-keys
/root/.gnupg/pubring.gpg
------------------------
pub   2048R/23E44D6C 2018-03-23
uid                  liuchunyuan <liucy@xxx.com>
sub   2048R/B94ECCF6 2018-03-23
————————————————

GPG作业

Computer Security Coursework Exercise 2
February 16, 2021
In this coursework we will touch upon a number of security-related topics, namely encrypting and decrypting with GPG, spoofing the sender of an email and performing a MitM attack. The deadline is 8 March 2020, 16:00.
1 Asymmetric Encryption with GPG
In this section you will learn to use GPG for day-to-day usage, most importantly including signing and verifying signatures. You will also have to prove your knowledge by solving a challenge. GPG (sometimes written as GnuPG) is the GNU Privacy Guard. GPG is an open source implementation of the OpenPGP standard for asymmetric encryption.
1.1 Introduction to GPG
The purpose of this part is to familiarise yourself with the GPG tool. You will see how to receive the public keys of other people and use them for encryption and signature verification. You will also learn how to generate private keys and use them for signing and decryption. The instructions that follow are specific for DICE machines, but should work on any Linux machine with slight variations. They should also work on MacOS machines with minimal adaptation. There exist some ports of GPG for Windows, but they are not supported in this coursework. If you prefer you can solve the exercise using only the terminal, so access to DICE using ssh should be sufficient.
1.1.1 Verifying Signatures
Verifying the integrity of software you download is important to ensure that your software hasn’t been tampered with. This section will show you how to verify signatures if they are available. Your task is to download the Alpine Linux mini root filesystem armv71 and the corresponding signature2 and verify it. Save the contents of the second link to a file. You should place both files in the same directory. The names of the files are important: the signature must have the same name as the file it signs, with the added extension ‘.asc’.
Before you can verify the signature however, you need to import the public key which was used to make it. These are also available from the Alpine Linux download page3. The fingerprint of the signing public key is 0482 D840 22F5 2DF1 C4E7 CD43 293A CD09 07D9 495A. More on what a fingerprint is later. To receive the public key, execute:
gpg --recv-key '0482 D840 22F5 2DF1 C4E7 CD43 293A CD09 07D9 495A'
This could take a while. You should see a report of the key which was imported. Next, to verify the file itself, go to the directory where you downloaded the files and run:
1 http://dl- cdn.alpinelinux.org/alpine/v3.11/releases/armv7/alpine- minirootfs- 3.11.3- armv7.tar. gz
2 http://dl- cdn.alpinelinux.org/alpine/v3.11/releases/armv7/alpine- minirootfs- 3.11.3- armv7.tar. gz.asc
3 https://alpinelinux.org/downloads/

         gpg --verify alpine-minirootfs-3.11.3-armv7.tar.gz.asc

Youshouldseealinestating‘Good signature from <person>’.Thisindicatesthatthesignatureisvalid, and that you have the signer’s public key. You will also see a rather scary-looking warning, which indicates that you haven’t assigned the public key a trust level. Proper GPG usage recommends to verify your correspondents’ keys by checking their fingerprint and subsequently signing their key and setting your trust level towards them, however we will not focus on it here.
Keep in mind that the aforementioned steps do not rule out completely the possibility of a Man in the Middle attack. An attacker could hijack the legitimate site, replace the original public keys with his own, put a backdoor in the provided source code and sign it with his key. GPG itself can only rule out such attacks if you have out-of-band reasons to trust the validity of the provided fingerprint. Such an out-of-band reason is the acknowledgement that the website itself is valid through TLS security.
1.1.2 Generating a Keypair
In order to sign or receive encrypted messages, you will need your own key pair. To generate one, run:
gpg --gen-key4
Complete the command line dialogue, and wait for the key to be generated. The default option for key type (RSA both for encrypting and signing) is sufficient. Note that, after the key generation phase, the underlying algorithms are handled by gpg under the hood, so you should never run into problems because of the key type of others. A key length of 4096 and an expiration date after one year are recommended, and the comment field should be left empty. Note that it is highly recommended to secure the key with a strong passphrase. Your private key is your digital identity, do not treat it lightly.
1.1.3 Key IDs
Many commands in GPG need to identify the key to use. The public keys available can be listed with the command ‘gpg -k’,andtheprivatekeyswith‘gpg -K’.Eachkeyisassociatedwithalong(160bits)hexadecimalID,which can be used to refer to it, known as the fingerprint of the key. Add the option ‘--fingerprint‘ to the previous commands to display it. More conveniently, keys can also be referred to by their email address.
1.1.4 Key Management
Once you’ve generated a key, there are a few maintenance operations you may need to do from time to time.

  1. Uploadyourpublickeytothekeyserverat‘hkp://keys.gnupg.net’.Youwillhavetosetthe‘keyserver’
    optionin‘~/.gnupg/gpg.conf’,andthenrun‘gpg --send-keys <Key ID>’.
  2. Makesureyoucanreceiveacoursemate’spublickey.Aftertheyhaveuploadedtheirs,run‘gpg --recv-keys <Key ID>’. You may have to wait a few minutes for their key to propagate before receiving it. Note that in this situation, the key ID must be the full fingerprint; an email address does not suffice.
  3. Generate a revocation certificate for your key, using the command ‘gpg --gen-revoke <Key ID>’. A revocation certificate can be used to invalidate your key pair. This is not something you want to do right now, however it is helpful to know what to do. The revocation certificate can be imported with ‘gpg --import’, similarly to keys. The (now revoked) public key can then be pushed to a keyserver. This may be useful if you want to stop using the particular email address or your private key has leaked.
  4. You can export your keys with the command ‘gpg --export > gpg.keys’. This will create a binary file ‘gpg.keys’, containing all public keys in your database. It is also possible to export private keys, using the command ‘gpg --export-secret-keys > gpg private.keys’. When exported in this way, the keys are still encrypted with your passphrase.

1.1.5 Signing Messages
GPGsignaturesoperateonfiles.Themostbasicwaytosignafileistoexecute‘gpg -b <file>’.Thiswillcreate a new file, called ‘<file>.sig’, which contains the signature of the file with your private key. Adding the -a option will force the signature to be generated in an ASCII format, making it more convenient for embedding.
Itisalsopossibletopackagethedatatogetherwiththesignature,byrunning‘gpg -s <file>’.Thisistypically used in conjunction with encryption.
1.1.6 Encrypting and Decrypting Messages
To encrypt a message, double check that you have a coursemate’s public key. Create a plain text file containing your message, and then encrypt it with ‘gpg -e <file>’. Send the newly created file to your coursemate. The same command can also be run with the -s option, to also sign the message, and the -a option to create an ascii-formatted message.
Hopefully you will have received an encrypted message from one of your coursemates. If not, ask someone to sendyouone.Todecryptthemessage,simplyrun‘gpg -d <file>’.
1.2 Encrypted email exercise
In this exercise you will have to prove your ability to encrypt and decrypt messages correctly. This is the only marked exercise in the GPG section.
2

Generateakeypairifyoudon’talreadyhaveoneanduploadthepublickeytothekeyserverasexplainedabove5.
Send an email from your student address with subject “fingerprint <your fingerprint>” and empty body to cw-2@ed.ac.uk. There should be no whitespace in the fingerprint. The only whitespace in the subject should be a single space between the word “fingerprint” and the actual fingerprint. For example, if your fingerprint is DEAD BEEF,thesubjectshouldbe“fingerprintDEADBEEF”.
Youwillreceivethroughemailthechallenge,encryptedwiththepublickeycorrespondingtothefingerprintyou uploaded. Decrypt it and solve the challenge. Note that due to technical difficulties on our end, the challenge may be arrive with a delay of some hours (especially at night).
Receive the key with fingerprint 96CB 3DC2 AFCA 575F EA2A AB3F 000B 2EDC 21F6 F23D. Create a file containing only the answer and encrypt it using the public key that you just received. Rename the
resulting ciphertext to response.gpg.
Submit the encrypted answer using the “GPG” link in BlackBoard Learn. The link should lead you to the
CodeGrade submission platform, where you can submit your file.
Spoofing email sender
For this exercise, you will send us an email with a spoofed email sender field: • The subject line of your email should be your student id
• The sender of your email should be darth.vader@starwars.com • You will send your email to cw-2@ed.ac.uk.
One way of doing this is by using the mailx utility program. You are free to try this amongst yourselves before you actually send your email to us. Spoofing is probably easier from a DICE machine than from your computer. (You won’t have to submit anything through Learn for this.)
5The key does not necessarily have to be tied with your student email account, but you will have to have access to your student email account in order to complete the exercise.
3

3 (wo)Man in the Middle Attack
You are asked to mount a (wo)Man-in-the-Middle (MitM) attack against the toy implementation of an encrypted chat between terminals provided in /afs/inf.ed.ac.uk/group/teaching/compsec/cw2/mitm/.
3.1 High-level overview
When Alice and Bob hear about encryption, they immediately set out to implement an encrypted chat client so that they are sure no one eavesdrops their intimate discussions. They decide to use AES6 to encrypt their messages, since everyone says it’s the best. They also hear of the Diffie-Hellman key exchange7 (DHKE) and figure it would be cool to use a new secret key for AES every time they connect.
3.1.1 AES
Just like every symmetric encryption scheme, AES consists of two algorithms:
• The encryption algorithm takes a key K1 and a message M1 as input and returns a ciphertext C1 as output:
C1 = Enc(K1, M1)
• The decryption algorithm takes a key K2 and a ciphertext C2 as input and returns a message M2 as output:
M2 =Dec(K2,M2)
If a message M is encrypted with key K and the resulting ciphertext C is decrypted with the same key K, the result of the decryption will be the original message M: ∀K∀M,M = Dec(K,Enc(K,M))
A simple library for encrypting and decrypting using pyaes is provided in symmetric.py.
3.1.2 Diffie-Hellman Key Exchange
This is a protocol between two parties (say Alice and Bob) that want to obtain a common key that is unknown to anybody else. Their communication takes place over an insecure channel that anyone can eavesdrop.
A physical-world equivalent is the following: A group of people sit around a table and two of them want to speak in private. They can have a brief exchange (of very long numbers) which everybody hears. After that they will possess a common secret that no one else knows. They can use this secret as the key for encrypting, sending and decrypting private messages in plain sight.
We assume that both parties have agreed beforehand on a finite cyclic group G and a generator g of G. For production software, these parameters are standardised by cryptographers and hardcoded in the implementation by the developers.
These are the steps of the protocol:
• Alice chooses a random number x and calculates a = gx. • Alice sends a to Bob.
• Bob chooses a random number y and calculates b = gy.
• Bob sends b to Alice.
– Now all eavesdroppers know a and b, but not x and y.
• Alice derives the common secret bx.
• Bob derives the common secret ay .
6 https://en.wikipedia.org/wiki/Advanced_Encryption_Standard
7 https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
4

Given that (gx)y = (gy)x, both Alice and Bob have derived the same common secret. Assuming that an eavesdropper cannot find x from a or y from b, we conclude that no one else can derive the common secret.
A simple library for doing the necessary steps of DHKE is provided in diffie hellman.py. You can see how to use it in the do Diffie Hellman() function in util.py.
3.1.3 Putting it all together
The entire process of chatting is then as follows:

  1. Alice and Bob establish a communication socket
  2. They do DHKE over this socket
  3. Bob encrypts his message under the derived key (with AES) 4. Bob sends the resulting ciphertext through the socket
  4. Alice decrypts the ciphertext using the derived key
  5. Alice reads the message
    Steps 3–6 can be repeated as many times as desired, possibly with changed roles. (In our implementation, the process is repeated only twice, so Bob sends first, then Alice, then both parties terminate.)
    3.1.4 MitM attack
    The described approach sounds very reasonable. Unfortunately Alice and Bob overlooked a fatal flaw: When com- municating over the internet (or even locally), one cannot know with certainty that they are speaking to the intended party, at least not without using some form of cryptographic authentication8.
    Going back to our round-table example, consider the case where every member of the group wears a different mask, uses a voice jammer and sits at random seats. Alice would be unable to recognize Bob. In an even worse scenario, if Bob happens to be missing from the table, someone with a good disguise could impersonate him and fool Alice into performing DHKE with him. This is why Alice and Bob should have agreed to only speak to each other after authenticating themselves.
    Given that no authentication takes place, Eve the attacker is now able to do the following: After Alice opens his end of the socket and before Bob connects, Eve connects and performs a DHKE with Alice. Eve then opens a new socket and waits for Bob to connect. When Bob and Eve connect, they perform another DHKE. Now Eve can decrypt messages from one party, read them and reencrypt them for the other party. If she so wishes she can even send arbitrary messages, completely unrelated to the original ones. In short, she has complete control of the channel while Alice and Bob think they communicate with each other privately.
    3.2 Implementation details
    3.2.1 How to use the provided code
    Open two terminals and navigate to the directory with the scripts. First run python3 alice.py in one and then python3 bob.py in the other (the order is important). You should see secure channel establishment, a couple of messages being exchanged and finally the channel closing.
    8 https://en.wikipedia.org/wiki/Message_authentication_code
    5

3.3 Code overview
Open both aforementioned scripts with your favourite editor. Each of the two scripts calls setup() with its name and the name of the pre-agreed buffer file over which communication happens. This name is set in const.py. Then Alice waits for a message, while Bob sends it. Alice then prints the message and the roles are reversed. Finally both parties close their sockets.
Familiarise yourself with the scripts and understand which lines correspond to each of the steps above. You can optionally dive in the code of the various supporting sources as well.
3.4 Exercise
You will have to implement and submit eve.py via CodeGrade – use the “MitM” link to the submission platform in BlackBoard Learn. The attack should execute correctly when first alice.py is started in one terminal, then eve.py in a second and last bob.py in a third. eve.py should be followed by exactly one of the following three flags: --relay, --break-heart or --custom.
• If the flag is --relay, Eve should just relay the two messages from Alice to Bob and from Bob to Alice. In this case, the outputs of both alice.py and bob.py in the terminals should be identical to the case when the MitM attack isn’t executed.
• Withthe--break-heartflag,EveshouldchangethemessagessothatAlicereceivesthemessage”I hate you!” and Bob receives ”You broke my heart...”. Remember, Eve still has to encrypt both messages correctly.
• As for the --custom flag, after receiving Bob’s messsage, Eve must prompt the user to input a message to the terminal and then must send this message to Alice instead. The same should happen for Alice’s message; Eve must prompt the user for a second message and this time send it to Bob.
Hint: Your solution will have to use the buffer file somehow. The function os.rename() will prove helpful.
Note: It may happen that a script dies without closing its socket gracefully. In that case, you should manually remove the remaining buffer file (by default called buffer) before restarting the scripts.
6
7

相关文章

网友评论

      本文标题:Security中的GPG用法 - TechLead 正式接程序

      本文链接:https://www.haomeiwen.com/subject/etpecltx.html