xanoutas/solidity-security-findings huggingface dataset:
check that the default `consoleFallbackHandler` and `SafeModerator`  have not been changed after executing every transaction by the executors and the operator will always revert and freeze all the functionality of the sub account if the owners of console account have changed this addresses 
Audit: 2023-10-brahma-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2023-10-brahma/blob/dd0b41031b199a0aa214e50758943712f9f574a0/contracts/src/core/TransactionValidator.sol#L181-L198


# Vulnerability details

## Impact
this vulnerability will lead to freeze all the functionality of the sub account and revert on all the transaction . 
## Proof of Concept
the main console is allowed to change the guard of the sub accounts and the fallback handler of the sub accounts , but if the main console change those values this will prevent the execution of the transaction on the sub accounts because of those checks :
https://github.com/code-423n4/2023-10-brahma/blob/dd0b41031b199a0aa214e50758943712f9f574a0/contracts/src/core/TransactionValidator.sol#L181-L198
```solidity 
    function _checkSubAccountSecurityConfig(address _subAccount) internal view {
        address guard = SafeHelper._getGuard(_subAccount);
        address fallbackHandler = SafeHelper._getFallbackHandler(_subAccount);


        // Ensure guard has not been disabled
        if (guard != AddressProviderService._getAuthorizedAddress(_SAFE_MODERATOR_HASH)) revert InvalidGuard();


        // Ensure fallback handler has not been altered
        if (fallbackHandler != AddressProviderService._getAuthorizedAddress(_CONSOLE_FALLBACK_HANDLER_HASH)) {
            revert InvalidFallbackHandler();
        }


        address ownerConsole =
            WalletRegistry(AddressProviderService._getRegistry(_WALLET_REGISTRY_HASH)).subAccountToWallet(_subAccount);


        // Ensure owner console as a module has not been disabled
        if (!IGnosisSafe(_subAccount).isModuleEnabled(ownerConsole)) revert InvalidModule();
    }
```

those checks should be performed to make sure that the transaction of the executors or the operators did not change any of the configuration values , but if the main console , who is allowed to change those values , modify any of them the execution of the transaction will always revert . 
so if the main console wants to modify the `fallbackHandler` and keep automating the transaction in the subAccount this will always fail . 

so this vulnerability will prevent the main console from keep automating the transaction after modifying the fallback handler , which should not be happened .  

## Tools Used
manual review 
## Recommended Mitigation Steps
the checks should make sure that the configuration values did not get changed after the execution of the transaction from the previous values not the default values 
```solidity 
    // Ensure fallback handler has not been altered
        if (fallbackHandler != beforeExecutionFallbackHandler )  {
            revert InvalidFallbackHandler();
        }
```


## Assessed type

Context
Resetting a sub-account's guard manually from the Main Console can potentially lead to a permanent denial of service (DoS) for that sub-account.
Audit: 2023-10-brahma-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2023-10-brahma/blob/dd0b41031b199a0aa214e50758943712f9f574a0/contracts/src/core/ExecutorPlugin.sol#L73-L74
https://github.com/code-423n4/2023-10-brahma/blob/dd0b41031b199a0aa214e50758943712f9f574a0/contracts/src/core/TransactionValidator.sol#L133
https://github.com/code-423n4/2023-10-brahma/blob/dd0b41031b199a0aa214e50758943712f9f574a0/contracts/src/core/SafeModerator.sol#L71-L72
https://github.com/code-423n4/2023-10-brahma/blob/dd0b41031b199a0aa214e50758943712f9f574a0/contracts/src/core/TransactionValidator.sol#L106
https://github.com/code-423n4/2023-10-brahma/blob/dd0b41031b199a0aa214e50758943712f9f574a0/contracts/src/core/TransactionValidator.sol#L186-L197


# Vulnerability details

## Impact
If the `Main Console` resets the `guard`, resets the `fallback handler`, or disables itself as a `module` of a `sub-account`, the `executors` will permanently cease executing any transactions on that `sub-account`.

And also if the `Main Console` resets the `fallback handler` or disables itself as a `module` of a `sub-account`, the `operators` will not be able to execute any transactions on the `sub-account`.

## Proof of Concept
I discovered the following three sentences in the `README` file.
```
Main Console Account should always stay as a module enabled on any subaccount it owns (unless manually changed by Main Console)
Subaccount should always have SafeModerator enabled as guard on it (unless manually changed by Main Console)
Subaccount should always have ConsoleFallbackHandler enabled as the fallback handler on it (unless manually changed by Main Console)
```
I believe this indicates that the `main console` can reset the `guard`, reset the `fallback handler`, or disable itself as a `module` of a `sub-account` through `module transactions`.

