Dataset Viewer
Auto-converted to Parquet Duplicate
question
stringclasses
1 value
answer
stringlengths
443
1.77k
source
stringclasses
1 value
No question: Moodle
com - 402 : information security and privacy 0x01 cyber threats mathias payer ( infosec. exchange / @ gannimo ) learning goals learn basic properties of security and privacy get an overview of cyber threats break cyber attack lifecycle into different steps differentiate classes of cyber threats 2 basic principles 3 basic security properties : confidentiality keep information secret, e. g., recipe of coca cola, passwords ● give read access only to those who need to know approach : access control, sealing, encryption 4 the attacker cannot hear what you say basic security properties : integrity keep information correct, e. g. my account balance, the result of a vote ● prevent modification of data ● detect modification approach : add a hash, a mac or a signature, make data public 5 the attacker cannot modify / replace / remove what you say basic security properties : availability keep information available / systems running, e. g., my photos, my web shop ● protect against denial of service approach : make copies, duplicate / distribute systems, prevent intrusions 6 the attacker cannot terminate your call basic security properties : authenticity demonstrate the authenticity of information, e. g. gift card, website of a bank ● prevent fake information ● detect modification / tampering approach : add a keyed hash ( mac ) or a signature 7 the attacker cannot impersonate you authenticity is also called integrity of origin basic security properties : non repudiation prevent denial of a statement ( e. g. payment order ) ● proof of
EPFL CS 402 Moodle
No question: Moodle
action / statement approach : add a signature as proof of origin 8 there ’ s a recording of the conversation basic privacy properties : confidentiality keep information of the data subject ( i. e. the person mentioned in the data ) secret ( e. g. age, opinions, health ) give ( limited ) access only to those who need to know approach : access control, encryption, absence of data 9 basic privacy properties : anonymity prevent a link between data and a subject ( e. g. postal address and age to person ) reduce / modify information until no correlation is possible approach : k - anonymity, differential privacy 10 basic privacy properties : absence of information prevent revealing information ● query a db without the db seeing what you are querying ● train a machine learning model without revealing the training data ● confirm a vote, without knowing what the vote is do not request, or delete information that is no longer needed 11 basic privacy properties : absence of information prevent revealing information ● query a db without the db seeing what you are querying ● train a machine learning model without revealing the training data ● confirm a vote, without knowing what the vote is do not request, or delete information that is no longer needed idea : work on encrypted information approach : homomorphic encryption, private information retrieval, zero knowledge proofs also called zero knowledge 12 differences between security and privacy security protects the data of data owners ( e. g. company ) against attacks privacy protects the data subject against abuse
EPFL CS 402 Moodle
No question: Moodle
it is in a company ’ s interest to have good security protecting the privacy of its customers does not always have a benefit for a data owner : some make money by abusing privacy ( facebook? ) we need strong laws to force companies to protect user privacy ( e. g. gdpr ) privacy by design : choose a design that achieves its goal while minimizing the threats to privacy, e. g. swisscovid app 13 the software / system development lifecycle 14 requirement analysis design implementation testing evolution repeat the security lifecycle 15 risk assessment implement operate, maintain establish policy the security lifecycle : risk assessment identify assets, their threats and vulnerabilities analyze the corresponding risk ( impact, probability ) evaluate which risks are acceptable, which must be treated 16 med med high low med med low low med impact probability risk the security lifecycle : establish policy what is, and what is not allowed, e. g. personal data must protected makes use of security mechanisms ● personal data must be encrypted ● require anti - virus software / endpoint scanning ● require two - factor authentication ● establish backup strategy ● name a data protection officer 17 the security lifecycle : implementation specify, design, and implement security policies clearly define and lay out policies with the goal of making them enforceable 18 the security lifecycle : operation, maintain maintain security enforce / apply properties in practice 19 case study : liblzma backdoor 20 case study : liblzma backdoor 21 motivation : gain
EPFL CS 402 Moodle
No question: Moodle
access to a machine through openssh attack steps : ● identify target in the supply chain ( liblzma / xz ) ● the attacker β€œ jia tan ” contributed for 3 years to gain community trust ● the attacker gained maintainer access ● push the backdoor to liblzma liblzma serves as the compressing / decompressing components for critical applications, e. g., openssh adversary can gain root access on the affected machine. andres freund accidentally detected the backdoor during ( performance ) testing case study : liblzma backdoor ( lessons learnt ) 22 be aware of supply chain security ● third party library can cause system rce testing can discover vulnerabilities ● oss - fuzz was modified to hide this bug update the software for bug fix ● update after security update is released oss developers are overwhelmed ● they ’ re unpaid volunteers cyber threats definition ( iso 27000 ) : β€œ potential cause of an unwanted incident, which can result in harm to a system or organization ” definition ( nist fips 200 ) : β€œ any circumstance or event with the potential to adversely impact organizational operations ( including mission, functions, image, or reputation ), organizational assets, or individuals through an information system via unauthorized access, destruction, disclosure, modification of information, and / or denial of service. also, the potential for a threat - source to successfully exploit a particular information system vulnerability. ” 23 types of threats environmental threats : fire, water
EPFL CS 402 Moodle
No question: Moodle
, pollution, earthquakes, cosmic radiation, war - like events, riots loss of essential services : power, cooling, communication technical failures : disk failure cyber : malicious software, denial of service, social engineering, software vulnerabilities / exploits this lecture focuses on cyber threats! 24 motivation for attacks originally : curiosity, fun, fame now : ● profit : small crime, organized crime, industrial espionage ● beliefs ( hacktivism ) : e. g. anonymous, lulzec, guardians of peace ● national security : police forces, national intelligence profit ( dark side ) : ● getting clicks on spam or ads ● resale of accounts, credit card numbers ● rental of hacked pcs ( botnets ) ● demand of ransom ( e. g. to decrypt files ) profit ( gray side ) : ● sell the vulnerabilities you discover to some broker 25 the value of a hacked pc 26 https : / / krebsonsecurity. com / 2012 / 10 / the - scrap - value - of - a - hacked - pc - revisited / cyber attack lifecycle phase 0 : preparation ● define target, from broad ( everyone ) to focused ( individual ) ● find and organize accomplices ● build and / or acquire tools ● research target ( infra & people ) ● test for detection phase 1 : gain access ● deployment ( social engineering, exploits, etc. ) ● initial intrusion ● outbound connection established 27 https : / / en. wikipedia. org / wi
EPFL CS 402 Moodle
No question: Moodle
##ki / advanced _ persistent _ threat cyber attack lifecycle phase 2 : maintain access ● strengthen foothold : persistence, lateral movement ● expand access, obtain credentials phase 3 : complete mission ● exfiltrate data ● manipulate, sabotage data phase 4 : cover tracks ● delete log files 28 https : / / en. wikipedia. org / wiki / advanced _ persistent _ threat commodity threats non - targeted ( " shotgun " approach ) usually non - stealthy and fully automated goal is often short - term financial gains often considered low risk to attackers possible starting point for more sophisticated attacks forms ● malware infected spam ● extorsion spam ● malicious ads ● computer worm 29 https : / / en. wikipedia. org / wiki / advanced _ persistent _ threat commodity threats : malware spam sent broadly to many people ( i. e., not targeted ) crude customization ( e. g., swiss post, linkedin, … ) attachment contains well - known malware campaigns are life hours to days 30 commodity threats : extortion sent broadly to many people ( i. e., not targeted ) relies on leaked information, e. g., password lists convinces user of β€œ hack ” 31 hacktivism several meanings such as : ● politically motivated hacking ● variant of ( anarchic ) civil disobedience good options ● create software to encrypt communications ● create tools to bypass censorship cyber threats ● website defacement ( e. g. anonymous
EPFL CS 402 Moodle
No question: Moodle
, lulzsec ) ● anonymous publication of confidential data ● distributed denial of service ( ddos ) 32 https : / / www. spiceworks. com / it - security / cyber - risk - management / articles / what - is - hacktivism / examples of hacktivism panama papers ( 2016 ) : somebody stole and published documents about 214, 000 offshore companies incorporated in panama epik data breach ( 2021 ) : a group of hacktivists exposed customer personal and credit card information, company emails, etc. from websites hosting extremist content, called the β€˜ panama papers of hate groups ’ oprussia ( 2022 ) : anonymous launched cyber operations against the russian federation in retaliation for the invasion of ukraine. website defacement, email leaks from weapon manufacturers, hacked tv channels and surveillance cameras, etc. 33 advanced persistent threat advanced targeted, multi - step attack, often uses specialized tools, often starts with spear - phishing ( targeted phishing attack ) persistent β€˜ low and slow ’ approach, prioritize long - term over short - term goals, continuous monitoring and interaction ( attacks are known to have lasted 5 years ) threat human coordinated attack ; attackers are skilled, motivated and well - funded ( e. g. industrial espionage ). no β€˜ fire and forget ’ approach, not fully automated 34 classes of malware malware = malicious software virus : spreads by infecting other files worm : spreads automatically to other systems trojan : malware hidden in useful software rootkit
EPFL CS 402 Moodle
No question: Moodle
: hides presence of malware on computer ransomware : encrypts files and requests payment for decryption nation state malware : malware developed by a nation - state 35 botnets : compute for hire mirai botnet consists of 150k iot cameras used to sell compute for, e. g., distributed denial of service attacks ( ddos ) denial of service overwhelms target computer with large amount of requests 36 social engineering β€œ hacking humans ” : use psychological tricks to manipulate another human social engineers use phishing, pretexting, baiting, or tailgating may target employees, customers, or vendors intent to obtain sensitive information, gain unauthorized access, commit fraud prevented by awareness, training, and robust security measures 37 vulnerabilities and exploits vulnerability : weakness in the logic, the software or hardware of a system ( bugs ) proof of concept ( poc ) : demonstrate the existence of vulnerability exploit : demonstrate that attacker can do harm via the vulnerability vulnerabilities can be fixed by patching a system zero day exploit : exploit for which no patch exists yet because the developers don ’ t know about it yet ( since 0 days ) they can be mitigated by making them difficult to exploit ● isolate the system ● add multiple layers of security 38 typical software vulnerabilities buffer / heap / stack overflows : violating memory safety unvalidated input, including sql injection : mixing code and data race conditions : changes of the order of events cause
EPFL CS 402 Moodle
No question: Moodle
a change in behaviour insecure file operations : incorrect assumptions about ownership, location or attributes side - channel leakage : leaking information via time, power, sound, etc. weaknesses in the implementation of access control : authentication and authorization flaws 39 summary a threat is an unwanted action that creates negative impact cyber threats are carried out by attackers through an it system there are different motivations, levels of sophistication, and techniques modeling threats is key to building defenses ( understand first, then act ) 40 risk assessment implement operate, maintain establish policy com - 402 : information security and privacy 0x02 crypto basics mathias payer ( infosec. exchange / @ gannimo ) learning goals basics of symmetric crypto ( stream ciphers, block ciphers, operation modes ) data integrity ( hash functions, message authentication codes ) authenticated encryption public - key cryptography ( digital signature, diffie - hellman key exchange ) public key infrastructure ( pki ) case study : tls 2 cryptography : etymology 3 goals of cryptography confidentiality : data is only accessible with the correct key integrity : any modification of data can be detected authentication : the author of a message can be identified non repudiation : the author of a message cannot deny being the author 4 brief look into the past some data points : ● - 50 caesar ’ s cipher ( substitution ) ● … ● 1883 kerckhoffs'principle ● 1970s data encryption standard ( des ) ● 1970s diffie - hellman public key
EPFL CS 402 Moodle
No question: Moodle
crypto ● 1970s rivest, shamir, adleman rsa ● 1985 elliptic curve crypto ( ecc ) ● 1990s md5, sha - 1 hash algorithms ● 2001 sha - 2 ● 2001 advanced encryption standard ( aes ) ● 2015 sha - 3 5 how do you deploy new algorithms? how do you sunset old algorithms? brief look at the present / future if quantum computers ever come to exist, they will break many crypto algorithms ( mainly asymmetric ). current research : post - quantum crypto : more complicated but plausibly unbreakable by quantum computers 6 nist mit technology review naive approach to encryption two parties agree on an algorithm ( e. g., rot13 ) and keep it secret caesar ’ s cipher was a simple shift of letters if you know that it is a shift, it only takes 26 trials to break it ( i. e., susceptible to brute force ) 7 1883 - kerckhoffs ’ s principle : a cryptosystem should be secure even if everything about the system, except the key, is public knowledge one - time pad key is a random string at least as long as the plaintext. ● xor operation to encrypt and decrypt ● 0βŠ•0 = 0, 0βŠ•1 = 1, 1βŠ•0 = 1, 1βŠ•1 = 0 encryption : = βŠ• decryption : = βŠ• one - time pad is perfect in theory practical
EPFL CS 402 Moodle
No question: Moodle
disadvantages : ● requires truly uniform random one - time pad values ● key must not be used more than once ● key length depends on the message length e. g., it needs a 1tb key to encrypt a 1tb disk 8 perfectly secure but impractical symmetric crypto 9 symmetric crypto encryption and decryption are done with the same key, hence symmetric. solves the problem of transferring large amounts of confidential data reduces security to the problem of transferring a symmetric key ( key exchange ) 10 encryption decryption plaintext plaintext ciphertext secret key secret key same key stream cipher use pseudo random generator to expand a short seed into a stream of random bits { 0, 1 } k - > { 0, 1 } n, n > k ● n - k bit stretch ● use part of output as new seed ● can encrypt data of arbitrary length ● stream cipher : xor message and pseudorandom pad ● e. g., salsa20, chacha20 11 1 - bit stretch prg key ( k bit ) 0 / 1 new key ( k bit ) 1 - bit stretch prg 1 - bit stretch prg 1 - bit stretch prg 1 - bit stretch prg … stream cipher : stream cipher key plaintext ( stream ) encryption 1 - bit stretch prg limitations of stream ciphers two possible pitfalls with stream ciphers : malleability : flipping one bit of the ciphertext will flip the same
EPFL CS 402 Moodle
No question: Moodle
bit in the plaintext ● e. g., if you know which bit encodes the sign of a value you can change a payment of $ 100 to - $ 100 ● you should always add an integrity check when encrypting data! cipher reuse : if two cleartexts are encrypted with the same cipher - stream, then : βŠ• = βŠ• ● if you know some bits of one message, you can deduce the corresponding bits of the other message : [ ] = [ ] βŠ• [ ] βŠ• [ ] you should always use unique seed to create a pseudorandom cipher - stream 12 limitations of stream ciphers 13 block cipher encrypts fixed size blocks of data ● a padding scheme is used to fill the last block ● a mode of operation to combine multiple blocks data encryption standard ( des ) : ● block size 64 bits ( too short, collisions ) ● key size 56 bits ( too short, can be brute forced ) advanced encryption standard ( aes ) ● block size 128 bits ● key size 128 / 192 / 256 bits ● hardware support ( e. g. intel, amd, armv8 ) 14 when in doubt, use aes don ’ t use des ( or triple des ), both are deprecated block cipher : aes ( rijndael ) a block cipher shuffles input on a per - block basis each output byte depends on all input
EPFL CS 402 Moodle
No question: Moodle
bytes multiple rounds ensure thorough shuffling https : / / en. wikipedia. org / wiki / advanced _ encryption _ standard 15 modes of operation : ecb ecb : encrypt each block separately, with the same key 16 plaintext ciphertext block cipher encryption key electronic codebook ( ecb ) mode encryption plaintext ciphertext block cipher encryption key plaintext ciphertext block cipher encryption key can you spot the weakness? modes of operation : ecb problem : you can see the penguin! 17 original encrypted same cleartext block results in same ciphertext block modes of operation : cbc introduces the use of an initialization vector ( iv ) for the first block 18 each ciphertext block acts as iv of the next block plaintext ciphertext block cipher encryption key initialization vector ( iv ) cipher block chaining ( cbc ) mode encryption plaintext ciphertext block cipher encryption key plaintext ciphertext block cipher encryption key modes of operation : cbc decryption is the opposite of encryption 19 note that the iv needs to be sent along the ciphertext plaintext ciphertext block cipher encryption key initialization vector ( iv ) cipher block chaining ( cbc ) mode decryption block cipher encryption key block cipher encryption key ciphertext ciphertext plaintext plaintext modes of operation : cbc cbc encryption does not reveal any structure 20 original encrypted quiz! what happens to decryption if a bit is flipped due to a transmission error? ● does the error propagate to all
EPFL CS 402 Moodle
No question: Moodle
following blocks? ● does it only affect the current block? ● none of the above? 21 modes of operation : cbc a whole block is garbled, one bit of the next block is inverted 22 plaintext ciphertext block cipher encryption key initialization vector ( iv ) cipher block chaining ( cbc ) mode decryption block cipher encryption key ciphertext ciphertext plaintext plaintext block cipher encryption key modes of operation : cbc some possible pitfalls in using cbc. malleability : ● flipping one bit of the iv will flip the same bit in the plaintext ● flipping one bit in a ciphertext block flips the same bit in the next plaintext block and mangles the current block ● always add an integrity check when encrypting data! padding oracle attacks : ● the last block must be padded to obtain the correct block size ● if not carefully implemented, validation of padding can lead to leakage of the plaintext ( e. g., in tls, see serge vaudenay ’ s cbc padding oracle attack ) 23 data integrity 24 data integrity integrity : protects against unauthorized modification integrity = confidentiality remember the malleability of stream and block ciphers : it ’ s easy to flip bits of the cleartext we need a primitive that : ● detects any modification of the message ● cannot be forged ( circumvented ) by an attacker 25 ( cryptographic ) hash functions goal : take an arbitrary length input, and generate fixed length
EPFL CS 402 Moodle
No question: Moodle
output cryptographers say they map a β€˜ preimage ’ to an β€˜ image ’ 26 e8927ahk03bc9f.. data of arbitrary length fixed length hash ( digest ) message hash function preimage image properties of hash functions preimage resistance : ● given a hash h, it is difficult to find a message for which h = hash ( ) ● this implies that the function is a one - way function ( and p! = np ) ● very useful for password hashing 27 prevented attack : given a password hash, an attacker cannot recover the matching password preimage image no! properties of hash functions second preimage resistance : ● given a message, it is difficult to find a second message such that hash ( ) = hash ( ) 28 prevented attack : hashes protect integrity of messages, thus, an attacker cannot forge a message with the same hash as an existing message preimage image no! 2nd preimage properties of hash functions collision resistance ● it is difficult to find any two messages, such that hash ( ) = hash ( ) 29 possible attack : hashes are used in signatures. an attacker could show one preimage and have it signed by a third party. the signature would also be valid for the other preimage. preimage 1 image preimage 2 no! no! quiz! what is the complexity of randomly finding a 2nd preimage in a
EPFL CS 402 Moodle
No question: Moodle
random function that generates 160 bit outputs ( e. g., sha - 1 )? what is the complexity of randomly finding a collision in sha - 1? nb : if the hash function has some weaknesses, the complexity might be lower 30 collisions in naively, 2 ^ 160 ops better : 2 ^ 80 ops * in practice, it took 2 ^ 63. 1 operations to find a preimage * hashing 2 ^ 80 random messages would produce one expected collision based on birthday paradox https : / / security. googleblog. com / 2017 / 0 2 / announcing - first - sha1 - collision. html sha - 1 broken 31 example of hash functions md5 : 128 bits, broken, chosen prefix collisions are easy ( do not use ) sha - 1 : 160 bits, broken, collisions are difficult but possible ( avoid ) sha - 2 : 224 / 256 / 384 / 512 bits, not broken, but related to sha - 1 ( use ) sha - 3 : 224 / 256 / 384 / 512 bits, no weakness known ( prefer ) blake3 : 224 / 256 / 384 / 512 bits, no weakness known, faster, not standard ( fine ) 32 key takeaway : complex enough to be hard to brute force but reasonable to compute message authentication codes ( mac ) similar to a hash function, but involves a symmetric key the same key is used to generate the mac and to validate it if the key is known only to the two parties of an
EPFL CS 402 Moodle
No question: Moodle
exchange, a correct mac proves : ● that the message was not created by a third party ( authentication ) ● that the message has not been modified ( integrity ) 33 message authentication codes typically based on a hash function ( e. g. hmac sha - 2 ) or on block ciphers ( e. g. cbc - mac - aes ) 34 β€œ alice ” β€œ bob ” malicious network link m1, h ( k, m1 ) m1, h ( k, m1 ) accept! β€œ alice ” β€œ bob ” malicious network link m1, h ( k, m1 ) m2, h (??, m2 ) reject! authenticated encryption 35 always require both confidentiality and integrity different approaches : ● encrypt then mac ( e. g., in ipsec, use whenever possible ) ● mac then encrypt ( e. g., in tls ) ● encrypt and mac ( e. g., in ssh ) 36 confidentiality and integrity authenticated encryption modern encryption modes guarantee confidentiality and integrity they include additional data that is authenticated but not encrypted : used for sequence numbers or other metadata aead ( authenticated encryption with associated data ) 37 42 hello hello nonce nonce tag zor & glb 42 42 encryption decryption aead : galois / counter mode gcm used with any block cipher, typically aes aes - gcm is best practice ( together with xsalsa20 - poly
EPFL CS 402 Moodle
No question: Moodle
##1305 and aes - siv ) 38 initialization vector ( iv ) counter 0 counter 1 counter 2 incr block cipher encryption block cipher encryption ciphertext plaintext 1 auth data 1 h h block cipher encryption ciphertext plaintext 2 h auth tag incr public - key cryptography 39 public - key cryptography solves the problem of having to agree on a pre - shared symmetric key uses a pair of public and private key instead encryption with the public key guarantees that only someone with the private key can decrypt signing with the private key allows anyone with the public key to check validity the public key can be transferred freely, no need to keep it secret much better than symmetric keys! 40 encryption plaintext plaintext ciphertext public key secret key different keys decryption origin of public - key crypto 1975 diffie and hellman describe the idea of asymmetric crypto in β€˜ new directions in cryptography ’ β€œ we stand today on the brink of a revolution in cryptography. the development of cheap digital hardware has freed it from the design limitations of mechanical computing and brought the cost of high grade cryptographic devices down to where they can be used in such commercial applications as remote cash dispensers and computer terminals. in turn, such applications create a need for new types of cryptographic systems which minimize the necessity of secure key distribution channels and supply the equivalent of a written signature. at the same time, theoretical developments in information theory and computer science show promise of
EPFL CS 402 Moodle
No question: Moodle
providing provably secure cryptosystems, changing this ancient art into a science. ” 41 original primitives public and private key ● two keys : public is widely distributed, private is kept secret ● must be hard to derive private from public ● may be easy to derive public from private operation : encryption and decryption ● encrypt with public key, decrypt with private key ● hard to decrypt without private key operation : digital signature ● sign with private key, verify with public key ● hard to create signature without private key interactive key exchange ● establish a shared secret key over an insecure communication channel 42 digital signatures private key allows signer to generate an unforgeable signature that attests to the validity of a message anybody can verify the signature using the public key not just encrypting with the secret key security notions : euf - nacma, euf - cma, seuf - cma … example signature schemes : ● ecdsa and eddsa ( elliptic curve based, most common ) ● bls ( pairing based, aggregatable, should be used more imo ) ● dlithium ( lattice - based ), sphincs + ( hash - based ). post quantum! 43 digital signatures : usage examples software - update distribution ● your computer knows the public key of the software developer type apt - key list on debian / ubuntu to see them ● updates are signed ● your
EPFL CS 402 Moodle
No question: Moodle
computer can verify that the update indeed comes from the developer and that it has not been altered on its way authenticated email ● if alice knows bob ’ s public key, she can verify bob ’ s signature on messages contracts ● in switzerland you can sign contracts with digital signatures 44 diffie - hellman key exchange alice and bob want to exchange data securely eve can listen to any messages 45 solution 1 : pre - shared key alice and bob agree on key ahead of time ( this is the symmetric key from earlier ) 46 solution 2 : multiple round - trips alice and bob exchange multiple messages 47 diffie - hellman key exchange protocol for key exchange ( to agree on a secret key ) developed 1976 by whitfield diffie and martin hellman, with preliminary work by ralph merkle 48 g, n a g, n g, n b a b a a b b k k? diffie - hellman key exchange calculation of common key assumption : mixing colors is easy, separating them is hard 49 diffie - hellman key exchange by exchanging the public values,, and combining them with their private values,, alice & bob can create a shared secret an attacker who observes and cannot find 50 diffie - hellman : security properties the reverse function of a = g ^ a % p is difficult ( hard ) due to discrete logarithm numbers p and g must be chosen well ( large enough ) standards usually define p and g 51 a, g
EPFL CS 402 Moodle
No question: Moodle
, p = rand ( size ) ; - - - a = g ^ a % p k1 = x ^ a % p b = rand ( size ) ; - - - b = g ^ b % p k2 = x ^ b % p a, g, p x m = rand ( size ) ; - - - x = g ^ m % p k1 = a ^ m % p k2 = b ^ m % p x, g, p b diffie - hellman : man in the middle 52 must authenticate each other using, e. g., public keys mitm may break diffie - hellman rsa encryption is product of two large primes βˆ— is coprime with ( n ) = ( βˆ’ 1 ) ( βˆ’ 1 ), compute d such that mod ( n ) = 1 53 rsa can be broken by factoring. use a number of 3072 bits or more ( for 128 bits of security ). scheme above is trivially insecure. use a padding scheme ( preferably rsa - oaep ). alice bob message = m use to encrypt m to decrypt use m = rsa encryption is product of two large primes βˆ— is coprime with ( n ) = ( βˆ’ 1 ) ( βˆ’ 1 ), compute d such that mod ( n ) = 1 54 rsa
EPFL CS 402 Moodle
No question: Moodle
can be broken by factoring. use a number of 3072 bits or more ( for 128 bits of security ). scheme above is trivially insecure. use a padding scheme ( preferably rsa - oaep ). elliptic curve cryptography ( ecc ) based on elliptic curves over finite fields used everywhere, e. g., can adapt diffie - hellman with different group operations smaller keys for equivalent security ( e. g., 256 bit ecc comparable to 3072 bit rsa ) popular curves offer fast performance e. g. ● curve25519 ● curve448 ● nist p256 ( controversial, c49d3608 ) giacomo with details on ecc 55 elliptic curve cryptography ( ecc ) ecc is used for key exchange, e. g., in tls : ecc diffie - hellman ( ecdhe ) used for signature : ecc digital signature algorithm ( ecdsa ) for example, sony used ecdsa to sign the software of the playstation 3 ● ecdsa uses the private key and a nonce to generate the signature ● the private key can be recovered if the same nonce is used in two signatures ● easy to misuse, eddsa improves on this ( deterministic nonce generation ) bitcoin addresses are a hash of an ecdsa public key imessages and icloud keychain sync rely on ecdsa 56 crypto
EPFL CS 402 Moodle
No question: Moodle
comparison asymmetric is powerful but orders of magnitude slower than symmetric crypto asymmetric used to exchange a symmetric key, then symmetric takes over all these algorithms are only safe with long enough keys ( for 128 bits of security ) : ● symmetric : 128 to 256 bits ● asymmetric : rsa 3072 bits, ecc 256 bits ● hash functions : 256 bits cryptography is used in real life : ● symmetric : kerberos ● asymmetric : wpa3 ( not possible to crack wifi passwords ), srp ( note that kerberos and srp will be covered later ) 57 public - key infrastructure ( pki ) 58 key distribution cryptography reduces a security problem to one of key management public keys do not have to be secret, but still must be authentic if a man in the middle can replace a public key, security guarantees are lost 59 hello hello scruntch 7onkvar hello key distribution we need a trusted third party to distribute the public keys the certification authority ( ca ) certifies the keys by signing them it does some validation before signing the keys ● may ask for an email ● may ask for a copy of your passport ● this is documented in the certificate practice statement ( cps ) of the ca if we trust the key of the ca, we can trust all keys signed by the ca a β€˜ signed key ’ is a certificate. it contains at least : ● the identity of the holder ( subject ) ● the validity date of
EPFL CS 402 Moodle
No question: Moodle
the certificate ● the public key of the subject ● the signature by the ca 60 example certificate hexhive ’ s certificate is signed by let ’ s encrypt uses rsa + sha256 61 example β€œ root ” certificate let ’ s encrypt certificate is signed by … isrg 62 hierarchy of trust current browsers know a set of root cas ( 144 root cas in firefox as of 11 / 2023 * ) if there is a chain of signatures up to a trusted root, the browser trusts the certificate 63 https : / / ccadb. my. salesforce - sites. com / mozilla / cacertificatesinfirefoxreport crypto summary 64 summary crypto can be symmetric ( fast ), asymmetric ( public keys ) and can provide confidentiality, integrity, authentication, and non - repudiation asymmetric should only be used to encrypt short data, e. g., ● the hash of a document, when signing it ● a random symmetric key, for encryption of a document ecc ( faster, shorter keys ) is replacing rsa as asymmetric algorithm trust is not possible without a trust root web browsers trust 150 - ish certification authorities from many countries ( this is not perfect! ) 65 case study : tls 66 tls transport layer security ( tls, previously known as ssl ) provides confidentiality, integrity, and authentication β€œ the primary goal of
EPFL CS 402 Moodle
No question: Moodle
tls is to provide a secure channel between two communicating peers ” ietf rfc 8846 basic idea : ● build your client - server app without security, add tls, et voila! history : ● tls 1. 0, 1999, rfc 2246 ● tls 1. 1, 2006, rfc 4346 ● tls 1. 2, 2008, rfc 5246 ● tls 1. 3, 2019, rfc 8846 67 tls building blocks the server is authenticated with a certificate it proves its identity by signing some information received from the client with its private key client and server create a symmetric key using asymmetric crypto ● ec diffie hellman only ( since 1. 3 ) ● previously also supported standard diffie - hellman and key transfer once key established, use an aead to communicate ( authenticated encryption with associated data ) 68 tls cipher suites ( after 1. 3 ) algorithms to be used are specified in cipher suites : tls _ aes _ 128 _ gcm _ sha256 key exchange and signatures default to ecdhe and rsa lesson from previous versions of the protocol : ● flexibility in cryptography can actually hurt security. ● better to stick to same defaults. 69 tls v1. 3 suites ● tls _ aes _ 128 _ gcm _ sha256 ● tls _ aes _ 256 _ gcm _ sha384 ● tls _ chacha20 _ poly1305 _
EPFL CS 402 Moodle
No question: Moodle
s ha256 ● tls _ aes _ 128 _ ccm _ sha256 ● tls _ aes _ 128 _ ccm _ 8 _ sha256 ● that ’ s it! 70 ( some ) tls v1. 2 suites ● tls _ ecdhe _ rsa _ with _ aes _ 128 _ gcm _ sha256 ● tls _ ecdhe _ ecdsa _ with _ aes _ 128 _ gcm _ sha 256 ● tls _ ecdhe _ rsa _ with _ aes _ 256 _ gcm _ sha384 ● tls _ ecdhe _ ecdsa _ with _ aes _ 256 _ gcm _ sha 384 ● tls _ dhe _ rsa _ with _ aes _ 128 _ gcm _ sha256 ● tls _ dhe _ dss _ with _ aes _ 128 _ gcm _ sha256 ● tls _ dhe _ dss _ with _ aes _ 256 _ gcm _ sha384 ● tls _ dhe _ rsa _ with _ aes _ 256 _ gcm _ sha384 ● tls _ ecdhe _ rsa _ with _ aes _ 128 _ cbc _ sha256 ● tls _ ecdhe _ ecdsa _ with _ aes _ 128 _ cbc _ sha2 56 ● tls _ ecdhe _ rsa _
EPFL CS 402 Moodle
No question: Moodle
with _ aes _ 128 _ cbc _ sha ● tls _ ecdhe _ ecdsa _ with _ aes _ 128 _ cbc _ sha ● … ( 37 total suites!!! ) simplicity is key! tls 1. 3 removes old, no - longer - safe cipher suites, remove compression remaining cipher suites all use aead handshake ● can be shorter in some cases ● is partially encrypted key exchange is always forward secure session resumption with pre - shared key ( psk ) about 63 % of websites offer tls 1. 3 now ( ssllabs ) 71 perfect forward secrecy strong security notion : session keys should not be compromised even if long - term secrets are. diffie - hellman - like protocol offers perfect forward secrecy ( pfs ) at least since ed. snowden ’ s revelations we know that : ● governments record a lot of traffic ● governments exploit opportunities to steal private keys whenever possible, prefer key agreement protocols with pfs 72 perfect forward secrecy 73 tls handshake clienthello contains supported crypto parameters selected serverhello is already encrypted only 1 - rtt required! serverhello contains server certificate, which client verifies client optionally authenticated once keys established, use aead 74 tls uses public and symmetric crypto public key crypto : ● the ca has signed the server ’ s certificate ( and its own root certificate ) ● the server signs the key exchange to prove
EPFL CS 402 Moodle
No question: Moodle
it holds the private key ● elliptic curve diffie hellman is used to exchange a symmetric key symmetric crypto : ● aes block cipher is used in gcm mode for encryption ● sha hash is used for hmac, for key derivations 75 historical weaknesses of tls downgrade attacks ( by a man - in - the - middle ) ● trick server into using an insecure version of tls ● trick server into using weak keys ( freak, 2014 ) ● trick server into downgrading the dh parameters ( logjam, 2015 ) padding oracle attacks : ● lucky 13, 2013 : break tls 1. 2 with padding oracle attack ( timing ) ● poodle, 2014 : downgrade tls 1. 0 to ssl3, then padding oracle attack crime, breach, 2012 / 13 : exploit vulnerability when compression is used bugs in implementations : ● 2014 : heartbleed in openssl : leaks random 64k bytes of server memory ● 2017 : cloudbleed : bug in cloudflare html parsers allowed people to read data of other cloudflare customers takeaway : tls before 1. 3 was too complex, simplicity is key! 76 implementing tls two major ways of implementing tls use a new name and port ( https, ldaps, imaps, etc. ) : ● http on port 80 β†’ https on 443 ● start with a tls handshake, security is mandatory ● not compatible with clients that can
EPFL CS 402 Moodle
No question: Moodle
’ t tls use the starttls command on the standard protocol ● e. g., esmtp ( extended smtp ) on port 25 ● client types starttls if it wants to start a handshake ● opportunistic encryption, no guarantees ● mitm can pretend starttls is not supported 77 deploying tls on the internet 78 increasing usage of tls using https everywhere would be better for privacy and security since 2014, google has started ranking https websites higher than http since july 2018, google chrome labels http web sites as not secure : 79 let ’ s encrypt : free certificates! to be able to create certificates that are trusted by all browsers, you must undergo a costly certification ● prove that you protect your private keys ● prove that you diligently validate the identity of your customers etc. the internet security research group ( not for profit ) found enough sponsors to certify a fully automated ca that gives certificates for free! it is called let ’ s encrypt to obtain a certificate, you must place specific data ● in a file on your web server, or ● in a dns entry of your domain fully automatable : no excuse for not using tls! 80 attacks on https and defenses 81 ssl stripping and hsts a mitm makes you believe that the site uses http, not https ● when you type a url, your browser first connects using http the server sends a redirect
EPFL CS 402 Moodle
No question: Moodle
to https the mitm doesn ’ t show you the redirect, your browser continues to use http ● or, attacker replaces https with http in the links of the pages that you visit you connect to the mitm with http, attacker connects to the site with https 82 you have no alert, as your browser doesn ’ t know that you should be using https! hsts http strict transport security ( hsts ) rfc 6797 the server sends an http header indicating you must always use https strict - transport - security : max - age = 63072000 ; includesubdomains ; ● max - age : the browser will remember to connect directly by https for one year ( 63072000 seconds ) ● includesubdomains : this is true for all subdomains of this domain 83 can you spot the weakness? hsts preload list if the mitm intercepts your very first connection to the site, they can hide the redirection to https ● the client will never see the hsts header you can request that your domain be added to the hsts - preload list all major browsers have a copy of that list ( chromium. org ) and never connect by http to the domains in the list e. g., digitec. ch is on the list, your browser will never try http when connecting to digitec 84 untrustworthy cas a trusted ca ( the root cert is in your browser ) can give the mitm a
EPFL CS 402 Moodle
No question: Moodle
trusted certificate in the name of any server using this, the server can intercept the traffic without you knowing 85 untrustworthy cas reasons for a ca to hand out fake certs ● the ca has been hacked ( 2011 comodo was hacked, certificates were generated for, e. g., www. google. com, login. yahoo. com, login. skype. com ) the certificates were later revoked ● the ca is your company ’ s ca your company wants to intercept all traffic to detect malware they have inserted the company ’ s root cert into your browser ● the ca is β€˜ experimenting ’ and not following the guidelines in 2015 symantec ( owners of versisign, thawte, equifax, geotrust, rapidssl ) issued fake certificates for google and other companies in 2018 google blocked symantec ’ s root certificates in chrome symantec sold its ca business to digicert ● the government may have requested the certs in order to spy on its citizens ( syria, china, india, or france ) 86 protection against untrustworthy cas certificate pinning ● client - side list of trusted certificates certificate transparency ● public list of certificates not seen in this course : caa ● official ca of domain published in dns dane ● certificates published in the dns 87 certificate pinning the developer of the client application ( e. g. smartphone app ), stores the certificate of a trusted root ca, or intermediate ca
EPFL CS 402 Moodle
No question: Moodle
in the client if the server shows a certificate which is not signed by this pin, it does not accept to connect, e. g., a mobile e - banking application only trusts certificates signed by an intermediate ca of the bank there was a proposal to enable pinning in browsers with an http header ( hkpk ) but it did not work out 88 certificate pinning the client knows that server cert must be signed by pinned cert from β€œ good ” ca it does not accept the fake cert, even if it is signed by a β€˜ trusted ’ ca 89 certificate transparency public signed logs of certs used in the internet rfc 6962 cas submit all the certs they generate servers can verify if the logs contain certs that they did not request ● then, somebody else requested a cert for their domain! clients can verify that a cert received from a server is in the logs when a cert is added to a log, the log generates a signed certificate timestamp ( sct ) ● the web server can give a copy of the sct to the client ● the client doesn ’ t need to lookup the certificate in the log very easy to detect fraudulent certificates 90 ct demo these are two signatures from two transparency logs both logs would have to coordinate to fake a β€œ valid ” certificate 91 ct demo there is a set of public logs that you can query separately ● you can find a list at here or you can use the site crt. sh to search in the
EPFL CS 402 Moodle
No question: Moodle
logs : 92 tls summary 93 tls summary tls authenticates the server ( and possible the client ) and protects confidentiality and integrity of data using a combination of symmetric and asymmetric crypto a public key infrastructure ( pki ) distributes public keys using certificates this does not work on the internet, because we can not trust > 150 cas hsts and certificate transparency protect against mitm and fraudulent cas certificate pinning helps even more, but needs some manual setup ● it does not scale to the web 94 com - 402 : information security and privacy 0x03 access control mathias payer ( infosec. exchange / @ gannimo ) switcheroo : swap class / exercises and quiz reminder ● 10 / 02 : class 0x14 data security + pake ( instead of 07 / 10 ) ● 10 / 07 : quiz, exercise for 0x03 and 0x14 ● 10 / 09 : class 0x15 pl security ● 10 / 14 : no class ● 10 / 16 : exercise for 0x15 ( back to normal ) 2 what do you prefer? exercise, then quiz at 18h30 β€” or β€” quiz at 16h15 and then exercises? quiz : ● no extra material allowed ● bring a blue or black pen ● multiple - choice format ● duration : 15min in co01 learning goals know authentication factors ( password, device, biometrics ), strengths and risks differentiate and identify access control policies ( rbac, dac, mac )
EPFL CS 402 Moodle
No question: Moodle
understand the value of authentication protocols and delegated authentication 3 authentication 4 what is authentication? 5 authentication is the process of verifying someone's or something's identity identification is the act of identifying a particular user, often through a username. hi, i ’ m mathias! show me the proof. my password is * * * * * *. password - based authentication ● simplest form of authentication ● user sends both username and password to the server, server authenticates user ’ s identity. 6 https : / / docs. oracle. com / cd / e19424 - 01 / 820 - 4811 / gdzeq / index. html what if the network is compromised ( 2 )? what if the server is compromised ( 3 / 4 )? authentication factors access control only makes sense if subjects are authenticated there are 3 common flavors to authenticate subjects : ● something you know : passwords, pin codes ● something you own : paper card, smartphone, certificate, electronic token ● something you are : biometrics two factor authentication ( aka 2fa ) requires the use of two factors ● a password is often one of the two factors 7 the password is dead... β€œ they just don ’ t meet the challenge for anything you really want to secure. ” ( bill gates ) β€œ within 5 years, you ’ ll never need a password again ” ( ibm ) β€œ passwords are done at google ” ( h. adkins, manager of information security at
EPFL CS 402 Moodle
No question: Moodle
google ) 8 truth : passwords are still the main form of authentication on the web β€œ no other single technology matches their combination of cost, immediacy and convenience ” ( c. herley, p. van oorschot ) ( bill gates, 2004 ) ( ibm, 2011 ) ( h. adkins, manager of information security at google, 2013 ) even strong passwords are at risk a stolen password can be replayed by anybody an attacker can : ● steal passwords using client - side malware ● obtain passwords by cracking hashes stolen from a server ( next lecture ) ● phish passwords with a fake website ● eavesdrop the password ( remember, that ’ s why we need tls ) credential stuffing ● lists of usernames and passwords are distributed online ● hackers try the same credentials on many different sites ● sony and gawker were both hacked : β€œ two thirds of people with accounts at both sony and gawker reused their passwords ” ( source : troy hunt ) 9 password managers store all your credentials in encrypted form ● your master password is used to decrypt the credentials ● to be used on different devices, the encrypted credentials must be accessible online where are passwords stored? ● password manager works offline, uses a local file ( e. g., keepass ) you can choose to host this file in the cloud ● password manager talks to a server in the cloud (
EPFL CS 402 Moodle
No question: Moodle
e. g., lastpass ) browser plug - in or app downloads credentials and decrypts them locally you must trust them to not steal your master password ● best of both : the password manager comes with an open source server that you can host where you want ( e. g., bitwarden ) 10 authentication / session cookies after logging in a web application the server sends a cookie, stored in the client the cookie is kept by the client and used for authenticating against the server the cookie should be unique for every subject the cookie can be used by illegal clients through forging ● if the server encrypts the cookie it limits forging ( hmac ) 11 something you own typically called a ( hardware / software ) token bingo card ● proves that the user owns the card ● can be easily copied without being detected one time password ( otp ) token ● displays a password to be used only once ● the password changes with time or click ● proves that user owns token at time of login ● cannot be copied easily ( secure hardware ) ● oath standard 12 something you own tan generator ● a calculator that generates a number based on user input ● can be used to sign a transaction ( transaction authentication number, tan ) ● proves that user owns the generator ● based on a smartcard ( secure hardware ), typically your bank card smartphone ● otp is sent by sms or ● otp is generated by app, as with an otp token ● proof that user
EPFL CS 402 Moodle
No question: Moodle
owns the phone ( or sim card, secure hardware? ) 13 something you own a private key in a hardware token ● token signs a challenge ● different keys for different websites ● proof that user owns the token ● secure hardware ● universal 2nd factor ( u2f ) standard 14 oath, generation of otp oath is a standard that describes : ● how otps are generated from a seed ● an xml format for importing the seeds into an authentication server standard oath tokens exist in both hardware or software form ● e. g., the google authenticator app generation of the next otp is either counter or time based ( rfc 4226 ) 15 oath algorithms counter based : hotp (, ) = truncate ( hmacβˆ’sha512 (, ) ) time - based ( initial time, time interval ) : totp (, ) = hotp (, ( βˆ’ ) / ) 16 what are the tradeoffs between hotp and totp? rsa secureids secure ids implement a form of totp requires a random seed to be synced between devices and customers in a massive hack, attackers stole all seeds from rsa the first true supply chain attack 17 https : / / www. wired. com / story / the - full - story - of - the - stunning - rsa - hack - can - finally - be - told / u2f, fido2 universal 2nd factor is a standard developed by
EPFL CS 402 Moodle
No question: Moodle
the fido alliance latest version is fido2 for each application, the token generates a key pair and gives the public key to the server ● on login, the server sends a random challenge to the client ● the client signs ( the challenge + the domain name of the server + a signature counter ) ● the client sends the data and signature to the server ● the server verifies the signature adding the domain prevents phishing attacks adding a counter detects cloning of the private key / replay attacks 18 u2f authentication workflow 19 u2f device client server lookup the kpriv associated with h counter + + check app id lookup the kpub associated with h check s using kpub verify origin, channel id, counter handle, app id, challenge h, a ; challenge, origin, channel id, etc. counter, signature ( a, c, counter ) counter, c, s s c h a https : / / developers. yubico. com / u2f / protocol _ details / overview. html fido2 standardizes u2f within the browser with javascript ( called webauthn ) additionally makes use of ctap to access the signature ctap, the client to authenticator protocol, describes how an application can ask an authenticator to generate an assertion ( signature ) ● authenticator can be a usb token smartphone connected by bluetooth authentication module of platform ( e. g., phone ’ s biometric authentication ) the
EPFL CS 402 Moodle
No question: Moodle
assertion contains information whether the user ● was present ( e. g., clicked on a button ) ● was verified ( e. g., pin or fingerprint ) u2f, fido2 ( webauthn ) 20 u2f, fido2 pros no problem if the server gets hacked : ● it is an asymmetric system. the information stored on the server cannot be used to log in no problem if the client gets hacked ● the private key stays in secure hardware of the client ● usage of the key is only possible with user interaction very convenient ● it can use the native authentication system of the platform ( iphone faceid, microsoft hello biometrics, google fingerprint ) motivation ● something you know could be guessed ● something you own could be stolen ● nothing to remember, nothing that can be lost physiological ● iris ● retina ● fingerprint ● shape of head ● shape of hand biometrics 22 behavioral ● speech ● keystroke timing ● handwritten signature on tablet ● gait registration ● acquisition ● extraction of characteristics ● storage of characteristics limitations ● acquisition is never exact ● comparison is never a perfect match biometric information cannot be hashed ( due to imprecision in reading out data ) ● decision is always error prone biometrics : authentication process 23 authentication ● acquisition ● comparison ● decision biometrics : error rates the decision algorithm must accept a certain error ; sensitivity can be tuned far false acceptance rate : the system declares a match when it wasn
EPFL CS 402 Moodle
No question: Moodle
’ t frr false rejection rate : the system declares a non - match although it was a match eer equal error rate, when the system is tuned such that far = frr 24 biometrics : fingerprints the fingerprint is read by a sensor an image of the ridges is created the minutiae are extracted at ● termination of a ridge ● bifurcation of a ridge a list of coordinates ( x, y ) and angles is generated the list is compared with a stored list ● the minutiae are shifted and rotated to get the best match 25 biometrics : faceid 30, 000 points are projected on the face and read from a different angle a specialized and isolated processor constructs a 3d image and compares it to the registered face 26 biometrics : faceid a specialized and isolated processor is used to store and compare images ● the main processor never sees the 3d data the communication with the sensor ( camera ) is encrypted ● cannot be intercepted and replayed this is the same for iphone fingerprint scanning ( touch id ) ● this is why you can ’ t just replace a broken sensor ● it has to be paired with the processor note : you still need to type a password when booting the phone ● used to decrypt the storage 27 biometrics : faceid limitations 28 biometrics and authentication ● no hashing possible ( neither for transmission nor for storage ), risk : theft ● it is impossible to change a stolen fingerprint! ● best
EPFL CS 402 Moodle
No question: Moodle
to store the biometric data locally in protected hardware ● example : biometrics are stored in passports, not at the customs offices smartphones store fingerprint data in separate, secure hardware ● some sensors can be fooled or replaced ● not ideal for remote authentication rather use it for local access to authentication key ( e. g. u2f ) biometrics discussion 29 biometrics discussion biometrics and privacy ● biometric data is considered sensitive data by european data protection laws and the swiss law ● biometric data can reveal health issues ( e. g., eye pathologies ) ● biometric data can exclude some people ( absence of fingerprints or fingers ) ● a lot of more or less serious research is done with ml and ai to extract information from faces detection of propensity for aggression based on facial structure privacy fears as tokyo taxis use facial recognition cameras to guess riders ’ age and gender for targeted advertisements 30 biometrics discussion 31 source : twitter @ rosa access control 32 after we authenticate a subject … access control defines and enforces operations that subjects can do on objects ● bob ( subject ) has permission to read / write ( operation ) from a socket ( object ) ● implies that the subject has been authenticated first access control basics 33 access control defines and enforces operations that subjects can do on objects ● bob ( subject ) has permission to read / write ( operation ) from a socket ( object ) ● implies that the subject has been authenticated first access control
EPFL CS 402 Moodle
No question: Moodle
basics 34 security policy access rights ( aka permissions, privileges ) describe which subjects can do what operations on what objects a security policy is a collection of access rights. security policies can be represented as an access control matrix 35 https : / / dl. acm. org / doi / 10. 1145 / 775265. 775268 security mechanism security mechanisms try to prevent operations that are not authorized by the security policy for example, the kernel implements an access check to see if a user has permissions to open a file. if the access check fails, the rights are not granted. 36 principle of least privilege ( polp ) ● subjects only have the minimum rights required for their job ● i. e., subjects are only allowed minimal operations on objects per task ● this limits the impact if anything should go wrong the challenge in access control is to have a system that is simple to implement and manage and that is close to the principle of least privilege there is no β€œ one size fits all ” solution and often different approaches to access control are combined to achieve the best results 37 most important access control principle multiple levels of access control network level access control ● subjects are connections or data packets ● they are identified by source / destination ip addresses and protocol ports ● typical operations are pass, block, or tag ● example : a database server only accepts traffic from inside epfl ( source addr 128. *. *. * ) connecting to tcp port 3306 ( mysql )
EPFL CS 402 Moodle
No question: Moodle
typically enforced with ● network equipment : firewalls ● the servers : local firewall on the server ( e. g., ufw in linux ) configuration of the server software 38 what are the tradeoffs of filtering at the different levels? multiple ( confusing? ) levels of access control access control at the operating system ● which user can start / stop the db engine? ● who can read / modify the files of the db? access control in the application ● which user of the application can edit user profiles? ● who can see financial data? access control within the enterprise ● which employees can access the application? ● which applications are limited to human resources, which to marketing? 39 multiple approaches to access control three common varieties : ● role - based access control ( rbac ) ● discretionary access control ( dac ) ● mandatory access control ( mac ) β†’ not message authentication code! 40 role - based access control ( rbac ) simplifies the specification of permissions by grouping users into roles centered on user roles ( a role can contain multiple permissions ) 41 rbac example : roles simplify management 42 user1 user2 user3 user4 right1 right2 right3 right4 right5 right6 user1 user2 user3 user4 role1 role2 right1 right2 right3 right4 right5 right6 users rights users roles rights example : operating systems ● most operating systems have the notion of groups ● groups can be given a set of permissions ●
EPFL CS 402 Moodle
No question: Moodle
users can be added to groups ● examples : debian / ubuntu : audio group can access mic and loudspeakers, wireshark group can sniff network traffic windows : " remote desktop user " group can access desktop remotely which groups does your user belong to? rbac implementation 43 $ id gannimo uid = 1000 ( gannimo ) gid = 1000 ( gannimo ) groups = 1000 ( gannimo ), 24 ( cdrom ), 25 ( floppy ), 27 ( sudo ), 29 ( audio ), 30 ( dip ), 44 ( video ), 46 ( plugdev ), 108 ( netdev ), 113 ( bluetooth ), 117 ( lpadmin ), 120 ( scanner ) rbac pros easy to grasp the idea of roles easy to manage ● roles decouple digital entities from permissions ● simply assign roles to a new subject no need to decide for each object ● easy to revoke authorizations by removing role easy to tell through roles which permissions a subject has and why ● typically centrally managed difficult to decide on the granularity of roles ● do we need different roles for modifying and deleting client information? ● leads either to role explosion or roles that are too broad ( not least privilege ) role meaning is fuzzy ● employee position in company may be different from rbac role ( think developers in same team working on different subjects ) unclear if roles can be shared across different
EPFL CS 402 Moodle
No question: Moodle
departments ● for β€œ manager ” roles, in general, is a finance it manager the same as a marketing it manager? rbac cons discretionary access control ( dac ) access control is at the discretion of the object owner ● owner specifies policies to access resources it owns access control matrix represents rules ● stored by column : access control list ( acl ) stored with object ● stored by row : capabilities stored with subjects 46 / stud / grades. txt / hw1 / grade. sh / sensitive stud1 r – – x β€” ta1 rw - rwx r - x acl vs capabilities think of a door protected by a bouncer vs. a door protected by a lock acl ( bouncer, tied to object ) : ● the bouncer knows exactly who can get in ● people don ’ t know where they can get in and where they can ’ t capabilities ( key, tied to subject ) : ● doors don ’ t know who will show up with a key ● people know exactly for which doors they have a key acl is practical when you often have to create or modify rights on objects capabilities, when you often create or change rights of subjects or roles 47 dac in unix file systems typically done with acl stored in the target object, e. g., in the metadata of files in the file system subjects are grouped in three categories : owner, group, other. three access rights : ( r ) ead, ( w ) rite
EPFL CS 402 Moodle
No question: Moodle
, e ( x ) ecute ● for directories : r : directory can be listed w : directory can be modified ( create, delete, rename files ) x : directory can be accessed by the cd command the three rights and three groups are stored in 9 bits ● represented as three octal digits ● owner rwx, group rx, others r : rwx | r - x | r - - = 754 ● the permissions of the first matching category dominate 48 remember the ubuntu local β€œ uncomplicated ” firewall gui gufw : ● only root can read or write the files and the directory : acls in unix : example 49 ● everybody can read the application profiles, but only root can modify them : $ ls - l / etc / gufw / total 44 drwxr - xr - x 2 root root 28672 avr 24 08 : 17 app _ profiles - rw - - - - - - - 1 root root 73 avr 23 15 : 10 gufw. cfg - rw - - - - - - - 1 root root 1079 avr 23 11 : 09 home. profile - rw - - - - - - - 1 root root 76 avr 18 11 : 40 office. profile - rw - - - - - - - 1 root root 78 avr 18 11 : 40 public. profile $ ls - l / etc /
EPFL CS 402 Moodle
No question: Moodle
gufw / app _ profiles / ssh. gufw _ service - rw - r - - r - - 1 root root 213 mai 24 2017 gufw / app _ profiles / ssh. gufw _ service acls in unix : setuid / setgid if a program has setuid bit set, it will be run with the permissions of the owner of the file instead of the permissions of the user running the program very useful to give users more privileges in specific cases example : the passwd command allows a user to modify the / etc / passwd and / etc / shadow files ● passwd can be read by all but only modified by root ● shadow can be read by root and shadow and modified by root 50 $ ls - l / etc / { passwd, shadow } - rw - r - - r - - 1 root root 2786 avr 23 11 : 09 / etc / passwd - rw - r - - - - - 1 root shadow 1489 avr 23 11 : 09 / etc / shadow ● the program / usr / bin / passwd has the setuid bit $ ls - l / usr / bin / passwd - rwsr - xr - x 1 root root 59640 jan 25 2018 / usr / bin / passwd acls in unix : setuid / setgid when user jane runs the program passwd, the process is run as root
EPFL CS 402 Moodle
No question: Moodle
: 51 $ ps - ef | grep passwd root 16003 26651 0 09 : 26 pts / 1 00 : 00 : 00 passwd the setgid bit does the same for groups : the group of the process running the program is set to the group of the owner of the program setuid and setgid is displayed as s instead of x in the access rights of the file example : this program has both setuid and setgid bits set : $ ls - l ~ / test - rwsrwsr - x 1 user user 0 sep 25 08 : 36 test finding files that have the setuid bit set : acls in unix : setuid / setgid 52 $ find / - perm / u = s 2 > / dev / null / bin / fusermount / bin / mount / bin / su / bin / umount / bin / ping... setuid is very practical, because it lets unprivileged users execute some well defined privileged actions quiz! setuid can be very dangerous, why? 53 programs with setuid bit set are privileged. any bug in these programs could be used to escalate the privileges of the user. as the user controls input to the program running as root, they may use that input to trigger the bug and gain arbitrary code execution. capabilities in linux capabilities are permissions that are related to a subject, not to an object linux supports capabilities for processes. some examples are
EPFL CS 402 Moodle
No question: Moodle
: ● cap _ chown : make arbitrary changes to file user id and group id ● cap _ dac _ override : bypass file read, write, and execute permission checks ● cap _ sys _ boot : use reboot or kexec ( load a new kernel ) example : dumpcap is the program used by wireshark to sniff network traffic ● it can only be run by user root and members of the wireshark group ● it does not have the setuid bit 54 $ ls - l / usr / bin / dumpcap - rwxr - xr - - 1 root wireshark 104688 jan 19 06 : 23 / usr / bin / dumpcap let ’ s check the capabilities of dumpcap : the process assumes net _ admin and net _ raw capabilities when launching dumpcap : it can read and write to all network interfaces the program can do this while running in the name of the user : capabilities in linux 55 $ sudo getcap / usr / bin / dumpcap / usr / bin / dumpcap = cap _ net _ admin, cap _ net _ raw + eip $ ps - ef | grep dumpcap user 24342 26651 0 13 : 10 pts / 1 00 : 00 : 00 / usr / bin / dumpcap this is much safer than using setuid if there was a bug in dumpcap allowing to execute arbitrary commands, setuid would run these commands as
EPFL CS 402 Moodle
No question: Moodle
root! pros ● flexible ● intuitive ● easy to manage ( owners get to set the permissions themselves ) dac pros and cons 56 cons ● depends on the owners judgment ● only works if programs are benign and users make no mistakes ● vulnerable to the " trojan " / declassification problem * * a malicious program run by an authorized user can read a protected file and write an unprotected copy of that file. anybody can now read the file. mandatory access control tries to ensure that even someone with access cannot leak the data historically associated with military - grade information security ● multilevel security : e. g., unclassified, confidential, secret, top - secret the system labels both subjects and objects with security labels ● can only be modified by trusted administrators via trusted software security policy : ● example : subjects can only access objects of the same or lower level 57 subjects \ objects top - secret secret confidential unclassified top - secret read, write read read read secret read, write read read confidential read, write read unclassified read, write mandatory access control depends on trusted software and admins for ● keeping the system in a protected state, by preventing operations that violate the rules of the matrix ● labeling new subjects and objects ● perform transitions of labels ( e. g., when a document is declassified ) can be used in conjunction with dac or rbac 58 quiz! why is it a bad idea to allow secret subjects to write confidential
EPFL CS 402 Moodle
No question: Moodle
documents? 59 remember the order of β€œ secrecy ” : unclassified, confidential, secret, top - secret. a secret subject may read a secret file and write the contents into a confidential file, thereby reclassifying the secrecy level and downgrading it. this is also called the β€œ no - write - down ” problem. mac confidentiality vs integrity mac and confidentiality ● when protecting confidentiality, we don ’ t want users to write to a lower level ( no write - down ) prevents leaking information from higher to lower levels ( " trojan " ) ● typical scenario : network access control network split in zones : internet, internal, secret firewalls only allow data to flow from lower zones to higher zones mac and integrity ● we don ’ t want users from lower levels to write into higher levels ( no write - up ) prevents unauthorized modification of objects ● typical scenarios : operating systems users can read and execute os programs, but they cannot modify them 60 mac linux examples selinux and apparmor are two mac systems for linux they are both based on the generic linux security module ( lsm ) lsm sits in the kernel and is called just after standard dac checks and before access is given lsm allows implementation of secondary security policies 61 a brief tour of linux security modules - starlab. io unix filesystem ( dac ) mac linux examples : selinux ● every user has a context made of name, role, and domain ● files
EPFL CS 402 Moodle
No question: Moodle
, ports and other objects can be labeled with name, role and type ● rules can be defined to allow certain actions selinux is leveraged in android : better isolation of apps and generic services 62 mac linux examples : apparmor ● also based on lsm ● uses profiles to define access rights to files, network and capabilities ● there are no labels or security levels ● profiles basically define the same rules that can be defined with dac, but they cannot be modified at the discretion of the owner of the objects or subjects ● profiles can be generated by observing a running application ● apparmor is enabled by default in ubuntu apparmor demo : copy a pdf file into your. ssh directory and try to open it with evince! 63 mac pros and cons pros ● addresses the limitations of dac ● easy to scale 64 cons ● can be too restrictive, prevent legitimate tasks ● not flexible summary of access control different types of access control ( rbac, dac, mac ), usage depends on situation ● aim : achieve least privilege at minimal complexity modern oses make use of all of these types ● dac with acls for files and most objects ● dac with capabilities for privileged operations ● using groups to implement rbac ( users, admins, hr, marketing ) ● mac for protecting the integrity of the system 65 authentication protocols when sending a password over tls is not enough 66 motivation why is the naive password - based authentication
EPFL CS 402 Moodle
No question: Moodle
insufficient? ● sending passwords over network is risky, leaks to adversary when the network is compromised ● attacker may break encryption ● server may be compromised or even store passwords too ● challenge - response authentication why do we need authentication protocols? ● standardization and save duplicated efforts implementing authentication. ● kerberos 67 challenge - response rather than sending the password to the server ● the server sends a random challenge to the client ● the client uses the password hash to create a response e. g., encryption or hmac of the challenge example, microsoft ad - hoc networking with smbv1 ( not kerberos ) 68 client, knows pwd server, knows hashes nthash = md4 ( pwd ) lookup nthash of alice choose random challenge c r = encnthash ( c ) r? = encnthash ( c ) calculate response r c i ’ m alice typically, challenge response protocols are vulnerable to mitm attacks microsoft introduced the signature of the packets with a key derived from the pwd hash ( it is actually an hmac ) ● the mitm does not know the key, cannot send any packets challenge - response 69 client, knows pwd server, knows hashes r c i ’ m alice r c i ’ m alice mitm challenge - response : mutual authentication the server and client can both use a challenge : they can authenticate each other examples : ● newer versions of microsoft challenge - response ( smbv2
EPFL CS 402 Moodle
No question: Moodle
) ● wifi wpa, wpa2, and wpa3 challenge - response protocols may be eavesdropped or suffer cracking attacks ● the attacker records a challenge and a response ● they try all possible passwords to find which would yield the same response 70 kerberos kerberos provides authentication and authorization across a network subjects receive tickets that they use to access objects exclusively based on symmetric keys developed at mit in the 80 ’ s initially deployed in unix the main authentication protocol in windows lan networks 71 motivation key idea : delegation ● users authenticate once and then access multiple services without needing to repeatedly re - enter credentials separation of concerns ● authentication ● access control ( authorization ) ● providing actual service 72 overview kerberos uses a three - phase approach 73 tgt service ticket service ticket tgt : an authentication server ( as ) authenticates the client and delivers a ticket granting ticket ( tgt ) : the client can then present the tgt to the ticket granting server ( tgs ) to get a service - specific ticket : the client can access the service as tgs server client role of as, and tgs the as handles authentication ( user identity verification and issuing the tgt ). ● this step is solely about confirming the user's identity. the tgs handles access control ( authorization, issuing service - specific tickets based on the tgt ) ● once the tgt is issued by the as, the user doesn ’ t need to go back to
EPFL CS 402 Moodle
No question: Moodle
the as for each service access. instead, the tgt can be used multiple times to request service - specific tickets from the tgs. 74 delegated authentication 75 oauth2 kerberos is a great but targets the intranet. following the idea of delegated auth … oauth2 ( rfc 6749 ) is used for delegated authentication on the internet ● oauth2 providers like facebook, google, or x / twitter can be used to authenticate and access other applications for example, you can log in to pinterest with facebook or google you can also authorize pinterest to access your photos on facebook 76 remember tlsv1. 2 vs 1. 3? oauth2 is much simpler than kerberos roles client : application that wants to use authentication and possibly access the user ’ s data ( pinterest ) resource server : server that has user ’ s data that client wants to use ( facebook ’ s server containing the user ’ s photos ) authorization server : server on which the user authenticates ( facebook authentication server ) user : owner of the account and resources on resource server ( wants to log into pinterest with his facebook account ) 77 typical oauth2 flow 78 typical oauth2 flow the client and the authentication server have a shared secret ● the client thus has to register with the authentication server before being able to offer this service ● the secret is used when the client exchanges the authentication code for an access token
EPFL CS 402 Moodle
No question: Moodle
● the authentication code is not sufficient to get access to the resources ● it can only be used by the client and nobody else oauth2 can be used by browsers or in apps ● in an app a redirection for authentication can be either opening a browser within the app ( called a webview ) β–  not very safe as the app could be spying while you login switching to the other app ( e. g. facebook ) and then back 79 oauth2 authentication only if oauth is only used for logging in, then the flow can stop after message 8 most apps in smartphones ( e. g., x, instagram, gmail ) do not store your passwords ● they use oauth2 to request an access token and use it ● when you change your password you don ’ t need to type your new password into all your devices 80 passwords can go a long way, especially if you use a password manager for critical accounts, 2fa significantly raises the bar for attackers ● u2f is secure and user - friendly challenge - response protocols authenticate a user without sending the password ● can be vulnerable to mitm, in particular if there is no mutual authentication kerberos uses tickets to authenticate users across a network ● authentication is separated from authorization oauth is used to delegate authentication on the internet ● it has no crypto at all, relies on communications being made over tls challenge - response protocols we have seen and ke
EPFL CS 402 Moodle
No question: Moodle
##rberos use symmetric crypto authentication summary 81 for the homework you will play with cookie for authentication ● cookie tampering ( attack ) ● hmac for cookies ( defense ) you will get confident with the otp algorithm internals ● hotp algorithm, based on hmac algorithm ● totp algorithm, an extension of the hotp algorithm 82 how does access control apply to data storage? ● server level ● application level ● data level ● network level how can we securely store passwords? ● salt ● memory hard functions how to verify a password and exchange a key? ● password authenticated key exchange ( pake ) in the upcoming lecture … 83 summary access control has multiple approaches depending on the policy definition security mechanisms prevent the violation of the policy authentication lets subjects to identify themselves via something they own / know / are authentication protocols let a user authenticate in a network without sending their passwords in cleartext authentication can be delegated to third parties 84 com - 402 : information security and privacy 0x14 data security mathias payer ( infosec. exchange / @ gannimo ) 1 learning goals understand how access control and encryption are applied in data security learn methods of secure password storage and techniques for password cracking know the basics of secure remote password protocol ( srp ) 2 data security data storage requirements are ubiquitous ● banking, industry, social networks, government, research, or mobile apps ● leads to new types of analysis ( big data, machine learning ) 3 companies must consider security of data they
EPFL CS 402 Moodle
No question: Moodle
store ● what are security requirements of db systems? ● what are main attack vectors of db systems? ● what are main protections of db systems? typical setups 4 internet firewall database web server farm on premises internet database website instances in the cloud / paas ( platform - as - a - service ) multitier architecture 1 ) presentation tier ( user interface, web pages, static content ) 2 ) application ( logic ) tier 3 ) data tier ( provides data persistence and apis to access data ) source : wikipedia 5 examples of db attacks taken from sqli hall - of - shame : 6 washington state 2021 - 02 1. 4 million records from users who applied for unemployment - via accellion vulnerability washington state breach tied to accellion vulnerability amadeus it group 2019 - 05 exposed data on 700, 000 visa applications of israeli citizens hacker reveals breach exposing flight histories of netanyahu family, other israeli officials epic games 2019 - 01 all fortnite player accounts accessible, exposing credit card info etc. bugs on epic games site allowed hackers to login to any fortnite players account steam 2018 - 11 api vulnerability gave access to cd keys for any game. now patched. steam bug could have given you access to all the cd keys of any game database : access control 7 layers of a database the layers of database accesses : 8 layer function threat hardware the disk stores the data of the db a thief can take the disk or their backups os the user running the db accesses
EPFL CS 402 Moodle
No question: Moodle
the files the sysadmin can access the files database db administrators use privileged db accounts for maintenance they can access all data network the application tier uses a tcp connection to talk to the db hackers could connect to the db remotely application uses a db account to access the data of the application users an application user can access data of other application users each layer needs to implement proper access control! access control : least privilege access control defines which actor can access which resource we should apply the principle of least privilege : ● each actor can only access the resources strictly needed for its function this must be applied across all levels of the db 9 hardware access control if it is a physical machine in a data center ● physical protection : locks, cameras, alarms if it is a virtual machine in the cloud ● cloning the machine is like stealing the hard disk ● limit the number of people who have the right to clone ● use strong authentication for your cloud management console ( e. g., 2 factor authentication ) 10 os access control the db runs as a process in the os, owned by a certain os user ( e. g., mysql, oracle ) 11 / com402 $ ps - ef | grep mysql mysql 29841 1 0 feb13? 00 : 04 : 02 / usr / sbin / mysqld this user is the only one allowed to access the files of the database : / com402 $ ls - l
EPFL CS 402 Moodle
No question: Moodle
/ var / lib / mysql / total 110660 drwx - - - - - - 2 mysql mysql 4096 feb13 23 : 13 com402 drwx - - - - - - 2 mysql root 4096 feb13 22 : 49 mysql drwx - - - - - - 2 mysql mysql 4096 feb13 22 : 49 performance _ schema the data of the com402 db is stored in directory com402 only user mysql is allowed to access this directory, or any user with root privileges! discretionary db access control sql databases use discretionary access control ( dac ) to grant user access to objects ( tables and views ) through privileges ( select, insert, update, delete, create, drop ) by default, the root or system user has all privileges on all objects allow alice to read, modify or write the name, address and grades in the table called students of the database called com402 : 12 grant select, update, insert ( name, address, grade ) on com402. students to alice @ localhost ; access control in the db : rows granularity at the row level can be achieved by defining views : 13 we allow bob to only read the lines with academic year 2024 in table students : we can combine this to control access to each column / row of the
EPFL CS 402 Moodle
No question: Moodle
database tables create view year _ 2024 as select * from com402. students where academic _ year = 2024 ; grant select on year _ 2024 to bob @ localhost ; role - based db access control sql databases also support role based access control roles are created very much like users ● privileges can be granted to roles ● then, roles can be granted to users e. g., profs can read most columns but only change grades : 14 user gannimo is a professor : you can grant several roles to a same user ( employee, lecturer, i & c ) create role prof ; grant select ( name, grade, academic _ year ) on com402. students to prof ; grant update ( grade ) on com402. students to prof ; grant prof to gannimo @ localhost ; network access control sometimes the application tier runs on the same machine as the db ● the db should be configured to only listen to connections from localhost in other cases, the application tier runs on a different machine ● accept connections only from machines that should talk to the db, e. g., by installing a firewall in front of the db, and / or by using a local firewall on the db server, and / or by restricting users to certain ip addresses that can access the db 15 create user bob @ 10. 2. 2. 33 identified by'horsebatterystapleok'bob can only connect from 10.
EPFL CS 402 Moodle
No question: Moodle
2. 2. 33 application access control applications usually have their own layer of users and privileges ● they use one or few db accounts to interact with the db example : an e - banking application has 1k customers and three tables : ● a customer table with all customers and their password hashes ● an account table with all accounts and their owners ● a transaction table with all transactions of all accounts access control is handled by the application ● it uses the customer table for authentication ● it uses the other two tables to find the accounts and give access to transactions 16 quiz! there is a single db user to access the three tables holding customers, accounts, and transactions the application makes sure each customer only sees their own data ( even if the db user has access to all data ) what are potential security flaws in this design? 17 sql injection : lack of separating code and data sql injection in python : ( never do this! ) 18 an attacker can modify the request : param = " peter " # given by user stmt = " select name, grade from students where name ='" + param + "'" cursor. execute ( stmt ) param = " peter'union select name, password from students - - " sql injection : lack of separating code and data sql injection in python : ( never do this! ) 19 do this! prepared statements in python : python replaces % s with the given parameter ● the meaning of the statement can not change param = " peter "
EPFL CS 402 Moodle
No question: Moodle
# given by user stmt = " select name, grade from students where name ='" + param + "'" cursor. execute ( stmt ) param = " peter " # given by user stmt = " select name, grade from students where name = % s " cursor. execute ( stmt, ( param, ) ) back to application level access control to limit the impact of sql injections, use different db users for different accesses : ● one db user with read access on the customer table for login purposes ● one db user with write access on the customer table for changing the users ’ password ● one db user with read access on the account table customers can not change ownership of accounts ● one db user with read / write access to the transaction table for the actual application the database access control is not exactly least privilege, but it reduces the impact of sql injection ( and compartmentalizes code with privileges ), e. g., an sql injection on the login form cannot read data from the transaction table 20 application level access control using different db users is an application of the defense in depth principle the application implements fine grained access control the database implements coarse grained control if the access control at the application level fails, the access control of the database reduces the impact 21 defense in depth : multiple layers of security encrypting data 22 encrypting data we have the same layers as with db access
EPFL CS 402 Moodle
No question: Moodle
control 23 layer function protect against hardware / os data is encrypted when read / write to disk stealing of disk / cloning virtual machines database db encrypts when read / write to file access by os users / admins network db encrypts when read / write to network ( e. g., tls ) hackers cannot sniff data in transit application application encrypts when read / write to the db access by db admins, memory dumps by os admins at rest in motion in use encrypting data at rest data stored on the server is data at rest the os can encrypt data before it is written to disks ● protects against theft / copy of the disks ● a user that can log into the machine and access the files of the database will see cleartext data! databases can be configured to encrypt data before writing it to files ● file access by os users does not yield cleartext data anymore ● the keys may be stored in local files or obtained from a key server, e. g., from the amazon key management service for machines in the amazon cloud most dbs call this type of encryption transparent data encryption ( tde ) 24 key use case : mobile phones! encrypting data in motion data is exchanged between the db and the application ( web server or logic tier ) if not encrypted, it could be eavesdropped most dbs support tls encryption for db connections
EPFL CS 402 Moodle
No question: Moodle
● certificate pinning : the client ( db ) can be given a copy of the server certificate or its ca ● it will refuse to connect if the server presents a different certificate ( no need for 200 cas as in web browsers ) 25 encrypting data in use by the application with encryption at rest and in motion, data is still in clear in the memory of the db! ● an admin of the db server can dump the memory and see the data the solution is to encrypt data in the application before storing it into the db the key stays in the application tier ● there is no way to decrypt the data on the db server 26 quiz : encrypted database what could go wrong if the data is encrypted in the database? 27 if the data is encrypted in the database, then the db can not ● search with wildcards ( e. g., where name = ’ pete % ’ ) ● sort, compare or aggregate data this makes the db pretty useless useful for certain information ● e. g., credit card numbers ● pin codes ● passwords? summary : database security data stored in dbs is often the main asset of a company ● there are both privacy and security risks apply access control at all layers : physical, os, db, network, application dbs can do both discretionary and role - based access control ● apply the principle of least privilege ● use multiple db users where applicable encryption is an efficient way
EPFL CS 402 Moodle
No question: Moodle
to protect data ● transparent data encryption protects at os and physical levels ● network traffic encryption is a must ● some data can be encrypted by the application, but you lose functionalities like search, sort, compare, etc. 28 password storage 29 password leaks are common source : troy hunt january 2019 30 the 773 million record " collection # 1 " data breach password leaks are common 31 source : haveibeenpwned. com password leaks are common 12, 724, 063, 603 e - mail / password pairs published in oct 2023 made up of thousands of different sources 32 password storage naive approach : cleartext ● store passwords in clear text in the database ● 000webhost. com used to store passwords in cleartext in 2015, a hacker used an exploit in an old php version of the website and stole 13 million passwords ( source : arstechnica ) ● you should never store passwords in cleartext better : hash the password ● microsoft stores windows passwords as hashes ( md4 ) ● almost all passwords of length 8 can be recovered in under a minute 33 password storage : hashing classic way : use salt and iterations ● hugely slows down password cracking ● simple passwords can still be cracked on specialized hardware modern way : use a memory hard function ● cracking a password requires a decent amount of memory ● specialized hardware with many computing cores ( e. g., graphics cards, fpga ) do not have enough
EPFL CS 402 Moodle
No question: Moodle
memory to speed - up cracking 34 the importance of salt 35 smbv1 ( microsoft ) does not salt their passwords. don ’ t be like microsoft. salt usage and examples salt : random data concatenated as an additional input to the hash function : pw _ hash = h ( password, salt ) examples ● wpa and wpa2 use the ssid as salt, and 4, 096 iterations of hmac - sha1 each test becomes expensive only simple passwords can be cracked ● kerberos pre - authentication 36 the importance of salt some systems store the passwords as a simple hash : pw _ hash = h ( password ) if passwords are hashed without salt, there are two major weaknesses : 1. multiple hashes can be cracked at once ● if you have a list of 1, 000 hashes and want to find out if any of the 1, 000 accounts has password β€œ correct horse battery staple ” ; calculate ( β€œ correct horse battery staple ” ) look - up which of the 1, 000 hashes matches ● with a smart data structure, the look - up is almost free, with a single hash operation you can try to crack 1, 000 passwords ● cracking passwords requires the same hash operations as cracking one! 37 the importance of salt 2. hashes can be calculated in advance ● windows hashes have no salt : every user on the earth with password β€œ correct horse battery staple ”
EPFL CS 402 Moodle
No question: Moodle
has the same hash β€œ 9cc2ae8a1ba7a93da39b46fc1019c481 ” ● if attackers had enough memory, they could calculate all hashes in advance and store them in a great big table eight mixed case characters plus digits : 62 ^ 8 2. 2 * 10 ^ 14 passwords we need 24 bytes to store a password and a hash ● the table would be 4. 7pb big! β†’ not feasible ● attackers can trade more time of cracking a password for a smaller table 38 time - memory trade - offs ( tmto ) in 1980, martin hellman invented a tmto to inverse cryptographic functions ● when you double the memory, it is four times faster to invert the function 39 rainbow tables are an optimization of this tmto from 2003 ( by ph. oechslin ) password cracking : time - memory trade - offs ( tmto ) basic idea : trade more time of cracking a password for a smaller table originally, we can crack one password from one password - hash pair 40 password hash p0 h0 p1 h1 p2 h2 … … pn hn h h h h ● number of passwords : n ● memory required : n * ( password _ len + hash _ len ) ● time of cracking a password : time of finding a hash match, i. e., o ( c ) password cracking : time - memory trade - offs basic
EPFL CS 402 Moodle
No question: Moodle
idea : trade more time of cracking a password for a smaller table can we crack two passwords from one password - hash pair? 41 password hash password hash p0 h0 p7 h7 p1 h1 p64 h64 p2 h2 p11 h11 … … … … pn / 2 pn / 2 pm hm h h h h h h h h???? ● number of passwords : n ● memory required : 1 / 2 * n * ( password _ len + hash _ len ) how can we connect the two password - hash pairs? password cracking : time - memory trade - offs basic idea : trade more time of cracking a password for a smaller table can we crack two passwords from one password - hash pair? 42 password hash p0 h0 p7 h7 p1 h1 p64 h64 p2 h2 p11 h11 … … … … pn / 2 pn / 2 pm hm h h h h h h h h r r r r ● number of passwords : n ● memory required : 1 / 2 * n * ( password _ len + hash _ len ) how can we connect the two password - hash pairs? ● reduction function ● map from the hash set to the password set quiz : password cracking what makes a good reduction function? 43 the reduction function glues the hash of the previous computation to current one : h64 β†’ password requirements : ● output follows the expected alphabet ● few collisions (
EPFL CS 402 Moodle
No question: Moodle
hash to password should be unique - ish ) ● output is reasonably uniformly distributed ● does not require any specific structure password cracking : time - memory trade - offs basic idea : trade more time of cracking a password for a smaller table 44 password hash p0 h0 p7 h7 p1 h1 p64 h64 p2 h2 p11 h11 … … … … pn / 2 pn / 2 pm hm example 1 : crack h11 ● find h11 at the end of the third row ● p11 = r ( h ( p2 ) ) h h h h h h h h r r r r example 2 : crack h1 ● no hash matched at row ends ● calculate h ( r ( h1 ) ) ● match with h64 at the end of the second row time of cracking a password : time of 1 reduction + 1 hash + finding a hash match password cracking : time - memory trade - offs more columns, more time of cracking a password, less memory consumption typically, chains would contain tens of thousands of hashes and passwords 45 password hash p0 h0 p7 h7 p4 h4 p17 h17 p47 h47 p1 h1 p64 h64 p23 h23 p6 h6 p32 h32 p2 h2 p11 h11 p42 h42 p35 h35 p9 h9 … … … … … … … … … … pn hn pm hm pt ht pl
EPFL CS 402 Moodle
No question: Moodle
hl pq hq h h h h r r r r h h h h r r r r h h h h r r r r h h h h r r r r h h h h password cracking : time - memory trade - offs challenge : reduction function may collide result in identical chains, which is a waste of the table space 46 password hash p0 h0 p7 h7 p4 h4 p42 h42 p35 h35 p1 h1 p64 h64 p23 h23 p6 h6 p32 h32 p2 h2 p4 h4 p42 h42 p35 h35 p9 h9 … … … … … … … … … … pn hn pm hm pt ht pl hl pq hq h h h h r r r r h h h h r r r r h h h h r r r r h h h h r r r r h h h h password cracking : rainbow table solution : using a different reduction function in each column of the table this allows building much larger tables and makes them much more efficient 47 password hash p0 h0 p7 h7 p5 h5 p41 h41 p33 h33 p1 h1 p64 h64 p27 h27 p76 h76 p52 h52 p2 h2 p4 h4 p22 h22 p15 h15 p9 h9 … … … … … … … … … … p
EPFL CS 402 Moodle
No question: Moodle
##n hn pm hm pt ht pl hl pq hq h h h h r1 r1 r1 r1 h h h h r2 r2 r2 r2 h h h h r3 r3 r3 r3 h h h h r4 r4 r4 r4 h h h h storing hashes with salt and iterations 48 the classical way using salt adding a random value ( salt ) to the hash function prevents the two issues : ● you cannot crack multiple hashes with a single hash calculation ● you cannot calculate the hashes in advance because each hash has a different, random salt salt = random ( ) pw _ hash = h ( password, salt ) we need to store both the hash and the salt in the database ● when a user logs in, we use the salt to generate a hash and compare it to the stored hash 49 quiz! what cryptographic primitive can we use to combine a salt with a hash? how can we make it harder to crack? 50 cryptographic hash functions are used to hash passwords and salts they are repeated many times to make it harder to crack salt is not enough cryptographic hash functions are designed to be fast and simple to implement a modern graphics card calculates hundreds of billions of hashes per second a simple way of slowing the attacker is to apply the hash function multiple times if you require 5, 000 iterations for creating the password hash ● login will take 5, 000 times longer ( e.
EPFL CS 402 Moodle
No question: Moodle
g., 0. 05s instead of 0. 00001s ) ● cracking will be 5, 000 times slower ( e. g., 2 years instead of 4 hours ) 51 salt and iterations : standards there is an official standard for using salt and iterations in hash functions the current version is password based key derivation function 2 ( pbkdf2, rfc 8018 ) used for example in ● wi - fi wpa ● macos user password hashes ● linux disk encryption ( luks ) ● previously for linux passwords ( sha512, 5000 iterations ) 52 memory hard hash functions 53 the modern way of hashing passwords memory hard functions iterating a cryptographic hash function is not the best way to slow down an attacker specialized hardware ( graphics cards, fpgas ) computes tera - hashes in parallel ● e. g., it takes less than 50k transistors to implement sha512 better password hash functions require a certain amount of memory ( e. g., 16mb ) ● for a single login operation, 16mb are easily available ● graphics cards or fpgas would need gigabytes of internal memory to parallelize thousands of hashes ● e. g., it takes millions of transistors to store 16mb of data 54 memory hard functions the functions run through many steps intermediate results are stored in memory each step depends on results from previous steps if you do not have enough memory you can still
EPFL CS 402 Moodle
No question: Moodle
calculate the result ● but you have to recalculate intermediate values again and again typical memory hard hash functions can be parameterized : ● choose the amount of memory needed ● choose the number of steps to calculate 55 memory hard password hash functions scrypt ● invented in 2012 by colin percival and standardized in 2016 ( rfc 7914 ) typical configuration uses about 16mb of memory and less than 100ms of cpu time parameters can be adapted to reflect capabilities of current hardware argon2 ● argon2 ( by biryukov et al. ) was selected 2015 as winner of the password hashing competition organized by jp aumasson and other cryptographers 56 cracking benchmark benchmark of the hashcat password cracker on a geforce rtx 3080 gpu 57 ntlm 93430. 6 mh / s ( windows, no iterations ) sha512crypt $ 6 $ 373. 2 kh / s ( linux, 5000 iterations ) osx v10. 8 + ( pbkdf2 - sha512 ) 1019. 2 kh / s ( osx, 1023 iterations ) cisco - ios $ 9 $ ( scrypt ) 42. 4 kh / s ( n = 16384, r = 1, p = 1 ) when implementing password storage ● always use salt and make the hash function slow ● use yescrypt, scrypt, or argon2 if available ● if
EPFL CS 402 Moodle
No question: Moodle
not, use pbkdf2 password storage in linux most distributions switched to yescrypt ( a memory hard function ) the salt and hash are stored in / etc / shadow : ● $ 1 $ is message digest 5 ( md5 ) ● $ 2a $ is blowfish ● $ 5 $ is 256 - bit secure hash algorithm ( sha - 256 ) ● $ 6 $ is 512 - bit secure hash algorithm ( sha - 512 ) ● $ y $ ( or $ 7 $ ) is yescrypt ● none of the above means des 58 gannimo : $ y $ j9t $ wgssdw7oeaxhw8zyuvpnp / $ 7rjx8odtw2dfdixvsuwgidqmy2ludjt7qcz3gw3uaz0 : 19646 : 0 : 99999 : 7 : : : $ y $ is the type of hash ( yescrypt ), j9t the config, wgssdw7oeaxhw8zyuvpnp / is the salt, 7rj.. az0 the hash summary of password storage never store passwords in cleartext always use salt to store passwords. if you do not : ● multiple hashes can be cracked at once ● hashes can be calculated in advance rainbow tables efficiently store this information salt is insufficient, must slow down hash function ● iterations are
EPFL CS 402 Moodle
No question: Moodle
a good start pbkdf2 is the standard way of doing it ● memory hard functions are better they are more expensive to parallelize ( gpus and fpgas have little internal memory ) examples : yescrypt, scrypt, or argon2 59 secure remote password protocol ( srp ) 60 introduction secure remote password protocol ( srp ) : a password authenticated key exchange ( pake ) a pake allows to ● verify the password of a remote party ● exchange a key ( e. g., for encryption ) in tls, the server can sign its half of the diffie hellman key exchange to prove possession of the private key of the certificate, thus proving its identity pake is similar ( based on diffie hellman ), but authentication is based on the password as key where the server stores information β€œ about ” the password it can ’ t be cracked, even if the attacker sees all messages 61 srp overview srp is like diffie hellman with additional elements that depend on the password it uses exponentiations of a generator ( e. g., gk ) and a modulo for each user, the server stores three elements : 1. the username 2. a salt 3. the password verifier ( the exponentiation of a salted hash of the password ) : 62 the server adds to its part of the diffie - hellman exchange ●
EPFL CS 402 Moodle
No question: Moodle
it contributes to the calculation of the key the client will need to know the salt to calculate, so it first asks for this x = h ( s | h ( u ) | ’ : ’ | p ) v = gx mod n b = ( gx + gb ) mod n srp exchange 63 bob alice knows username and password ( u, p ) ask for salt of user u knows username, salt, and gx ( u, s, gx ) lookup salt calculate password hash x = h ( s | h ( u ) | ’ : ’ | p ) choose random a send salt choose random b they both get k = gb ( a + ux ) mod n add gx to gb u = h ( a | b ) k = ( agux ) b mod n u s a = ga mod n u = h ( a | b ) k = ( b - gx ) a + ux mod n srp summary alice and bob have only exchanged public values : ga and gb + gx eavesdropper cannot learn anything from these values ● in particular : they cannot brute - force the password the resulting key depends on, and ( depends on the password ) bob only knows the public value gx ● if a hacker takes control of bob, they do not learn the password hash ● they could try to brute force the password from gx before continuing, they can send each other an encrypted
EPFL CS 402 Moodle
No question: Moodle
message or a mac to prove that they succeeded in calculating the key 64 summary data security touches three kinds of data : at rest, in transit, and in use data must be protected throughout all layers ( from hardware to app ) passwords may never be stored in cleartext hashing with salt is key, ideally using a memory hard function or repetition remote password authentication allows authentication without leaking passwords 65 com - 402 : information security and privacy 0x15 programming languages mathias payer ( infosec. exchange / @ gannimo ) learning goals for today understand how modern programming languages achieve key safety properties and their security implications differentiate type safety, memory safety, and thread safety as policies how to use sandboxing and compartmentalization to handle complex code 2 motivation 3 4 motivation google security blog : rust in the android platform, april 2021 google security blog : memory safe languages in android 13, dec 2022 microsoft cambridge security research group : trends, challenges, and shifts in software vulnerability mitigation, feb 2019 google β€œ two out of three ” security rule developer may only select 2 of 3 options using a β€œ safe ” programming language makes rule unnecessary 5 consequences of memory safety vulnerabilities in 2022, memory - safety vulnerabilities ● 36 % of vulnerabilities in cve security bulletin ● 86 % of critical severity security vulnerabilities, highest rating ● 89 % of remotely exploitable vulnerabilities over past few years, 78 % of confirmed exploited android β€œ in
EPFL CS 402 Moodle
No question: Moodle
- the - wild ” vulnerabilities 6 memory safety violations are most common 7 https : / / syzkaller. appspot. com / upstream a major portion ( 147 / 442, ~ 33 % ) of bugs found by syzbot is still memory corruption errors. ( 24. 09. 2024 ) memory safety 8 76 % of android vulnerabilities in 2019 24 % of android vulnerabilities in 2024 ~ 70 % of android ’ s high severity security vulnerabilities ( 2021 ) android 13 is first android release where majority of new code is in a memory safe language https : / / security. googleblog. com / 2024 / 09 / eliminating - memory - safety - vulnerabilities - android. html morris worm – nov. 1988 9 β€œ too hard ” to fix ~ 1m lines of code in use at the time is a safe language better for security? β€œ [ the ] nsa recommends using a memory safe language when possible. while the use of added protections to non memory safe languages and the use of memory safe languages do not provide absolute protection against exploitable memory issues, they do provide considerable protection. ” https : / / media. defense. gov / 2022 / nov / 10 / 2003112742 / - 1 / - 1 / 0 / csi _ software _ memory _ safety. pdf 10 three types of safety : type, memory, thread safety 11 type safety 12 is the object an elephant or a crocodile
EPFL CS 402 Moodle
No question: Moodle
? type system 13 logical system that assigns a type to every term ( variable, expression, function ) type of a value specifies which operations can be applied to it type of a variable limits values that it can be assigned type of an expression / function delimits values it accepts and can produce many different type systems ● static / dynamic ● declared / inferred ● strict / relaxed type safety : definition well - typed programs cannot " go wrong ". ( robin milner ) if a type system is sound, then expressions accepted by that type system must evaluate to a value of the appropriate type ( rather than produce a value of some other, unrelated type or crash with a type error ). a language is type - safe if the only operations that can be performed on data in the language are those sanctioned by the type of the data. ● type safety depends on the language ● influenced by static / dynamic semantics 14 main ( ) { f ( 1 ) f ( 1. 0 ) } f ( n ) { return n * 2 } static / dynamic typing 15 in most static systems, without type conversions, this is an error since f accepts an integer argument in most dynamic languages, this would execute without problem since multiplication is defined for both types of numbers static type system is checked by the compiler ( or preprocessors ) before program executes ● type checker uses typing rules to determine type of all terms ● compare inferred types against declared types and operations performed on values ● mismat
EPFL CS 402 Moodle
No question: Moodle
##ch is typing error dynamic type system tracks types of objects at runtime and prevents improper operations from being applied to them static / dynamic typing pros / cons 16 static – checked at compile time ● no runtime overhead ( memory or time ) ● find errors before program runs ● find all errors ● better for building reliable systems and groups of developers dynamic – checked at runtime ● more flexible ( at least without complex type system ) ● fewer type declarations ● better for quick & dirty programming ( β€œ scripting ” ) def f ( a : int ) - > list [ float ] : return [ 1 / n for n in range ( 1, a ) ] declared / inferred types 17 infer n : int infer 1 / n : float languages previously required full type declarations for all functions and variables. compilers only infer expression types. hindley - milner type inference ( algorithm w ) used in haskell. later spread to other languages. ● declare function argument and result type ● compiler infers types in function body ● scala, c #, java ( v8 ), typescript, … struct str { int len ; char first ; } ; struct str * f ( char * s ) { struct str * str = ( struct str * ) malloc ( sizeof ( str ) + strlen ( s ) ) ; str - > len = strlen ( s )
EPFL CS 402 Moodle
No question: Moodle
; strcpy ( & str - > first, s ) ; return str ; } printf ( β€œ % s \ n ”, ( char * ) ( & ( str - > first ) ) ) strict / relaxed ( or weak ) c is not strict! it β€œ trusts ” programmer - supplied type conversions. 18 danger zone! put string inline in struct! what ’ s up with c ’ s type system? 19 c was a thin layer over assembly language, designed by talented programmers for talented programmers ● machines were slow. memory was tight type system did not constrain programmers or prevent them from using assembly language tricks clearly successful, but times change ● correctness and security are far more important, and c ’ s type system is not helpful type safety and security 20 type checking is the only β€œ automatic ” bug detection technique in widespread use ● type system might prevent you from expressing something exactly in the manner you want ● but it will not stop you from expressing a computation : language with type system is still turing - complete ● problems found by sound type system are real errors : no false positives bugs do not always cause security problems, but they can type system can enforce rules that enhance security class foo { int len ; string str ; } foo f ( string str ) { return new foo ( str. length ( ), str. copy ( ) ) ; } c example in java 21 string is not inlined into object. one extra memory
EPFL CS 402 Moodle
No question: Moodle
allocation. type confusion bugs in c 22 # define name _ type 1 # define id _ type 2 struct messagebuffer { int msgtype ; union { char * name ; int nameid ; } ; } ; int main ( int argc, char * * argv ) { char * defaultmessage = " hello world " ; struct messagebuffer buf = {. msgtype = name _ type,. name = defaultmessage } ; buf. nameid = ( int ) ( defaultmessage + 1 ) ; / / bug printf ( " message : % s \ n ", buf. name ) ; / / buf. name is now " ello world " / / even though it's not directly modified! } https : / / cwe. mitre. org / data / definitions / 843. html memory safety 23 is the monkey caged or free? memory safety is an essential programming language property code can only access data within live regions of memory whose pointer is properly obtained int f ( int [ ] array, int i ) { return array [ i ] } memory safety 24 java array with known upper and lower bounds i must be between upper and lower bounds memory safety definition 25 memory safety ensures that only valid objects are accessed in bounds spatial memory safety : objects are only accessed in bounds ● after pointer arithmetic, the new pointer still points to the same object temporal memory safety : only
EPFL CS 402 Moodle
No question: Moodle
valid objects are accessed ● the underlying object has not been freed memory corruption unintended modification of memory location due to missing / faulty safety check 26 void vulnerable ( int user1, int * array ) { / / missing bound check for user1 array [ user1 ] = 42 ; } spatial memory safety error the pointer is updated to point outside of the valid object the pointer is used to dereference invalid memory 27 void vulnerable ( ) { char buf [ 12 ] ; char * ptr = buf [ 11 ] ; * ptr + + = 10 ; * ptr = 42 ; / / out of bound write! } temporal memory safety error the referenced object is freed and no longer β€œ live ” the pointer is used to dereference invalid memory 28 void vulnerable ( char * buf ) { free ( buf ) ; buf [ 12 ] = 42 ; / / use after free! } 29 bounds checking ● check that every indexed memory reference is within array bounds ● compiler optimizations can eliminate some runtime checks lifetime tracking ● use after free is not allowed ● double free is not allowed ● memory leakage is bad ( but allowed ) automated storage reclamation ● garbage collection ● reference counting ● smart pointers / borrow checking memory safety : implementation 30 every region of memory has a length associated with it ● c ’ s interior pointers make tracking more complex ● programmer needs to verify that every memory access is in - bounds manually ● almost every other modern pl automatically inserts bound
EPFL CS 402 Moodle
No question: Moodle
check for array access spatial memory safety : array access int array _ access ( int array [ ], int size, int index ) { if ( index > size ) return 0 ; else / / * ( array + i * sizeof ( int ) ) return array [ index ] ; } pub fn access _ slice ( bytes : & [ u8 ], index : usize ) - > u8 { return bytes [ index ] ; } access _ slice : cmp rdx, rsi jae. out _ of _ bound movzx eax, byte ptr [ rdi + rdx ] ret. out _ of _ bound : push rax lea rax, [ rip +. l _ _ unnamed _ 1 ] mov rdi, rdx mov rdx, rax call qword ptr [ rip + core : : panicking : : panic _ bounds _ check @ gotpcrel ] rust bounds checking 31 rust automatically insert bounds check for slices. aborts when index is out of bound. overhead of bounds checking 32 [ 1 ] santosh nagarakatte, jianzhou zhao, milo m. k. martin, and steve zdancewic. 2009. softbound : highly compatible and complete spatial memory safety for c. ( pldi'09 ). [ 2 ] stefan marr, the cost of safety in java, october 2022. https : / / stefan - marr. de / 2022 / 10
EPFL CS 402 Moodle
No question: Moodle
/ cost - of - safety - in - java / [ 3 ] griffin smith, how much does rust's bounds checking actually cost?, november 2022. https : / / blog. readyset. io / bounds - checks / overhead for enforcing spatial memory safety for c code is significant ● softbound reported 67 % overhead [ 1 ] ● β€œ unfortunately, c's arbitrary pointer arithmetic, conflation of pointers and arrays, and programmer - visible memory layout make retrofitting c / c + + with spatial safety guarantees extremely challenging. ” overhead for java is not nearly as large ● stefan marr reported 3 - 10 % on small benchmarks [ 2 ] ● griffin smith found roughly same for rust [ 3 ] automated storage reclamation 33 reclaim and reuse memory that will not be accessed in future execution ● conservative approximation : reclaim when memory is not reachable prevent errors with manual reclamation ( malloc / free ) ● double free ● use after free ● ( not freeing ) many algorithms (! ) ● reference counting ● garbage collection 34 temporal memory safety and security double free is an integrity concern ● libc ’ s memory allocator stores metadata alongside allocated objects. ● freeing memory chunks twice will corrupt these metadata. ● the corrupted metadata can lead to two different pointers pointing to the same memory location. if an attacker controls one of those pointers, they can change the contents of that memory, which can cause security issues or even allow them to execute code. missing free is an
EPFL CS 402 Moodle
No question: Moodle
availability concern ● basis for denial - of - service attacks ( out - of - memory ) https : / / book. hacktricks. xyz / binary - exploitation / libc - heap / double - free 35 reference counting every block of memory maintains a count of numbers of pointers to it ● one when block allocated ● copying pointer increments count ● dropping pointer decrements count conceptually simple, but fidgety to get right ( try it ) memory freed immediately when last pointer is dropped ( count = 0 ) ● no pauses ( unlike gc ) ● incr / decr overhead can be significant count never reaches zero in graphs with cycles language implementations : python, php 36 reference counting example x = [ 1, 2, object ( ) ] y = x last = x [ - 1 ] x. pop ( ) del last live demo on python tutor 2 1 x list global frame object instance 37 reference counting example x = [ 1, 2, object ( ) ] y = x last = x [ - 1 ] x. pop ( ) del last 2 1 x y list object instance global frame 38 reference counting example x = [ 1, 2, object ( ) ] y = x last = x [ - 1 ] x. pop ( ) del last 2 1 x y last list object instance global frame 39 reference counting example x = [ 1, 2, object ( ) ] y = x last = x [ - 1 ] x. pop ( ) del last
EPFL CS 402 Moodle
No question: Moodle
2 1 x y last list object instance global frame 40 reference counting example x = [ 1, 2, object ( ) ] y = x last = x [ - 1 ] x. pop ( ) del last 2 1 x y list global frame 41 garbage collection ( gc ) when program is running out of free memory, stop and run collector to find unreachable objects pauses program execution uncollected garbage increases memory requirements may be less expensive than rc collects unreachable cyclic structures language implementations : javascript ( v8, spidermonkey ), ruby, lua 42 mark and sweep gc object 6 object 1 object 2 object 3 object 4 object 8 object 7 object 5 sweep root set mark 43 garbage collection overhead is difficult to measure ● what is baseline? no allocation? malloc / free? other gc? ● gc affects behavior of caches and program performance has a reputation for being significant ● depends on how program is written as well more troublesome is unpredictable interruptions ● there are pause - free gcs gc overhead c + + smart pointers as an intermediary step, c + + introduced the notion of β€œ smart pointers ”, for automatic memory management. ( note : not mandatory to use them. ) smart pointers automatically free their referenced content when it goes out of scope ( or refcount reaches zero ). ● unique _ ptrs : unique reference to an object in heap, cannot be copied. ● shared _ ptrs :
EPFL CS 402 Moodle
No question: Moodle
reference counted pointers, similar to those used in python. ● weak _ ptr : used together with shared _ ptrs to break reference cycles. 44 c + + smart pointers : example 45 class smartptr { int * ptr ; / / actual pointer public : explicit smartptr ( int * p = null ) { ptr = p ; } / / destructor ~ smartptr ( ) { delete ( ptr ) ; } / / overload dereferencing operator int & operator * ( ) { return * ptr ; } } ; int main ( ) { smartptr ptr ( new int ( ) ) ; * ptr = 20 ; cout < < * ptr ; / / we don't need to call delete ptr / / when the object ptr goes out of scope, / / the destructor for it is automatically called / / and destructor does delete. return 0 ; } safe programming language ( type and memory ) ● ownership types reduce need for runtime garbage collection ● allows unsafe code for low - level programming ● efficient code, no garbage collection, optional reference counting becoming popular for systems programming ● already in use for linux kernel modules the rust programming language ( β€œ the rust book ” ) 46 rust let v = vec! [ 1, 2, 3 ] ; let v2 = v ; println! ( " v [ 0 ] is : { } ", v [
EPFL CS 402 Moodle
No question: Moodle
0 ] ) ; 47 error : use of moved value : ` v ` println! ( " v [ 0 ] is : { } ", v [ 0 ] ) ; variables own the value they are bound to ( contain ) when variable goes out of scope, value is deallocated key restriction : exactly one variable can be bound to a value a step forward from c + + smart pointers, as the compiler strictly enforces the constraint. in c + +, developers can still choose to use raw pointers. rust ownership 48 ownership is a very restrictive rule that often gets in the way ● how do we pass a value to a function? β€œ borrowing ” handles common situations by sharing ownership between two variables so long as ● borrower ’ s lifetime is no longer than owner ’ s lifetime ● either one writer or multiple readers rust β€œ borrowing ” fn foo ( v1 : & vec < i32 >, v2 : & vec < i32 > ) - > i32 { / / do stuff with v1 and v2 dbg! ( v1, v2 ) / / return the answer 42 } let v1 = vec! [ 1, 2, 3 ] ; let v2 = vec! [ 1, 2, 3 ] ; let answer = foo ( & v1, & v2 ) ; / / we can use v1 and v2 here! 49 reference – borrows object without taking ownership reference is immutable
EPFL CS 402 Moodle
No question: Moodle
, need mutable reference if foo changes v1 or v2 borrowing example fn main ( ) { let mut x = 5 ; let y = & mut x ; / / removing this line works / / single mutable borrow dbg! ( & x ) ; * y + = 1 ; } 50 read / write restriction cannot have mutable and immutable borrow to a value at the same time rust ownership pain β€œ implement a linked list ” is a meme in the rust community. ● people wrote an 8 - chapter book * on implementing linked lists in rust. ● a singly linked list is already quite verbose. need to use option and box. ● a doubly linked is challenging due to cyclic reference of the previous node and next node. 51 * learn rust with entirely too many linked lists rust ownership : singly linked list ● box is required as otherwise, node references itself, resulting in infinite - size struct. ● option is needed because tail of the linked list does not have a next node. null pointers are disallowed in rust. ● current node owns next node 52 struct node { data : i32, next : option < box < node > >, } rust ownership : doubly linked list ● rc ( reference counting ) is needed because prev and next cannot own each other. ● refcell is needed for interior mutability. when inserting / deleting a node, we need
EPFL CS 402 Moodle
No question: Moodle
a mutable borrow to both neighbors. ● still needs to implement a custom destructor to avoid memory leak. ● bad performance due to multiple layers of wrapping. 53 struct node { data : i32, prev : option < rc < refcell < node > > >, next : option < rc < refcell < node > > >, } 54 rust also allows unsafe code that would not pass borrow checker put unsafe code in module and wrap in safe interface almost all non - trivial data structures implemented this way ● linked lists, trees ● what does that say about type system? easier to understand and hand - verify a small amount of code that is explicitly marked unsafe unsafe code unsafe code growing a vector is implemented in unsafe rust, hidden away from users 55 fn grow ( & mut self ) { let new _ cap = if self. cap = = 0 { 1 } else { 2 * self. cap } ; let new _ layout = layout : : array : : < t > ( new _ cap ). unwrap ( ) ; let new _ ptr = if self. cap = = 0 { / / unsafe allocation of raw memory, calls to ` malloc `. unsafe { alloc : : alloc ( new _ layout ) } } else { let old _ layout = layout : : array : : < t > ( self. cap ). unwrap ( ) ; let old _ ptr = self. ptr
EPFL CS 402 Moodle
No question: Moodle
. as _ ptr ( ) as * mut u8 ; unsafe { alloc : : realloc ( old _ ptr, old _ layout, new _ layout. size ( ) ) } } ; } 56 rewrite everything in rust? in many cases, simply not possible. ● chromium is over 33 million lines of code. ( mostly c + + ) ● the linux kernel is around 30 million lines of code ( mostly c ) ● simply too much to rewrite for old code ● employ fuzzing, mitigation and hardening ( defense in - depth ) for newer code ● prefer safe language like rust ( linux kernel modules, android binder ) 57 google rewrite everything in rust? clean slate not needed, simply writing new code in rust suffices! thread safety 58 code runs in parallel and may access the same data structures faster ( or slower ) thread safety thread - safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without unintended interaction. [ 1 ] examples of concurrency bugs ● race condition : when two or more threads attempt to access and modify shared data simultaneously without proper synchronization, it can lead to inconsistent data states. ● deadlock : deadlocks occur when two or more threads are blocked forever, each waiting for the other to release a resource. concurrency bugs can have security consequences : dirty cow 59 [ 1 ] : https : / / en.
EPFL CS 402 Moodle
No question: Moodle
wikipedia. org / wiki / thread _ safety dirty cow a local privilege escalation attack that exploits a race condition in the linux kernel memory - management subsystem. cow : copy on write, a mechanism for efficiently sharing modifiable data. used extensively in the mmap and fork syscall. with the right timing, a read - only mapping of a file can be turned into a writable mapping 60 cve - 2016 - 5195 thread safety in programming languages modern languages include type - safe synchronization primitives in their stdlib : ● locks ● semaphores ● atomic variables, … other thread - safe language constructs ● java : synchronized keyword ● go : goroutines and channels ● rust : ownership modern languages makes it easier to write thread - safe program, but ultimately it ’ s the programmer ’ s responsibility to ensure the correctness of concurrent programs. 61 thread safety in java in java, the synchronized keyword is used in the declaration of a method or code block to acquire the mutex lock for an object while the current thread executes the code. 62 class counter { private int i = 0 ; public synchronized void inc ( ) { i + + ; } } thread safety in go don ’ t communicate by sharing memory, share memory by communicating. goroutines : threads created by the go runtime, cheap and fast. channels : means of communication between goroutines. data is copied from one
EPFL CS 402 Moodle
No question: Moodle
end of the channel to another. it ’ s possible to send pointers, but that once again may create issues. 63 func main ( ) { / / creates a channel messages : = make ( chan string ) / / creates a new goroutine / / sends data into the channel ( goroutine thread ) go func ( ) { messages < - " ping " } ( ) / / receives data from the channel ( main thread ) msg : = < - messages fmt. println ( msg ) } thread safety in rust the same mechanism that guarantees temporal memory safety also ensures thread safety : ownership recall in rust borrowing ● owner ’ s lifetime must outlast borrowers lifetime - > no use - after - free. ● either one writer or multiple readers - > no data races fearless concurrency in rust 64 thread safety in rust : compilation error! 65 thread safety in rust : fix 66 pub fn parent ( ) { let vec = vec! [ 1, 2, 3 ] ; / / move ownership of vec into spawned thread / / parent will not be allowed to access vec from now on thread : : spawn ( move | | { dbg! ( & vec ) ; } ) ; } thread safety in rust : mutex for concurrent write 67 pub fn parent ( ) { / / use atomic reference counting to ensure / / vec lives after parent returns. / / use mutex to ensure concurrent write is serialized. let
EPFL CS 402 Moodle
No question: Moodle
wrapped = arc : : new ( mutex : : new ( vec! [ 1, 2, 3 ] ) ) ; let copy = wrapped. clone ( ) ; thread : : spawn ( move | | { dbg! ( copy. lock ( ). unwrap ( ) ) ; } ) ; wrapped. lock ( ). unwrap ( ). push ( 3 ) ; } sandboxing & compartmentalization 68 principle of least privilege 69 the principle of least privilege ensures that a component has the least privileges needed to function ● no extra functionality is present ● any additionally removed functionality would impact ( some ) functionality ● any added functionality would not increase ( any ) functionality sandboxing 70 sandboxing implements principle of least privilege by running programs ( often untrusted code ) in an isolated, restricted environment sandboxing is usually a implementation feature of programming languages instead of design feature. depending on the context / application, a script may or may not be sandboxed. implemented by restricting access to certain library / system calls ● seccomp ( selinux ) ● cgroup ( docker ) implementation β€œ only ” at the language level is challenging sandboxing example javascript / webassembly inside the browser interpreters ( ghostscript / vba macros ) embedded inside word processors without explicit permission from the user, opening a web page or document shouldn ’ t leak secrets in your local hard disk the premise of sandboxing providing security relies entirely on
EPFL CS 402 Moodle
No question: Moodle
the implementation of the sandbox. bugs may still lead to sandbox breaches 71 flash and vba macros used to be security nightmares ( now phased out ) javascript engine bugs remain a source of critical browser vulnerabilities sandboxing : hard to get right 72 compartmentalization 73 compartmentalization can enforce principle of least privilege break a complex system into small components limit the access of entities to only what is necessary prevent error propagation in the system to diminish impact * image from arm morello project compartmentalization : chromium sandboxed render engines : cannot affect the world, except via the exposed api ● start process, establish ipc channel ● drop all access privileges ● do not require admin rights 74 if a webpage in a tab crashes, it should not bring other tabs or the entire browser down! compartmentalization : chromium browser kernel api : decide how render engines influence the outside world ● user interaction : display rendered bitmaps, forward input events ● storage : manage cookies, passwords, authorize uploads, restrict downloads ● network : handle http requests and responses, restrict certain schemes ( e. g., file : / / ) 75 compartmentalization in pl what should a basic entity be : functions, libraries? ( component ) how should each component interact with each other? ( policy ) efficient software - based fault isolation enclosure : language - based restriction of untrusted libraries 76 for the homework you will play with the
EPFL CS 402 Moodle
No question: Moodle
increasing safety in the programming languages paradigm by converting c code to rust code using safe code practices concerning ● external code ● memory pointers ● union types ● global variables ● name mangling securing unsafe code with compile - time checks or runtime fails ● stack spatial safety ● stack temporal safety ● heap temporal safety ● heap spatial safety ● type safety 77 summary memory safety issues remain dominant. modern pls achieve memory safety through bounds checking, lifetime tracking and automatic storage reclamation. a programming language ’ s type system can be static / dynamic, inferred / declared, strict / relaxed. a well - designed type system prevents type confusion bugs. modern languages provide synchronization primitives and incorporate thread - safe constructs in their design sandboxing / compartmentalization can enforce least privileges 78 com - 402 : information security and privacy 0x16 web and software bugs mathias payer ( infosec. exchange / @ gannimo ) learning goals for today web applications and regular applications have a lot in common understand the impact of processing attacker - controlled data differentiate between types of bugs and what potential attacks they enable 2 web application security owasp top 10 : common vulnerabilities achieving arbitrary code execution ● cross - site scripting ( xss ) : executing javascript code ● sql injection : executing sql code ● ldap injection : executing ldap queries ● command injection : executing shell commands 3 open web application security project ( owasp ) many useful projects, for example : ● ow
EPFL CS 402 Moodle
No question: Moodle
##asp top 10 ● tool : zed attack proxy ( zap ) ● method : owasp testing guide the β€œ top 10 ” project documents the 10 most critical security risks to web apps ● updated frequently, current : 2021 ● https : / / owasp. org / top10 / ● cross - references cwes 4 cve : common vulnerabilities and exposures cwe : common weakness enumeration owasp top 10 : a01 broken access control access control enforces policy such that users cannot act outside of their intended permissions. failures typically lead to unauthorized information disclosure, modification, or destruction of all data or performing a business function outside the user's limits. ● cwe - 200 : exposure of sensitive information to an unauthorized actor, cwe - 201 : insertion of sensitive information into sent data, and cwe - 352 : cross - site request forgery ● reduce attack surface by β€œ deny by default ” ● implement access control mechanisms once, reuse through app ( use session ) ● log access control failures ● rate limit api calls 5 owasp top 10 : a01 broken access control 6 https : / / portswigger. net / web - security / access - control real world example : accessing everyones google drive files with google classrooms google classrooms : 1. teacher creates a classroom and adds students to that room 2. students submit google documents to classroom 3. teacher becomes owner of that document http request when student submits a document :
EPFL CS 402 Moodle
No question: Moodle
post / v7 / writesubmission? _ reqid = 4786040 & rt = j http / 1. 1 host : classroom. google. com f. req = [ [ 3 ], [ [ [ " 18537069787 ", [ " 46653220298 ", [ " 41400909728 " ] ] ], [ [ " 18537069787 ", [ " 46653220298 ", [ " 41400909728 " ] ] ], null, null, null, [ [ null, null, " 1h8trewm8cp6bsv24bwmlimfrj3w1d7sdpxyhfur1rgw ", 2, " application / vnd. google - apps. ritz " marked in bold is the google drive document id of the submitted document. google forgot to add checks on that value, students could submit any google drive document of any user and teacher would become owner of that document … 7 https : / / secreltyhiddenwriteups. blogspot. com / 2024 / 07 / leaking - all - users - google - drive - files. html owasp top 10 : a02 cryptographic failures the first thing is to determine the protection needs of data in transit and at rest. for example, passwords, credit card numbers, health records, personal information, and
EPFL CS 402 Moodle
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1