-- Copyright (C) 2016  Fraser Tweedale
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--      http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.

{-# LANGUAGE ScopedTypeVariables #-}

{- |

Advanced Encryption Standard (AES) Key Wrap Algorithm;
<https://https://tools.ietf.org/html/rfc3394>.

-}
module Crypto.JOSE.AESKW
  (
    aesKeyWrap
  , aesKeyUnwrap
  ) where

import Control.Monad.State
import Crypto.Cipher.Types
import Data.Bits (xor)
import Data.ByteArray as BA hiding (replicate, xor)
import Data.Memory.Endian (BE(..), toBE)
import Data.Memory.PtrMethods (memCopy)
import Data.Word (Word64)
import Foreign.Ptr (Ptr, plusPtr)
import Foreign.Storable (peek, peekElemOff, poke, pokeElemOff)
import System.IO.Unsafe (unsafePerformIO)

iv :: Word64
iv :: Word64
iv = Word64
0xA6A6A6A6A6A6A6A6

aesKeyWrapStep
  :: BlockCipher128 cipher
  => cipher
  -> Ptr Word64   -- ^ register
  -> (Int, Int)   -- ^ step (t) and offset (i)
  -> StateT Word64 IO ()
aesKeyWrapStep :: cipher -> Ptr Word64 -> (Int, Int) -> StateT Word64 IO ()
aesKeyWrapStep cipher
cipher Ptr Word64
p (Int
t, Int
i) = do
  Word64
a <- StateT Word64 IO Word64
forall s (m :: * -> *). MonadState s m => m s
get
  Word64
r_i <- IO Word64 -> StateT Word64 IO Word64
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (IO Word64 -> StateT Word64 IO Word64)
-> IO Word64 -> StateT Word64 IO Word64
forall a b. (a -> b) -> a -> b
$ Ptr Word64 -> Int -> IO Word64
forall a. Storable a => Ptr a -> Int -> IO a
peekElemOff Ptr Word64
p Int
i
  ScrubbedBytes
m :: ScrubbedBytes <-
    IO ScrubbedBytes -> StateT Word64 IO ScrubbedBytes
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (IO ScrubbedBytes -> StateT Word64 IO ScrubbedBytes)
-> IO ScrubbedBytes -> StateT Word64 IO ScrubbedBytes
forall a b. (a -> b) -> a -> b
$ Int -> (Ptr Word64 -> IO ()) -> IO ScrubbedBytes
forall ba p. ByteArray ba => Int -> (Ptr p -> IO ()) -> IO ba
alloc Int
16 ((Ptr Word64 -> IO ()) -> IO ScrubbedBytes)
-> (Ptr Word64 -> IO ()) -> IO ScrubbedBytes
forall a b. (a -> b) -> a -> b
$ \Ptr Word64
p' -> Ptr Word64 -> Word64 -> IO ()
forall a. Storable a => Ptr a -> a -> IO ()
poke Ptr Word64
p' Word64
a IO () -> IO () -> IO ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Ptr Word64 -> Int -> Word64 -> IO ()
forall a. Storable a => Ptr a -> Int -> a -> IO ()
pokeElemOff Ptr Word64
p' Int
1 Word64
r_i
  let b :: ScrubbedBytes
b = cipher -> ScrubbedBytes -> ScrubbedBytes
forall cipher ba.
(BlockCipher cipher, ByteArray ba) =>
cipher -> ba -> ba
ecbEncrypt cipher
cipher ScrubbedBytes
m
  Word64
b_hi <- IO Word64 -> StateT Word64 IO Word64
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (IO Word64 -> StateT Word64 IO Word64)
-> IO Word64 -> StateT Word64 IO Word64
forall a b. (a -> b) -> a -> b
$ ScrubbedBytes -> (Ptr Word64 -> IO Word64) -> IO Word64
forall ba p a. ByteArrayAccess ba => ba -> (Ptr p -> IO a) -> IO a
withByteArray ScrubbedBytes
b Ptr Word64 -> IO Word64
forall a. Storable a => Ptr a -> IO a
peek
  Word64
b_lo <- IO Word64 -> StateT Word64 IO Word64
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (IO Word64 -> StateT Word64 IO Word64)
-> IO Word64 -> StateT Word64 IO Word64
forall a b. (a -> b) -> a -> b
$ ScrubbedBytes -> (Ptr Word64 -> IO Word64) -> IO Word64
forall ba p a. ByteArrayAccess ba => ba -> (Ptr p -> IO a) -> IO a
withByteArray ScrubbedBytes
b (Ptr Word64 -> Int -> IO Word64
forall a. Storable a => Ptr a -> Int -> IO a
`peekElemOff` Int
1)
  Word64 -> StateT Word64 IO ()
forall s (m :: * -> *). MonadState s m => s -> m ()
put (Word64
b_hi Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
`xor` BE Word64 -> Word64
forall a. BE a -> a
unBE (Word64 -> BE Word64
forall a. ByteSwap a => a -> BE a
toBE (Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
t)))
  IO () -> StateT Word64 IO ()
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (IO () -> StateT Word64 IO ()) -> IO () -> StateT Word64 IO ()
forall a b. (a -> b) -> a -> b
$ Ptr Word64 -> Int -> Word64 -> IO ()
forall a. Storable a => Ptr a -> Int -> a -> IO ()
pokeElemOff Ptr Word64
p Int
i Word64
b_lo

-- | Wrap a secret.
--
-- Input size must be a multiple of 8 bytes, and at least 16 bytes.
-- Output size is input size plus 8 bytes.
--
aesKeyWrap
  :: (ByteArrayAccess m, ByteArray c, BlockCipher128 cipher)
  => cipher
  -> m
  -> c
aesKeyWrap :: cipher -> m -> c
aesKeyWrap cipher
cipher m
m = IO c -> c
forall a. IO a -> a
unsafePerformIO (IO c -> c) -> IO c -> c
forall a b. (a -> b) -> a -> b
$ do
  let n :: Int
n = m -> Int
forall ba. ByteArrayAccess ba => ba -> Int
BA.length m
m
  c
c <- m -> (Ptr Word8 -> IO c) -> IO c
forall ba p a. ByteArrayAccess ba => ba -> (Ptr p -> IO a) -> IO a
withByteArray m
m ((Ptr Word8 -> IO c) -> IO c) -> (Ptr Word8 -> IO c) -> IO c
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
p ->
    Int -> (Ptr Any -> IO ()) -> IO c
forall ba p. ByteArray ba => Int -> (Ptr p -> IO ()) -> IO ba
alloc (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
8) ((Ptr Any -> IO ()) -> IO c) -> (Ptr Any -> IO ()) -> IO c
forall a b. (a -> b) -> a -> b
$ \Ptr Any
p' ->
      Ptr Word8 -> Ptr Word8 -> Int -> IO ()
memCopy (Ptr Any
p' Ptr Any -> Int -> Ptr Word8
forall a b. Ptr a -> Int -> Ptr b
`plusPtr` Int
8) Ptr Word8
p Int
n
  c -> (Ptr Word64 -> IO ()) -> IO ()
forall ba p a. ByteArrayAccess ba => ba -> (Ptr p -> IO a) -> IO a
withByteArray c
c ((Ptr Word64 -> IO ()) -> IO ()) -> (Ptr Word64 -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Ptr Word64
p -> do
    let coords :: [(Int, Int)]
coords = [Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
1..] ([[Int]] -> [Int]
forall (m :: * -> *) a. Monad m => m (m a) -> m a
join (Int -> [Int] -> [[Int]]
forall a. Int -> a -> [a]
replicate Int
6 [Int
1 .. Int
n Int -> Int -> Int
forall a. Integral a => a -> a -> a
`div` Int
8]))
    Word64
a <- StateT Word64 IO () -> Word64 -> IO Word64
forall (m :: * -> *) s a. Monad m => StateT s m a -> s -> m s
execStateT (((Int, Int) -> StateT Word64 IO ())
-> [(Int, Int)] -> StateT Word64 IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (cipher -> Ptr Word64 -> (Int, Int) -> StateT Word64 IO ()
forall cipher.
BlockCipher128 cipher =>
cipher -> Ptr Word64 -> (Int, Int) -> StateT Word64 IO ()
aesKeyWrapStep cipher
cipher Ptr Word64
p) [(Int, Int)]
coords) Word64
iv
    Ptr Word64 -> Word64 -> IO ()
forall a. Storable a => Ptr a -> a -> IO ()
poke Ptr Word64
p Word64
a
  c -> IO c
forall (m :: * -> *) a. Monad m => a -> m a
return c
c

aesKeyUnwrapStep
  :: BlockCipher128 cipher
  => cipher
  -> Ptr Word64   -- ^ register
  -> (Int, Int)   -- ^ step (t) and offset (i)
  -> StateT Word64 IO ()
aesKeyUnwrapStep :: cipher -> Ptr Word64 -> (Int, Int) -> StateT Word64 IO ()
aesKeyUnwrapStep cipher
cipher Ptr Word64
p (Int
t, Int
i) = do
  Word64
a <- StateT Word64 IO Word64
forall s (m :: * -> *). MonadState s m => m s
get
  Word64
r_i <- IO Word64 -> StateT Word64 IO Word64
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (IO Word64 -> StateT Word64 IO Word64)
-> IO Word64 -> StateT Word64 IO Word64
forall a b. (a -> b) -> a -> b
$ Ptr Word64 -> Int -> IO Word64
forall a. Storable a => Ptr a -> Int -> IO a
peekElemOff Ptr Word64
p Int
i
  let a_t :: Word64
a_t = Word64
a Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
`xor` BE Word64 -> Word64
forall a. BE a -> a
unBE (Word64 -> BE Word64
forall a. ByteSwap a => a -> BE a
toBE (Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
t))
  ScrubbedBytes
m :: ScrubbedBytes <-
    IO ScrubbedBytes -> StateT Word64 IO ScrubbedBytes
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (IO ScrubbedBytes -> StateT Word64 IO ScrubbedBytes)
-> IO ScrubbedBytes -> StateT Word64 IO ScrubbedBytes
forall a b. (a -> b) -> a -> b
$ Int -> (Ptr Word64 -> IO ()) -> IO ScrubbedBytes
forall ba p. ByteArray ba => Int -> (Ptr p -> IO ()) -> IO ba
alloc Int
16 ((Ptr Word64 -> IO ()) -> IO ScrubbedBytes)
-> (Ptr Word64 -> IO ()) -> IO ScrubbedBytes
forall a b. (a -> b) -> a -> b
$ \Ptr Word64
p' -> Ptr Word64 -> Word64 -> IO ()
forall a. Storable a => Ptr a -> a -> IO ()
poke Ptr Word64
p' Word64
a_t IO () -> IO () -> IO ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Ptr Word64 -> Int -> Word64 -> IO ()
forall a. Storable a => Ptr a -> Int -> a -> IO ()
pokeElemOff Ptr Word64
p' Int
1 Word64
r_i
  let b :: ScrubbedBytes
b = cipher -> ScrubbedBytes -> ScrubbedBytes
forall cipher ba.
(BlockCipher cipher, ByteArray ba) =>
cipher -> ba -> ba
ecbDecrypt cipher
cipher ScrubbedBytes
m
  Word64
b_hi <- IO Word64 -> StateT Word64 IO Word64
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (IO Word64 -> StateT Word64 IO Word64)
-> IO Word64 -> StateT Word64 IO Word64
forall a b. (a -> b) -> a -> b
$ ScrubbedBytes -> (Ptr Word64 -> IO Word64) -> IO Word64
forall ba p a. ByteArrayAccess ba => ba -> (Ptr p -> IO a) -> IO a
withByteArray ScrubbedBytes
b Ptr Word64 -> IO Word64
forall a. Storable a => Ptr a -> IO a
peek
  Word64
b_lo <- IO Word64 -> StateT Word64 IO Word64
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (IO Word64 -> StateT Word64 IO Word64)
-> IO Word64 -> StateT Word64 IO Word64
forall a b. (a -> b) -> a -> b
$ ScrubbedBytes -> (Ptr Word64 -> IO Word64) -> IO Word64
forall ba p a. ByteArrayAccess ba => ba -> (Ptr p -> IO a) -> IO a
withByteArray ScrubbedBytes
b (Ptr Word64 -> Int -> IO Word64
forall a. Storable a => Ptr a -> Int -> IO a
`peekElemOff` Int
1)
  Word64 -> StateT Word64 IO ()
forall s (m :: * -> *). MonadState s m => s -> m ()
put Word64
b_hi
  IO () -> StateT Word64 IO ()
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (IO () -> StateT Word64 IO ()) -> IO () -> StateT Word64 IO ()
forall a b. (a -> b) -> a -> b
$ Ptr Word64 -> Int -> Word64 -> IO ()
forall a. Storable a => Ptr a -> Int -> a -> IO ()
pokeElemOff Ptr Word64
p Int
i Word64
b_lo

-- | Unwrap a secret.
--
-- Input size must be a multiple of 8 bytes, and at least 24 bytes.
-- Output size is input size minus 8 bytes.
--
-- Returns 'Nothing' if inherent integrity check fails.  Otherwise,
-- the chance that the key data is corrupt is 2 ^ -64.
--
aesKeyUnwrap
  :: (ByteArrayAccess c, ByteArray m, BlockCipher128 cipher)
  => cipher
  -> c
  -> Maybe m
aesKeyUnwrap :: cipher -> c -> Maybe m
aesKeyUnwrap cipher
cipher c
c = IO (Maybe m) -> Maybe m
forall a. IO a -> a
unsafePerformIO (IO (Maybe m) -> Maybe m) -> IO (Maybe m) -> Maybe m
forall a b. (a -> b) -> a -> b
$ do
  let n :: Int
n = c -> Int
forall ba. ByteArrayAccess ba => ba -> Int
BA.length c
c Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
8
  m
m <- c -> (Ptr Any -> IO m) -> IO m
forall ba p a. ByteArrayAccess ba => ba -> (Ptr p -> IO a) -> IO a
withByteArray c
c ((Ptr Any -> IO m) -> IO m) -> (Ptr Any -> IO m) -> IO m
forall a b. (a -> b) -> a -> b
$ \Ptr Any
p' ->
    Int -> (Ptr Word8 -> IO ()) -> IO m
forall ba p. ByteArray ba => Int -> (Ptr p -> IO ()) -> IO ba
alloc Int
n ((Ptr Word8 -> IO ()) -> IO m) -> (Ptr Word8 -> IO ()) -> IO m
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
p ->
      Ptr Word8 -> Ptr Word8 -> Int -> IO ()
memCopy Ptr Word8
p (Ptr Any
p' Ptr Any -> Int -> Ptr Word8
forall a b. Ptr a -> Int -> Ptr b
`plusPtr` Int
8) Int
n
  Word64
a <- c -> (Ptr Word64 -> IO Word64) -> IO Word64
forall ba p a. ByteArrayAccess ba => ba -> (Ptr p -> IO a) -> IO a
withByteArray c
c ((Ptr Word64 -> IO Word64) -> IO Word64)
-> (Ptr Word64 -> IO Word64) -> IO Word64
forall a b. (a -> b) -> a -> b
$ \Ptr Word64
p' -> Ptr Word64 -> IO Word64
forall a. Storable a => Ptr a -> IO a
peek Ptr Word64
p'
  Word64
a' <- m -> (Ptr Word64 -> IO Word64) -> IO Word64
forall ba p a. ByteArrayAccess ba => ba -> (Ptr p -> IO a) -> IO a
withByteArray m
m ((Ptr Word64 -> IO Word64) -> IO Word64)
-> (Ptr Word64 -> IO Word64) -> IO Word64
forall a b. (a -> b) -> a -> b
$ \Ptr Word64
p -> do
    let n' :: Int
n' = Int
n Int -> Int -> Int
forall a. Integral a => a -> a -> a
`div` Int
8
    let tMax :: Int
tMax = Int
n' Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
6
    let coords :: [(Int, Int)]
coords = [Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
tMax,Int
tMaxInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1..Int
1] ([Int] -> [Int]
forall a. [a] -> [a]
cycle [Int
n'Int -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1,Int
n'Int -> Int -> Int
forall a. Num a => a -> a -> a
-Int
2..Int
0])
    StateT Word64 IO () -> Word64 -> IO Word64
forall (m :: * -> *) s a. Monad m => StateT s m a -> s -> m s
execStateT (((Int, Int) -> StateT Word64 IO ())
-> [(Int, Int)] -> StateT Word64 IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (cipher -> Ptr Word64 -> (Int, Int) -> StateT Word64 IO ()
forall cipher.
BlockCipher128 cipher =>
cipher -> Ptr Word64 -> (Int, Int) -> StateT Word64 IO ()
aesKeyUnwrapStep cipher
cipher Ptr Word64
p) [(Int, Int)]
coords) Word64
a
  Maybe m -> IO (Maybe m)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe m -> IO (Maybe m)) -> Maybe m -> IO (Maybe m)
forall a b. (a -> b) -> a -> b
$ if Word64
a' Word64 -> Word64 -> Bool
forall a. Eq a => a -> a -> Bool
== Word64
iv then m -> Maybe m
forall a. a -> Maybe a
Just m
m else Maybe m
forall a. Maybe a
Nothing