Let's imagine that the `main console` reset the guard of the `sub-account`.
And then, a particular `executor` initiates a valid transaction on that `sub-account` and calls the `executeTransaction` function of the `ExecutorPlugin`.
Every `transaction` conducted through the `ExecutorPlugin` should require a security configuration check after the transaction is completed.
```
function validatePostExecutorTransaction(address, /*msgSender */ address subAccount) external view {
   _checkSubAccountSecurityConfig(subAccount);
}
```
And all transactions will be reverted because this `sub-account` lacks a `guard`.
```
function _checkSubAccountSecurityConfig(address _subAccount) internal view {
    address guard = SafeHelper._getGuard(_subAccount);
    address fallbackHandler = SafeHelper._getFallbackHandler(_subAccount);

    // Ensure guard has not been disabled
    if (guard != AddressProviderService._getAuthorizedAddress(_SAFE_MODERATOR_HASH)) revert InvalidGuard();
}
```

You can add the following test to the `test/branch-trees/SafeModerator/SafeModerator.misc.t.sol` to verify that the main console can reset the guard of a sub-account.
```
function testResetSafeModeratorFro
Malicious Module can change the policy commit of a Gnosis Safe console Account
Audit: 2023-10-brahma-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2023-10-brahma/blob/dd0b41031b199a0aa214e50758943712f9f574a0/contracts/src/core/registries/PolicyRegistry.sol#L35-L60


# Vulnerability details

## Impact
The overall design of the Gnosis safe allows for the addition of a Module, modules are smart contracts that extend the ability of the Gnosis safe, which means that a module can be setup in such a way that it can perform actions that is meant to improve the functionality and performance of a gnosis safe, they can also be many of these modules, and some of these modules are not written by the safe owners, which mean an unaudited module can be integrated into the safe, the module does not have to be malicious at inception, but can become malicious if being taken over by a malicious actor. These modules having the ability to make transactions on behalf of the safe present a risk although mitigated by the validators ability to check if the transaction being made, is following the predefined owners policy of the account, some transaction calls, do not have that check in place, like the ```updatePolicy``` function in the ```PolicyRegistry``` contract. This will allow the module to change the policy from a defined rule to any rules. making a huge impact on the subaccounts under the console account as ```operators``` and ```Executors``` will have free reign to perform unauthorized transactions by the owners.

This can cause a DOS in which the owners are not aware of the transactions that are occurring on their sub accounts, since they expected it to be an automation process, where DCA and TWAP actions are supposed to be happening. Before the owners assemble to disable the module, they need a minimum threshold as that would be a safe transaction, this can further increase the time of the DOS.
This goes against the need to create sub accounts to divide the risk assets are exposed to, so has to protect the users asset in the main Console Account safe

## Proof of Concept
For the Whole Process to work a new safe or an existing safe has to add a new module to the module manager, which they can do by calling the ```enableModule``` function, which adds the new module to the whitelist in the Gnosis Safe ```ModuleManager``` contract
```solidity
function enableModule(address module) public authorized {
        // Module address cannot be null or sentinel.
        require(module != address(0) && module != SENTINEL_MODULES, "GS101");
        // Module cannot be added twice.
        require(modules[module] == address(0), "GS102");
        modules[module] = modules[SENTINEL_MODULES];
        modules[SENTINEL_MODULES] = module;
        emit EnabledModule(module);
    }
```
After a module is added they can actually now execute safe transactions without any further confirmations, which means they have the ability to make transaction has defined in them. maybe for example like reinvesting rewards in the safe and other actions. This ability is defined in the natspec for the `
Protocol's invariants can be broken
Audit: 2023-10-brahma-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2023-10-brahma/blob/a6424230052fc47c4215200c19a8eef9b07dfccc/contracts/src/core/SafeDeployer.sol#L82-L104
https://github.com/code-423n4/2023-10-brahma/blob/a6424230052fc47c4215200c19a8eef9b07dfccc/contracts/src/core/SafeDeployer.sol#L168-L190


# Vulnerability details

## Impact
Due to insufficient input validation to the inputs of the external function "deploySubAccount()" in the SafeDeployer.sol contract,A malcious subAccount wallet can be imported,registered and then take control over other subAccounts. This can cause many damages depending on the purposes of the kidnaped subaccount and Obviousely violates the intended protocol invarients.
 
## Proof of Concept

The protocol  Invarients states that "Main Console Account should always stay as a module enabled on any subaccount it owns (unless manually changed by Main Console)" This can be broken as follows:
In the SafeDeployer.sol contract deploySubAccount() function which deploys a new sub-account with policy commit and registers it, the function first checks that there is a policy commit registered for the subAccount then it checks if msg.sender is a registered wallet and THAT'S IT,no more validations made and a new subAccount can be directly deployed just after setting-up using this line:

_subAcc = _createSafe(_owners, _setupSubAccount(_owners, _threshold, msg.sender), _salt);

