Saturday, October 12, 2019

What is ECB and CBC


The really simple explanation for the difference between the two is this:

ECB (electronic code book) is basically raw cipher. For each block of input, you encrypt the block and get some output. The problem with this transform is that any resident properties of the plaintext might well show up in the ciphertext – possibly not as clearly – that's what blocks and key schedules are supposed to protect againt, but analyzing the patterns you may be able to deduce properties that you otherwise thought were hidden.

CBC mode is short for cipher block chaining. You have an initialization vector which you XOR the first block of plaintext against. You then encrypt that block of plaintext. The next block of plaintext is xor'd against the last encrypted block before you encrypt this block.


The advantages of CBC over ECB are many – with ECB, assuming many things, you could manage a partial decryption and easily fill in the blanks, for example if extracting data from an encrypted hard disk. With CBC, if you are missing a few blocks in the sequence encryption becomes impossible. However, there is one downside to CBC – ECB naturally supports operation in parallel since each block can be encrypted independently of the next. However, with CBC this is harder, since you have to wait on each block. (You can still parallelize decryption, though.)

CBC itself can also be considered vulnerable in certain situations, specifically the use of predictable IVs and unauthenticated decryption can allow you to guess plaintexts as explained in this answer and in more detail here.

The IV problem is resolved by using unpredictable (cryptographically random) IVs. The authentication problem is traditionally resolved using message authentication codes - however, implementation of these is not perfect. Dedicated modes have been invented which tackle the issue of authentication too, for example EAX and Galois Counter Mode.

Other modes exist to deal with specific scenarios, e.g.:

Counter Mode uses the fact that a block cipher's output in ECB mode should be indistinguishable from random, and XOR's the result of encrypting a counter+iv combination as a stream cipher.
XTS is a mode of operation used in disk encryption.
The key point to take away is that each mode has a number of merits and implementation concerns and these must be weighed up carefully (and correctly implemented). And, where possible, avoid ECB.


references:
https://crypto.stackexchange.com/questions/225/should-i-use-ecb-or-cbc-encryption-mode-for-my-block-cipher


Which Encryption mode to Choose?

ECB should not be used if encrypting more than one block of data with the same key.

CBC, OFB and CFB are similar, however OFB/CFB is better because you only need encryption and not decryption, which can save code space.

CTR is used if you want good parallelization (ie. speed), instead of CBC/OFB/CFB.

XTS mode is the most common if you are encoding a random accessible data (like a hard disk or RAM).

OCB is by far the best mode, as it allows encryption and authentication in a single pass. However there are patents on it in USA.

The only thing you really have to know is that ECB is not to be used unless you are only encrypting 1 block. XTS should be used if you are encrypting randomly accessed data and not a stream.

You should ALWAYS use unique IV's every time you encrypt, and they should be random. If you cannot guarantee they are random, use OCB as it only requires a nonce, not an IV, and there is a distinct difference. A nonce does not drop security if people can guess the next one, an IV can cause this problem.


references:
https://stackoverflow.com/questions/1220751/how-to-choose-an-aes-encryption-mode-cbc-ecb-ctr-ocb-cfb


What is Google Key Management Service?



Cryptographic key management : Cloud KMS is a cloud-hosted key management service that lets you manage cryptographic keys for your cloud services the same way you do on-premises. You can generate, use, rotate, and destroy AES256, RSA 2048, RSA 3072, RSA 4096, EC P256, and EC P384 cryptographic keys. Cloud KMS is integrated with Cloud IAM and Cloud Audit Logging so that you can manage permissions on individual keys and monitor how these are used. Use Cloud KMS to protect secrets and other sensitive data that you need to store in Google Cloud Platform.

Scalable, automated, fast
Keep millions of cryptographic keys, allowing you to determine the level of granularity at which to encrypt your data. Set keys to automatically rotate regularly, using a new primary version to encrypt data and limit the scope of data accessible with any single key version. Keep as many active key versions as you want. Rely on our low latency to ensure you can access your keys quickly.

Greater management over key use
Manage Cloud IAM permissions for user-level permissions on individual keys and grant access to both individual users and service accounts. View admin activity and key use logs with Cloud Audit Logging, using Cloud KMS as a central point to filter access to your most sensitive data. Monitor logs to ensure proper use of your keys.

Easily encrypt and sign data
Cloud KMS gives you the flexibility to encrypt your data with either a symmetric or asymmetric key that’s under your control. You can also perform signing operations with both RSA and elliptic curve keys of various lengths.

Implement envelope encryption
Implement a key hierarchy with a local data encryption key (DEK), protected by a key encryption key (KEK) in Cloud KMS. Manage keys used to encrypt your data at the application layer, stored in your storage systems, at Google, or anywhere else.

Help satisfy compliance needs
With Cloud KMS, you can manage the encryption keys used to protect sensitive data residing across GCP with customer managed encryption keys (CMEK). For compliance mandates requiring that keys and crypto operations be performed within a hardware environment, the Cloud KMS integration with Cloud HSM makes it simple to create a key protected by a FIPS 140-2 Level 3 device.


references:
https://cloud.google.com/kms/

Firebase encrypting user data with Public / Private key pair

