Why is global state not considered as an example of dependency injection?

According to Why is Global State so Evil?, as I understand, global state is bad and I should use dependency injection instead. That means, for example, a mobile app that use bundles of app level data as follow:

public class UserData{
    private static UserData userData=new UserData();
    public UserData getInstance(){
        return userData;
    }

    private String sessionId;
    private String surname;
    ... (other fields with setter and getter)
}

public class SomePage{
    private UserData userData;
    public MainPage(){
        this.userData=UserData.getInstance();
    }
    public void onLogoutButtonPressed(){
      Http.post(Constant.LOGOUT_URL,"?sessionId="+userData.sessionId);
    }
}

is an bad example and need to be fixed to use dependency injection.

However, as far as I know and according to https://softwareengineering.stackexchange.com/a/319609, the “spirit” of dependency injection is , an object receives target objects externally instead of that object creates target objects by itself, eg:

non dependency injection version:

public class SomePage{
    public UserData userData;
    public SomePage(){
        this.userData=new UserData();
    }
}

dependency injection version:

public class SomePage{
    public UserData userData;
    public SomePage(UserData userData){
        this.userData=userData;
    }
}

Then, I think my “global state” version:

public class SomePage{
    private UserData userData;
    public MainPage(){
        this.userData=UserData.getInstance();
    }
}

also doesn’t create UserData at all. And I think the “spirt” of using global state and injecting object from constructor is quite similar : getting required objects externally, just their ways to get that external objects are different. So my question is, why is using global state doesn’t consider as dependency injection even if it gets object externally?

javascript – Null byte injection using JSON

I’m trying to make a chatroom for my university, It takes username in JSON, and then stores it in an array, then takes it to DB for keeping logs, but the thing is, that array also has a “status” key, whose value is set to guest my default, but is set to ADMIN if I log in or any member from my team logs in. I know that the idea of storing “status” with username is bad but I just started working on the project. I want to confirm that is it possible to inject NULL byte using username field via JSON and add another key with same name “status” to gain admin privileges??

Dependency Injection of custom classes into custom class (Event Subscriber)

I wrote an Event Subscriber class for a custom module to listen for events. I also wrote a custom class that the event listener needs to use when the events happen. I tried to adding it with the namespace I have for the repository class: ‘use MyModuleCustomAPIServicesRepository;’ at the top and add it using the new APIServicesRepository() but Drupal/Symfony freaked since it wants me to pass it to the constructor.

I can add it to the constructor but I have no idea how to pass it into the constructor as an argument in the mymodules.services.yml

I see arguments: (‘@commerce_cart.cart_manager’) but I can’t figure out where I need to create the @path for my main repository class.

my custom module structure looks like:

  • modules
    • custom
      • mymodule
        • mymodule.info.yml
        • mymodule.services.yml
        • MyModule
          • Custom
            • APIServicesRepository.php
        • src
          • EventSubscriber
          • CartEventsSubscriber.php

My namespace for APIServicesRepository is namespace: MyModuleCustom

Any advice or pointing to a good Drupal resource to learn how to create my class into a services that can be injected in would be greatly appreciated. Thanks!

Why does Integer Based SQL Injection still require single quote in the parameter (‘)?

This is the source code of Damn Vulnerable Web Application (DVWA).

nl /var/www/dvwa/vulnerabilities/sqli/source/low.php

 7      $id = $_GET('id');
 8  
 9      $getid = "SELECT first_name, last_name FROM users WHERE user_id = '$id'";

mysql

mysql> DESC users;
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| user_id    | int(6)      | NO   | PRI | 0       |       | 
| first_name | varchar(15) | YES  |     | NULL    |       | 
| last_name  | varchar(15) | YES  |     | NULL    |       | 
| user       | varchar(15) | YES  |     | NULL    |       | 
| password   | varchar(32) | YES  |     | NULL    |       | 
| avatar     | varchar(70) | YES  |     | NULL    |       | 
+------------+-------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

mysql> 

The user_id or id in users table is actually an integer type. So, this is an Integer based SQL Injection.

Based on Joe McCray presentation in Def Con on page 23, ' not required for Integer based injection.

However, when I tested it on DVWA without ', I did not get Unknown column '100' in 'order clause' message.

http://127.0.0.1/dvwa/vulnerabilities/sqli/?id=1 ORDER BY 100-- &Submit=Submit#

Output (No error)

ID: 1 ORDER BY 100-- 
First name: admin
Surname: admin

Then, I decided to test it with ' and it worked.

http://127.0.0.1/dvwa/vulnerabilities/sqli/?id=1' ORDER BY 100-- &Submit=Submit#