which, in turn, invokes the function _setupSubAccount() to do the setting-up for the new subaccount providing it with the shown parameters, let's see what parameters this function is expecting:

function _setupSubAccount(address[] memory _owners, uint256 _threshold, address _consoleAccount)
        private view returns (bytes memory)

So, the third param is expected to be the address of the console account, which should be enabled as a module for this subAccount as we can see below:
 
address safeEnabler = AddressProviderService._getAuthorizedAddress(_SAFE_ENABLER_HASH);
        Types.Executable[] memory txns = new Types.Executable[](2);
        txns[0] = Types.Executable({
            callType: Types.CallType.DELEGATECALL,
            target: safeEnabler,
            value: 0,
            data: abi.encodeCall(IGnosisSafe.enableModule, (_consoleAccount)) // here the Third param will be 
                                                                                 enabled as a module that was 
                                                                                 supposed to be consoleAcoount
        });

As such, the subAccount enabled module can be any registered wallet with no restriction to be THE main consoleAccount.

## Tools Used
Manual review

## Recommended Mitigation Steps
Ensure that only ConsoleAccount can deploy subAccount. May be by making two different registries one for consolAccounts and the other one for subAccounts. 




## Assessed type

Invalid Validation
attacker can perform malicious transactions in the safe because reentrancy is not implemented in the execTransaction() and checkAfterExecution() function 
Audit: 2023-10-brahma-findings
Severity: HIGH

# Lines of code

https://github.com/MolochVentures/moloch/blob/master/v1_contracts/gnosis-safe/GnosisSafe.sol#L78-L114
https://github.com/code-423n4/2023-10-brahma/blob/main/contracts/src/core/SafeModerator.sol#L70-L73


# Vulnerability details

## Impact
Due to reentrancy, it's possible to set a guard or threshold during the `execTransaction()` and execute another malicious transaction which resets the guard and threshold

## Proof of Concept
to prevent reentrancy during the safe's `execTransaction()` function code didn't uses any reentrancy guard. that's why the attacker can perform reentrancy during the `execTransaction()` call.

an attacker can perform these actions:

Transaction1 which has a valid number of signers and sets the value of the guard to 0x0. and call `safe.execTransaction(Transaction2)`.
Transaction2 which reset the value of the guard to the SafeModerator address.
now by calling `Tsafe.execTransaction(Transaction1)`, the code would first call checkTransaction() and would see the number of the signers is correct, and then the code in safe would execute the Transaction1 which would set the guard to 0x0 and execute the Transaction2 in safe.
because the guard is 0x0, the code would execute the Transaction2 and then during that code would reset the value of the guard to the SafeModerator address.
now checkAfterExecution() would get executed and would see that the guard value is correct and Tx will be completed


## Tools Used
manual code review 
vscode 

## Recommended Mitigation Steps
It is recommended to use a reentrancy guard on execTransaction() 










## Assessed type

Reentrancy
`checkAfterExecution()` function has a design flaw
Audit: 2023-10-brahma-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2023-10-brahma/blob/main/contracts/src/core/SafeModeratorOverridable.sol#L76


# Vulnerability details

## Impact

`checkAfterExecution()` function has a design flaw.
It may cause some danger problem, such as ,signers can change the threshold of the vault, giving themselves increased control over future transactions and breaking an important trust assumption of the protocol.


## Proof of Concept

According to the introduction, brahma console account is a standard `GnosisSafe`, When account calls the `execTransaction()`,it will call the `GnosisSafe.execTransaction()`.