After user A logs in a random public private key pair is generated on his phone. eg.: use Ecc Curve25519
The private key from A is stored securely on his phone
The public key from A is stored in firebase and is accessible to anybody that chats with A.
If X sends a message to A he fetches the public key from A from firebase encrypts the message for A locally and stores the encrypted message on firebase in the inbox from A
A downloads the encrypted message from firebase and decrypts it with his private key stored on his phone
(vice versa for A to X)

If A want's to move to another phone or wants to use multiple phones you can do this that way:

Ask A to define a strong password to encrypt his locally stored private key. (or create a random passphrase and use QR codes for key exchange)
Encrypt the private key locally (eg.: use AES256) on his phone with the password from step 1 and upload it to firebase. (optional sign it with his private key)
Download the encrypted private key from the second device from A
Ask for the passphrase on the second device from A and store the private key securely (optional check the signature with the public key from A)
Delete the encrypted private key from firebase if no backup is wanted

references:
https://stackoverflow.com/questions/38304258/how-to-encrypt-user-data-in-firebase

Do firebase encrypt the data on transit as well as on Rest?


Google Cloud Platform encrypts customer data stored at rest by default, with no additional action required from you

Data in Google Cloud Platform is broken into subfile chunks for storage, and each chunk is encrypted at the storage level with an individual encryption key. The key used to encrypt the data in a chunk is called a data encryption key (DEK). Because of the high volume of keys at Google, and the need for low latency and high availability, these keys are stored near the data that they encrypt. The DEKs are encrypted with (or “wrapped” by) a key encryption key (KEK). Customers can choose which key management solution they prefer for managing the KEKs that protect the DEKs that protect their data.

The summary is that the data is encrypted in transit, and it is stored on encrypted disks on the servers. If you enable local persistence on the device, the on device data is not encrypted.

But administrators of the app can see the data in the Firebase console. If it is a requirement of your app that administrators can't read this data, then you'll need to encrypt it on the client before sending it to Firebase.


references:
https://stackoverflow.com/questions/38788258/encryption-of-data-between-clients-and-firebase-real-time-database
https://cloud.google.com/security/encryption-at-rest/#googles_default_encryption



Friday, September 13, 2019

iOS UNUserNotifications Learning



The trigger is the main this. We can either use TimeInterval or Calendar Trigger.
For repeating intervals, 60 seconds or more must be the minimum between two repeating ones.
Does it actually apply for non repeating? For e.g. If we set 5 different alarms separately
With 5 different identifiers, do they fire? To be checked!

From the investigations by doing sample, the info that I could collect is that we are not able to
Get the notification even if not repeat is set to true and even if the identifier is set as unique one,
It just posts for 2 and then it stops posting!. Not sure if it is something specific to testing


OK with a bit of investigation, the crux is around the type of trigger. The time interval trigger could be used
For repeating ones.

Below setup works well to repeat the notification every X times

let content = UNMutableNotificationContent()
        content.title = "Pizza Time!!"
        content.body = "Monday is Pizza Day"

var timeInterval : TimeInterval = 60;

let trigger = UNTimeIntervalNotificationTrigger(
            timeInterval: timeInterval,
            repeats: true)
        content.title = "Pizza Time!! "
        let request = UNNotificationRequest(identifier: baseID, content: content, trigger: trigger)
       
        UNUserNotificationCenter.current().add(request) { (error) in
            if let error = error {
                print("error in pizza reminder: \(error.localizedDescription)")
            }
        }


Now as per documentation, we should not have < 60 seconds for a repeating one.

This works best if schedule every X second using scheduler interval than calendar date.


References:
https://makeapppie.com/2017/01/31/how-to-repeat-local-notifications/

CWE, and CERT Secure Coding Standards



Common Weakness Enumeration

The Common Weakness Enumeration (CWE) is a unified, measurable set of software weaknesses that enables the effective discussion, description, selection, and use of software security tools and services that can find these weaknesses in source code and operational systems. The CWE also enables better understanding and management of software weaknesses related to architecture and design. It enumerates design and architectural weaknesses, as well as low-level coding and design errors.

CERT Secure Coding Standards

CERT is developing secure coding standards for commonly used programming languages such as C, C++, and Java through a broad-based community effort that includes members of the software development and software security communities. Well-documented and enforceable coding standards are essential to secure software development. Coding standards encourage programmers to follow a uniform set of rules and guidelines determined by the requirements of the project and organization, rather than by the programmer’s familiarity or preference. Once established, these standards can be used as a metric to evaluate source code (using manual or automated processes) to determine compliance with the standard.

CERT secure coding standards include guidelines for avoiding coding and implementation errors, as well as low-level design errors.

CERT-CWE Relationship
The CWE and the CERT secure coding standards perform separate but mutually supportive roles. Simply stated, the CWE provides a comprehensive repository of known weaknesses, while CERT secure coding standards identify insecure coding constructs that, if present in code, could expose a weakness or vulnerability in the software. Not all weaknesses enumerated in the CWE are present in any particular secure coding standard because not all weaknesses are present in each language and because the CWE also includes high-level design issues. Not all CERT secure coding guidelines are mapped directly to weaknesses in the CWE because some coding errors can manifest in ways that do not directly correlate to any given weakness. Both tools are necessary in evaluating the security and safety of software systems.


References:
https://resources.sei.cmu.edu/library/asset-view.cfm?assetid=50399
https://www.us-cert.gov/bsi/articles/knowledge/coding-practices/mitre-cwe-and-cert-secure-coding-standards