-- 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 (join)
import Control.Monad.State (StateT, execStateT, get, lift, put)
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 :: forall cipher.
BlockCipher128 cipher =>
cipher -> Ptr Word64 -> (Int, Int) -> StateT Word64 IO ()
aesKeyWrapStep cipher
cipher Ptr Word64
p (Int
t, Int
i) = do
  a <- StateT Word64 IO Word64
forall s (m :: * -> *). MonadState s m => m s
get
  r_i <- lift $ peekElemOff p i
  m :: ScrubbedBytes <-
    lift $ alloc 16 $ \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 a b. IO a -> IO b -> IO b
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 = cipher -> ScrubbedBytes -> ScrubbedBytes
forall cipher ba.
(BlockCipher cipher, ByteArray ba) =>
cipher -> ba -> ba
forall ba. ByteArray ba => cipher -> ba -> ba
ecbEncrypt cipher
cipher ScrubbedBytes
m
  b_hi <- lift $ withByteArray b peek
  b_lo <- lift $ withByteArray b (`peekElemOff` 1)
  put (b_hi `xor` unBE (toBE (fromIntegral t)))
  lift $ pokeElemOff p i 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 :: forall m c cipher.
(ByteArrayAccess m, ByteArray c, BlockCipher128 cipher) =>
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 <- m -> (Ptr Word8 -> IO c) -> IO c
forall ba p a. ByteArrayAccess ba => ba -> (Ptr p -> IO a) -> IO a
forall p a. m -> (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 (ZonkAny 0) -> 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 (ZonkAny 0) -> IO ()) -> IO c)
-> (Ptr (ZonkAny 0) -> IO ()) -> IO c
forall a b. (a -> b) -> a -> b
$ \Ptr (ZonkAny 0)
p' ->
      Ptr Word8 -> Ptr Word8 -> Int -> IO ()
memCopy (Ptr (ZonkAny 0)
p' Ptr (ZonkAny 0) -> Int -> Ptr Word8
forall a b. Ptr a -> Int -> Ptr b
`plusPtr` Int
8) Ptr Word8
p Int
n
  withByteArray c $ \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]))
    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
    poke p a
  return c

aesKeyUnwrapStep
  :: BlockCipher128 cipher
  => cipher
  -> Ptr Word64   -- ^ register
  -> (Int, Int)   -- ^ step (t) and offset (i)
  -> StateT Word64 IO ()
aesKeyUnwrapStep :: forall cipher.
BlockCipher128 cipher =>
cipher -> Ptr Word64 -> (Int, Int) -> StateT Word64 IO ()
aesKeyUnwrapStep cipher
cipher Ptr Word64
p (Int
t, Int
i) = do
  a <- StateT Word64 IO Word64
forall s (m :: * -> *). MonadState s m => m s
get
  r_i <- lift $ peekElemOff p i
  let 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))
  m :: ScrubbedBytes <-
    lift $ alloc 16 $ \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 a b. IO a -> IO b -> IO b
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 = cipher -> ScrubbedBytes -> ScrubbedBytes
forall cipher ba.
(BlockCipher cipher, ByteArray ba) =>
cipher -> ba -> ba
forall ba. ByteArray ba => cipher -> ba -> ba
ecbDecrypt cipher
cipher ScrubbedBytes
m
  b_hi <- lift $ withByteArray b peek
  b_lo <- lift $ withByteArray b (`peekElemOff` 1)
  put b_hi
  lift $ pokeElemOff p i 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 :: forall c m cipher.
(ByteArrayAccess c, ByteArray m, BlockCipher128 cipher) =>
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 <- c -> (Ptr (ZonkAny 1) -> IO m) -> IO m
forall ba p a. ByteArrayAccess ba => ba -> (Ptr p -> IO a) -> IO a
forall p a. c -> (Ptr p -> IO a) -> IO a
withByteArray c
c ((Ptr (ZonkAny 1) -> IO m) -> IO m)
-> (Ptr (ZonkAny 1) -> IO m) -> IO m
forall a b. (a -> b) -> a -> b
$ \Ptr (ZonkAny 1)
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 (ZonkAny 1)
p' Ptr (ZonkAny 1) -> Int -> Ptr Word8
forall a b. Ptr a -> Int -> Ptr b
`plusPtr` Int
8) Int
n
  a <- withByteArray c $ \Ptr Word64
p' -> Ptr Word64 -> IO Word64
forall a. Storable a => Ptr a -> IO a
peek Ptr Word64
p'
  a' <- withByteArray m $ \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. HasCallStack => [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
  return $ if a' == iv then Just m else Nothing