As we can see , the standard GnosisSafe has many sensitive function, such as `swapOwner()`, `removeOwner()`.
```solidity
function removeOwner(
        address prevOwner,
        address owner,
        uint256 _threshold
    ) public authorized {
        // Only allow to remove an owner, if threshold can still be reached.
        require(ownerCount - 1 >= _threshold, "GS201");
        // Validate owner address and check that it corresponds to owner index.
        require(owner != address(0) && owner != SENTINEL_OWNERS, "GS203");
        require(owners[prevOwner] == owner, "GS205");
        owners[prevOwner] = owners[owner];
        owners[owner] = address(0);
        ownerCount--;
        emit RemovedOwner(owner);
        // Change threshold if threshold was changed.
        if (threshold != _threshold) changeThreshold(_threshold);
    }

    /// @dev Allows to swap/replace an owner from the Safe with another address.
    ///      This can only be done via a Safe transaction.
    /// @notice Replaces the owner `oldOwner` in the Safe with `newOwner`.
    /// @param prevOwner Owner that pointed to the owner to be replaced in the linked list
    /// @param oldOwner Owner address to be replaced.
    /// @param newOwner New owner address.
    function swapOwner(
        address prevOwner,
        address oldOwner,
        address newOwner
    ) public authorized {
        // Owner address cannot be null, the sentinel or the Safe itself.
        require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), "GS203");
        // No duplicate owners allowed.
        require(owners[newOwner] == address(0), "GS204");
        // Validate oldOwner address and check that it corresponds to owner index.
        require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "GS203");
        require(owners[prevOwner] == oldOwner, "GS205");
        owners[newOwner] = owners[oldOwner];
        owners[prevOwner] = newOwner;
        owners[oldOwner] = address(0);
        emit RemovedOwner(oldOwner);
        emit AddedOwner(newOwner);
    }

    /// @dev Allows to update the number of required confirmations by Safe owners.
    ///      This can only be done via a Safe transaction.
    /// @notice Changes the threshold of the Safe to `_threshold`.
    /// @param _threshold New threshold.
    function changeThreshold(uint256 _thre
Signed data may be usable cross-chain
Audit: 2023-10-brahma-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2023-10-brahma/blob/a6424230052fc47c4215200c19a8eef9b07dfccc/contracts/src/libraries/TypeHashHelper.sol#L64-L77
https://github.com/code-423n4/2023-10-brahma/blob/a6424230052fc47c4215200c19a8eef9b07dfccc/contracts/src/libraries/TypeHashHelper.sol#L23-L31


# Vulnerability details

## Impact
The function validatePreTransactionOverridable(), which Validates a txn on guard before execution, for Brahma console accounts.takes one parameter "txParams" which is of type SafeTransactionParams Struct, if we look at that struct members :
struct SafeTransactionParams {
        Enum.Operation operation;
        address from;
        address to;
        address payable refundReceiver;
        address gasToken;
        address msgSender;
        uint256 value;
        uint256 safeTxGas;
        uint256 baseGas;
        uint256 gasPrice;
        bytes data;
        bytes signatures;
    }

there is no chainId identifier, this is also the case with the following functions:
-function validatePreTransaction(SafeTransactionParams memory txParams) // which Validates a txn on guard before execution, for subAccounts.
-function validatePreExecutorTransaction(
        address, /*msgSender */
        address from,
        bytes32 transactionStructHash,
        bytes memory signatures
    ) // which Validates a module txn before execution.

And as the Brahma Console is multi-chain ( Target Chains:Ethereum,Optimism,Base,Avalanche, C Chan,Polygon Mainnet,Arbitrum,Polygon zkEVM,Binance Smart Chain,Fantom), This issue can lead to many problems such as:

1. The signature can be replayed on other EVM-compatible chains on which Brahma Console protocol is deployed. 
2. Users can transfer their assets - by mistake- to another chain where they may be lost forever.  


## Proof of Concept
 In "ethereum.stackexchange.com" there are many questions asking about a way to return their assets that they mistakenly sent to the wrong Gnosis Safe on another chain,
here is an example: https://ethereum.stackexchange.com/questions/117781/how-to-recover-funds-mistakenly-sent-to-polygon-instead-of-eth-gnosis-safe-1-1?rq=1
this proves that it is already an issue that needs to be handled in Gnosis Safe and as Brahma Console stated in the docs " The SafeDeployer contract facilitates the deployment of Gnosis Safe accounts and configuring them as console accounts" Then most likely there will be the same issue unless it is mitigated beforehand.

of course, the mentioned issue is about innocent mistake, the same vulnerability can be used by a malicious attacker to steal the protocol users.

## Tools Used
Manual review
## Recommended Mitigation Steps
- Include the "chainId" in the signature or in the Transaction Struct to avoid this issue.


## Assessed type

Other
A new executor cannot be added because of the wrong restriction
Audit: 2023-10-brahma-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2023-10-brahma/blob/dd0b41031b199a0aa214e50758943712f9f574a0/contracts/src/core/registries/ExecutorRegistry.sol#L42


# Vulnerability details

## Impact
A new executor cannot be added because of the wrong restriction

## Proof of Concept
`
   if (!subAccountToExecutors[_subAccount].add(_executor)) revert AlreadyExists();
`

https://github.com/code-423n4/2023-10-brahma/blob/dd0b41031b199a0aa214e50758943712f9f574a0/contracts/src/core/registries/ExecutorRegistry.sol#L42

The if statement checks if _executor to be added to the subAccountToExecutors mapping is not in the mapping. And if it's not in the mapping, it should revert with AlreadyExists(); This is not the intended 
logic.

What is intended is to add a new `_executor` not in the subAccountToExecutors mapping.

## Tools Used
Manual review

## Recommended Mitigation Steps
I suggest something like this:

`
if (subAccountToExecutors[_subAccount].add(_executor)) {
  emit RegisterExecutor(_subAccount, msg.sender, _executor); 
} else {
  revert AlreadyExists(); 
}

`


## Assessed type

Access Control