1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
// Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! # PsaAeadEncrypt operation
//!
//! Process an authenticated encryption operation.

use super::psa_key_attributes::Attributes;
use crate::operations::psa_algorithm::Aead;
use crate::requests::ResponseStatus;
use derivative::Derivative;

/// Native object for AEAD encryption operations.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Operation {
    /// Defines which key should be used for the encryption operation.
    pub key_name: String,
    /// An AEAD encryption algorithm that is compatible with the key type.
    pub alg: Aead,
    /// Nonce or IV to use.
    #[derivative(Debug = "ignore")]
    pub nonce: zeroize::Zeroizing<Vec<u8>>,
    /// Additional data that will be authenticated but not encrypted.
    #[derivative(Debug = "ignore")]
    pub additional_data: zeroize::Zeroizing<Vec<u8>>,
    /// Data that will be authenticated and encrypted.
    #[derivative(Debug = "ignore")]
    pub plaintext: zeroize::Zeroizing<Vec<u8>>,
}

impl Operation {
    /// Validate the contents of the operation against the attributes of the key it targets
    ///
    /// This method checks that:
    /// * the key policy allows encrypting messages
    /// * the key policy allows the encryption algorithm requested in the operation
    /// * the key type is compatible with the requested algorithm
    /// * the message to encrypt is valid (not length 0)
    /// * the nonce is valid (not length 0)
    pub fn validate(&self, key_attributes: Attributes) -> crate::requests::Result<()> {
        key_attributes.can_encrypt_message()?;
        key_attributes.permits_alg(self.alg.into())?;
        key_attributes.compatible_with_alg(self.alg.into())?;
        if self.plaintext.is_empty() || self.nonce.is_empty() {
            return Err(ResponseStatus::PsaErrorInvalidArgument);
        }
        Ok(())
    }
}

/// Native object for AEAD encrypt result.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Result {
    /// The `ciphertext` field contains the encrypted and authenticated data.For algorithms where
    /// the encrypted data and the authentication tag are defined as separate outputs, the authentication
    /// tag is appended to the encrypted data.
    #[derivative(Debug = "ignore")]
    pub ciphertext: zeroize::Zeroizing<Vec<u8>>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::operations::psa_algorithm::AeadWithDefaultLengthTag;
    use crate::operations::psa_key_attributes::{Lifetime, Policy, Type, UsageFlags};
    use psa_crypto::types::algorithm::Aead;

    fn get_attrs() -> Attributes {
        Attributes {
            lifetime: Lifetime::Persistent,
            key_type: Type::Aes,
            bits: 0,
            policy: Policy {
                usage_flags: UsageFlags {
                    encrypt: true,
                    ..Default::default()
                },
                permitted_algorithms: Aead::AeadWithDefaultLengthTag(AeadWithDefaultLengthTag::Ccm)
                    .into(),
            },
        }
    }

    #[test]
    fn validate_success() {
        (Operation {
            key_name: String::from("some key"),
            alg: AeadWithDefaultLengthTag::Ccm.into(),
            plaintext: vec![0xff, 32].into(),
            nonce: vec![0xaa, 12].into(),
            additional_data: vec![0xff, 16].into(),
        })
        .validate(get_attrs())
        .unwrap();
    }

    #[test]
    fn cannot_encrypt() {
        let mut attrs = get_attrs();
        attrs.policy.usage_flags.encrypt = false;
        assert_eq!(
            (Operation {
                key_name: String::from("some key"),
                alg: AeadWithDefaultLengthTag::Ccm.into(),
                plaintext: vec![0xff, 32].into(),
                nonce: vec![0xaa, 12].into(),
                additional_data: vec![0xff, 16].into()
            })
            .validate(attrs)
            .unwrap_err(),
            ResponseStatus::PsaErrorNotPermitted
        );
    }

    #[test]
    fn wrong_algorithm() {
        assert_eq!(
            (Operation {
                key_name: String::from("some key"),
                alg: AeadWithDefaultLengthTag::Gcm.into(),
                plaintext: vec![0xff, 32].into(),
                nonce: vec![0xaa, 12].into(),
                additional_data: vec![0xff, 16].into()
            })
            .validate(get_attrs())
            .unwrap_err(),
            ResponseStatus::PsaErrorNotPermitted
        );
    }

    #[test]
    fn invalid_plaintext() {
        assert_eq!(
            (Operation {
                key_name: String::from("some key"),
                alg: AeadWithDefaultLengthTag::Ccm.into(),
                plaintext: vec![].into(),
                nonce: vec![0xaa, 12].into(),
                additional_data: vec![0xff, 16].into()
            })
            .validate(get_attrs())
            .unwrap_err(),
            ResponseStatus::PsaErrorInvalidArgument
        );
    }

    #[test]
    fn invalid_nonce() {
        assert_eq!(
            (Operation {
                key_name: String::from("some key"),
                alg: AeadWithDefaultLengthTag::Ccm.into(),
                plaintext: vec![0xff, 32].into(),
                nonce: vec![].into(),
                additional_data: vec![0xff, 16].into()
            })
            .validate(get_attrs())
            .unwrap_err(),
            ResponseStatus::PsaErrorInvalidArgument
        );
    }
}