Error Message

Unknown column '100' in 'order clause'

Didn’t ' not required in this example (integer based injection)?

SQL Injection: How to fix broken SQL query with comment?

This is purposedly vulnerable test site developed by Acunetik.

http://testphp.vulnweb.com/listproducts.php?cat=1

Let’s test it.

http://testphp.vulnweb.com/listproducts.php?cat=1'

Error

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''' at line 1 Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /hj/var/www/listproducts.php on line 74

Looking at the error message, this site is clearly vulnerable to SQL Injection.

I imagine the SQL query looks like this.

SELECT ? FROM ? WHERE cat LIKE '1';

And this query generates SQL error because of additional ' character.

SELECT ? FROM ? WHERE cat LIKE '1'';

Normally by commenting out the syntax with -- comment will make this error go away.

SELECT ? FROM ? WHERE cat LIKE '1'--';

Similar query executed from the site

http://testphp.vulnweb.com/listproducts.php?cat=1'--

But this trick is not working for this site. What was I missing here?

web application – Having problems with SQL injection with mysqli extension PHP

I am new to SQL injections, and people on Reddit asked me do the portswigger labs. Which I did up till before 2nd order ones. So I am pretty comfortable with usual SQL injections.

Now I have myself made a PHP website using mysqli extensions instead of mysql. So for example, a basic Query execution looks like:

//mysqli// $result = mysqli_query($conn, $qry); instead of $result =
mysql_query($qry);

========================================================================

So I asked others and found out that without proper sanitization or separate query builders, mysqli extension is as vulnerable as mysql extension. So, the app I made is too basic. It’s just querying the DB and spitting out results. It’s that simple. No sanitization is done.

But executing basic payloads like ‘+or+1=1–+ or anything basic, gives me the error:

mysqli_error() expects exactly 1 parameter, 0 given

So I tried a lot and can’t get past this error for anything I try. I simply can’t execute injections with mysqli extension. Any help is highly appreciated.

Thank You.

How to exploit LDAP injection?

BurpSuite marked a website I am testing with having a potential LDAP injection vulnerability. It seems that when I put an asterisk in a parameter ex. getStuff?id=* I get a 500 error and Java error output. When I set it to something normal like 123 I get a 200 response (the page is just blank however). I’m not sure how I can further exploit this, maybe someone knows?

MVVM-C Swift with Dependency injection

I want to create a MVVM-C project, but also adequately test it. Naturally I want to create such a project that can access a Network Service.

I’ve written the whole thing (and have tests in this GitHub Repo https://github.com/stevencurtis/MVVM-CDependency)

Any comments or thoughts on this approach?

DependencyFactory:

protocol Factory {
    var networkManager: HTTPManagerProtocol { get }
    func makeInitialViewModel(coordinator: Coordinator) -> InitialViewModel
    func makeInitialView(viewModel: InitialViewModel) -> InitialView
    func makeDetailView(viewModel: DetailViewModel) -> DetailView
    func makeDetailViewModel(coordinator: Coordinator) -> DetailViewModel
}

// replace the DependencyContainer for tests
class DependencyFactory: Factory {
    var networkManager: HTTPManagerProtocol = HTTPManager()

    // should not return an optional at the end of this project
    func makeInitialCoordinator() -> ProjectCoordinator {
        let coordinator = ProjectCoordinator(factory: self)
        return coordinator
    }

    func makeInitialView(viewModel: InitialViewModel) -> InitialView {
        let view = InitialView()
        return view
    }

    func makeInitialViewModel(coordinator: Coordinator) -> InitialViewModel {
        let viewModel = InitialViewModel(coordinator: coordinator, networkManager: networkManager)
        return viewModel
    }

    func makeDetailView(viewModel: DetailViewModel) -> DetailView {
        let view = DetailView()
        return view
    }

    func makeDetailViewModel(coordinator: Coordinator) -> DetailViewModel {
        let viewModel = DetailViewModel(coordinator: coordinator, networkManager: networkManager)
        return viewModel
    }
}

A basic HTTPManager (that doesn’t really touch the network, but you get the point!)

protocol HTTPManagerProtocol {
    func get(url: URL, completionBlock: @escaping (Result<Data, Error>) -> Void)
}

class HTTPManager: HTTPManagerProtocol {
    public func get(url: URL, completionBlock: @escaping (Result<Data, Error>) -> Void) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            let data = Data("The Data from HTTPManager".utf8)
            completionBlock(.success(data))
        }
    }
}

Project Coordinator

protocol Coordinator: class {
    func start(_ navigationController: UINavigationController)
    func moveToDetail()
}

class ProjectCoordinator: Coordinator {
    var childCoordinators = (Coordinator)()
    var navigationController: UINavigationController?

    private var factory: Factory

    init(factory: Factory) {
        self.factory = factory
    }

    func start(_ navigationController: UINavigationController) {
        let vc = InitialViewController(factory: factory, coordinator: self)
        self.navigationController = navigationController
        navigationController.pushViewController(vc, animated: true)
    }

    func moveToDetail() {
        let vc = DetailViewController(factory: factory, coordinator: self)
        navigationController?.pushViewController(vc, animated: true)
    }
}

InitialModel

struct InitialModel : Codable {
    let dataString : String
}

InitialView

final class InitialView: UIView {

    let traverseButton = UIButton(type: .custom)
    let networkButton = UIButton(type: .custom)
    let networkLabel = UILabel()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setup() {
        self.backgroundColor = .red
        traverseButton.frame = CGRect(x: 0, y: 0, width: 200, height: 100)
        traverseButton.setTitle("Go to Detail", for: .normal)
        traverseButton.setTitleColor(.black, for: .normal)
        traverseButton.isUserInteractionEnabled = true

        self.addSubview(traverseButton)
        traverseButton.translatesAutoresizingMaskIntoConstraints = false
        traverseButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        traverseButton.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true

        networkButton.frame = CGRect(x: 0, y: 0, width: 200, height: 100)
        networkButton.setTitle("Make Network Call", for: .normal)
        networkButton.setTitleColor(.black, for: .normal)
        networkButton.isUserInteractionEnabled = true

        self.addSubview(networkButton)
        networkButton.translatesAutoresizingMaskIntoConstraints = false
        networkButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        networkButton.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 100).isActive = true

        networkLabel.text = "No network calls made"
        networkLabel.backgroundColor = .purple
        self.addSubview(networkLabel)

        networkLabel.translatesAutoresizingMaskIntoConstraints = false
        networkLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        networkLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 200).isActive = true
        networkLabel.widthAnchor.constraint(equalToConstant: 300).isActive = true
        networkLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
    }

    func setNetworkLabel(text: String){
        networkLabel.text = text
    }

}

InitialViewController

class InitialViewController: UIViewController {
    private var coordinator: Coordinator?
    private var factory: Factory?

    var intialView: InitialView?

    lazy var viewModel: InitialViewModel? = {
        return factory?.makeInitialViewModel(coordinator: coordinator!)
    }()

    init(factory: Factory, coordinator: Coordinator) {
        self.factory = factory
        self.coordinator = coordinator
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func loadView() {
        if let initialView = factory?.makeInitialView(viewModel: viewModel!) {
            initialView.traverseButton.addTarget(self, action: #selector(traverseButton(_:)), for: .touchDown)
            initialView.networkButton.addTarget(self, action: #selector(networkButton), for: .touchDown)
            self.intialView = initialView
            self.view = initialView
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func traverseButton(_ sender: UIButton) {
        coordinator?.moveToDetail()
    }

    @IBAction func networkButton(_ sender: UIButton) {
        viewModel?.fetchData(completion: { data in
            switch data {
            case .failure: fatalError()
            case .success(let data):
                if let data = data.first {
                    self.intialView?.setNetworkLabel(text: data.dataString)
                }
            }
        })
    }

}

InitialViewModel

class InitialViewModel {
    private var networkManager: HTTPManagerProtocol?
    init(coordinator: Coordinator?, networkManager: HTTPManagerProtocol) {
        self.networkManager = networkManager
    }

    func fetchData(completion: @escaping (Result<(InitialModel), Error>) -> Void) {
        networkManager?.get(url: URL(string: "NOURL")!, completionBlock: { result in
            DispatchQueue.main.async {
                switch result {
                case .failure:
                    completion(.failure(NSError()))
                case .success(let data):
                    if let str = String(data: data, encoding: .utf8) {
                        let model = InitialModel(dataString: str)
                        completion(.success((model)))
                    }
                }
            }
        })
    }
}

DetailViewController

class DetailViewController: UIViewController {
    weak var coordinator: Coordinator?
    private var factory: Factory?

    var detailView: DetailView?

    lazy var viewModel: DetailViewModel? = {
        return factory?.makeDetailViewModel(coordinator: coordinator!)
    }()

    init(factory: Factory, coordinator: Coordinator) {
        self.factory = factory
        self.coordinator = coordinator
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func loadView() {
        if let detailView = factory?.makeDetailView(viewModel: viewModel!) {
            self.detailView = detailView
            self.view = detailView
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

DetailViewModel

class DetailViewModel {
    private var networkManager: HTTPManagerProtocol?
    init(coordinator: Coordinator?, networkManager: HTTPManagerProtocol) {
        self.networkManager = networkManager
    }
}

DetailView

final class DetailView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setup() {
        self.backgroundColor = .blue
    }
}

The whole thing is on GitHub – all suggestions welcome! https://github.com/stevencurtis/MVVM-CDependency

Dependency Injection (di.xml) – (virtualType vs type) Magento 2 xsi:type=’object’

Can someone please explain when you would use <type/> or <virtualType in your di.xml file?

I want to make sure I understand it correctly..
At the moment, this is what I sort of think the difference is, especially with xsi:type='object' as arguments.

Type:

    <type name='SomeFileObject'>
       <arguments>
          <argument name="someText" xsi:type="string">String Value for This Arg</argument>
          <argument name="someArg" xsi:type="object">SomeObjectArgForThisArg</argument>
       </arguments>
    </type>

Virtual Type:

<virtualType name='instance1' type='SomeFileObject'>
   <arguments>
      <argument name="someArg" xsi:type="object">SomeObjectArgForThisArg</argument>
   </arguments>
</virtualType>
<virtualType name='instance2' type='SomeFileObject'>
   <arguments>
      <argument name="someArg" xsi:type="object">SomeOtherObjectArgForThisArg</argument>
   </arguments>
</virtualType>
  • So the questions I guess: – This is what I think it does:

    1. <type/> vs </virtualType> usage:

      • <type/> : This is a singular instance, and everywhere Magento 2 references this type, would it replace the argument given for every other class that use this object (argument)?
      • <virtualType/> : These ones you are able to call by name=, (in my example instance1, or instance2) to differentiate their usage at different places. I then call them and give them different argument values, so they do not interact with each other?
    2. Is this how you would use type and virtualType…. one/more objects and then ‘override’ them for use in other places that do not have any dependency on each other. For example: creating different log files, Magento has the main xsi:type=object referenced somewhere, then using virtualTypes I call them using the name?

    3. Do I do this (based on instance1 or instance2 above) example usage:

Use Type

   <type name='SomeOtherObjectB'>
       <arguments>
            <argument name="ObjectInstance" xsi:type='object'>instance1</argument>
       </arguments>
   </type>
   <type name='SomeOtherObjectB'>
       <arguments>
            <argument name="ObjectInstance" xsi:type='object'>instance2</argument>
       </arguments>
   </type>

OR
VirtualType:

   <virtualType name='SomeOtherObjectB'>
       <arguments>
            <argument name="ObjectInstance" xsi:type='object'>instance1</argument>
       </arguments>
   </virtualType>
   <virtualType name='SomeOtherObjectB'>
       <arguments>
            <argument name="ObjectInstance" xsi:type='object'>instance2</argument>
       </arguments>
   </virtualType>

I think the confusion is when do I use <virtualType/> elements do I use them in conjunction with AND / OR , especially when I want to use multiple virtualTypes with just arguments different (log files for sake of this discussion)

query – How to reproduce SQL Injection problem by sending single quote in MySQL?

This is Damn Vulnerable Web Application (DVWA) and it’s vulnerable to SQL injection (SQLi).

Let’s begin by sending normal request

http://127.0.0.1/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#

Output via browser

ID: 1
First name: admin
Surname: admin

This is how the request looks like in MySQL

mysql> SELECT first_name, last_name FROM users WHERE user_id = '1';
+------------+-----------+
| first_name | last_name |
+------------+-----------+
| admin      | admin     |
+------------+-----------+
1 row in set (0.00 sec)

mysql> 

Common way to identify SQL injection is by sending single quote ' char in the parameter.

E.g. id='

Give it a try on the url and it works.

http://127.0.0.1/dvwa/vulnerabilities/sqli/?id='&Submit=Submit#

Web browser will display SQL error indicates that the site is vulnerable to SQLi

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''''' at line 1

I didn’t know how the query looks like in MySQL ..

So I’ve tried SELECT first_name, last_name FROM users WHERE user_id = '''; but I didn’t get the same error.

Instead, I was getting '> symbol from MySQL shell.

mysql> SELECT first_name, last_name FROM users WHERE user_id = ''';
    '> 
    '> 
    '> '
    -> 
    -> ;
Empty set (0.00 sec)

mysql> 

What is the right way to query id=' or user_id = ' (single quote) request in MySQL?