Beispiel #1
0
 def _save_listing(self, listing_url):
     try:
         sess = models.Session()
         sess.add(models.Listing(listing_url, self.suburb_name))
         sess.commit()
     except IntegrityError:
         pass
Beispiel #2
0
async def login(
    form_data: OAuth2PasswordRequestForm = Depends(),
    user_agent=Header(None),
    x_moca_client=Header(None),
    db: Session = Depends(get_db),
):
    """Login to the MOCA Server.
    This will return an access token which can be used to authenticate all following requests."""
    user: models.User = authenticate_user(form_data.username, form_data.password, db)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )

    # Create a new session
    new_session = models.Session(
        user_id=user.user_id,
        name=x_moca_client if x_moca_client else user_agent,
        valid_until=datetime.now() + timedelta(days=30),
    )
    db.add(new_session) # add is ok here
    db.commit()

    access_token_expires = timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
    access_token = create_access_token(
        data={
            "sub": str(user.user_id),
            "username": user.username,
            "jti": str(new_session.session_id),
        },
        expires_delta=access_token_expires,
    )
    return {"access_token": access_token, "token_type": "bearer"}
Beispiel #3
0
def session_create():
    if not current_user.is_faculty:
        flash("Only faculty can create new attendance session")
        return redirect("index")
    # TODO: take courses relevant to current faculty user
    courses = models.Course.query.all()
    s_types = models.SessionType.query.all()
    form = SessionCreateForm()
    form.course.choices = [(c.id, c.name) for c in courses]
    form.s_type.choices = [(st.id, st.name) for st in s_types]
    if form.validate_on_submit():
        new_session = models.Session(date=datetime.now(),
                                     faculty_id=current_user.id,
                                     is_closed=False,
                                     type_id=form.s_type.data,
                                     course_id=form.course.data)
        db.session.add(new_session)
        db.session.commit()
        s_id = new_session.id
        return redirect(url_for("session_manage", s_id=s_id))
    return render_template("session_create.html", form=form)
Beispiel #4
0
def createSession(auth_user):
    now = gf.now()
    user = gf.Map(auth_user)

    session_ = gf.randomString(16)

    user_id = user.id

    session_exist, old_session = sessionExist(user, session_)

    error = ""

    if session_exist:
        result = old_session.session_  #prepare visual data
    else:
        session = models.Session(session_=str(session_),
                                 created_date=now,
                                 active=1,
                                 user_id=user.id)

        db_sess = db.session  #open database session
        try:
            db_sess.add(session)  #add prepared statment to opened session
            db_sess.commit()  #commit changes
        except sqlalchemy.exc.SQLAlchemyError as e:
            db_sess.rollback()
            db_sess.flush()  # for resetting non-commited .add()
            error = {"error": e, "session": session_}
        finally:
            db_sess.close()
            db_sess.flush()  # for resetting non-commited .add()

        if error:
            result = error  #[data] #prepare visual data
        else:
            new_session = models.Session.query.filter_by(id=session.id).first()
            result = new_session.session_  #prepare visual data
    return result
Beispiel #5
0
def addSessionToDB(ssh_session, hostID):
    try:
        x = models.Session(ssh_session=ssh_session, hostID=hostID)
        db.session.add(x)
        db.session.commit()
        print('Storing in DB works')

    except IOError:
        print('An error occured trying to read the file.')

    except ValueError:
        print('Non-numeric data found in the file.')

    except ImportError:
        print "No module found"

    except EOFError:
        print('Why did you do an EOF on me?')

    except KeyboardInterrupt:
        print('You cancelled the operation.')

    except:
        print('An error occured.')
Beispiel #6
0
def create_session(user):
    session = get_session(user)
    if session is None:
        session = models.Session(user_id=user.id)
        models.Session.add(session)
Beispiel #7
0
    def startTeamSession(team_id):
        """Create a new session for the team
        ---
        post:
            parameters:
                - in: header
                  schema: 'TokenParameter'
                - in: path
                  schema: 'TeamParameter'
            description: Create a session
            responses:
                200:
                    description: successful
                    content:
                        application/json:
                            schema: 'SessionSchema'
                404:
                    description: Invalid token
                400:
                    description: Invalid team id
                400:
                    description: Missing level or buffer size
                400:
                    description: Missing buffer_high or buffer_low
                400:
                    description: Missing buffer_high or buffer_low or address_mask
                500:
                    description: error starting bof server - code 1 - Build Image
                500:
                    description: error starting bof server - code 2 - API Error
                500:
                    description: error starting bof server - code 3 - Image Not Found
                500:
                    description: error starting bof server - code 4 - Container error
            security:
                - api_key: []
        """
        req = request.get_json()

        if (not 'token' in req
                or req['token'] != admin_token):  # check for admin token
            return jsonify({"error": "Invalid token"}), 404

        team_id = int(team_id)
        if team_id == 'undefined' or not isinstance(team_id,
                                                    int):  # check the team id
            return jsonify({"error": "Invalid team id"}), 400

        if (not 'level' in req or not 'buffer_size'
                in req):  # check if level and buffer_size is provided
            return jsonify({'error': 'Missing level or buffer size'}), 400

        # generate the command string based on the level of the session
        if req['level'] == 1 or req['level'] == 4:
            cmd = [
                '/bof_vulnerable_server', '-l',
                str(req['level']), '-p', '9090', '-b', '0.0.0.0'
            ]

        if req['level'] == 2:
            if (not 'buffer_high' in req or not 'buffer_low'
                    in req):  #check if buffer_high and buffer_low is provided
                return jsonify({'error':
                                'Missing buffer_high or buffer_low'}), 400

            cmd = [
                '/bof_vulnerable_server', '-l',
                str(req['level']), '-p', '9090', '-b', '0.0.0.0', '-S',
                str(req['buffer_high']), '-s',
                str(req['buffer_low'])
            ]

        if req['level'] == 3:
            if (
                    not 'buffer_high' in req or not 'buffer_low' in req
                    or not 'address_mask' in req
            ):  #check if buffer_high, buffer_low and address_mask is provided
                return jsonify({
                    'error':
                    'Missing buffer_high or buffer_low or address_mask'
                }), 400

            cmd = [
                '/bof_vulnerable_server', '-l',
                str(req['level']), '-p', '9090', '-b', '0.0.0.0', '-S',
                str(req['buffer_high']), '-s',
                str(req['buffer_low']), '-m', req['address_mask']
            ]
        letters = string.ascii_lowercase
        bof_secret = ''.join(random.choice(letters) for i in range(
            10))  #generate a random secret string of 10 characters
        team = models.Team.query.get(team_id)

        if team.flag:
            team_session = models.Session(team_id=team_id,
                                          level=req['level'],
                                          port=-1,
                                          running=False,
                                          status="building",
                                          successes=0,
                                          trials=0,
                                          hints="",
                                          flag_url="",
                                          flag_status=False,
                                          secret=bof_secret)
        else:
            team_session = models.Session(team_id=team_id,
                                          level=req['level'],
                                          port=-1,
                                          running=False,
                                          status="building",
                                          successes=0,
                                          trials=0,
                                          hints="",
                                          flag_url="/team_test.jpg",
                                          flag_status=False,
                                          secret=bof_secret)

        db.session.add(team_session)
        db.session.commit()

        try:
            # build a new image from the dockerfile with the secret generated for this session
            docker_client.images.build(path="docker",
                                       tag="bof:" + str(team_session.id),
                                       buildargs={
                                           "bof_secret":
                                           bof_secret,
                                           "ddummy_size":
                                           str(dummy_sizes[req['level']]),
                                           "dbuf_size":
                                           str(req['buffer_size'])
                                       })
            team_session.status = "image built"
            core_limit = docker.types.Ulimit(
                name='core', soft=0,
                hard=0)  # disable code dump in the container

            # run the docker image with the command generated based on the level chosen
            ct = docker_client.containers.run(
                image="bof:" + str(team_session.id),
                command=cmd,
                ulimits=[core_limit],
                nano_cpus=100000000,
                restart_policy={"Name": "always"},
                detach=True,
                auto_remove=False,
                publish_all_ports=True)

            ct.reload(
            )  # required to get auto-assigned ports, not needed if it was an already running container

            port_assigned = ct.ports['9090/tcp'][0][
                'HostPort']  # fetch the port number of the exposed port in the container
        except docker.errors.BuildError as err:  # build error during the image build process
            app.logger.info(err)
            app.logger.info("Error- Build Image")
            return jsonify({"error":
                            "error starting bof server - code: 1"}), 500
        except docker.errors.APIError as err:  # unable to connect to docker api
            app.logger.info(err)
            app.logger.info("Error- API Error")
            return jsonify(
                {"error":
                 "error starting bof server - API Error - code: 2"}), 500
        except docker.errors.ImageNotFound as err:  # unable to find the BOF docker image
            app.logger.info(err)
            app.logger.info("Error- Image Not Found")
            return jsonify({"error":
                            "error starting bof server - code: 3"}), 500
        except docker.errors.ContainerError as err:  # unable to start the container
            app.logger.info(err)
            app.logger.info("Error- Container error")
            return jsonify({"error":
                            "error starting bof server - code: 4"}), 500

        team_session.running = True
        team_session.container_id = ct.id
        team_session.port = port_assigned
        db.session.add(team_session)
        db.session.commit()

        eventlet.greenthread.spawn(watchStdErrLogs,
                                   {'container_id': team_session.id}, models)
        eventlet.greenthread.spawn(watchLogs,
                                   {'container_id': team_session.id}, models)
        eventlet.greenthread.spawn(watchSocketStatus,
                                   {'container_id': team_session.id}, models)

        return jsonify(session_schema.dump(team_session))
Beispiel #8
0
 def __init__(self):
     self.session = models.Session()
     self.seed_suburbs()
     self.session.commit()
Beispiel #9
0
def seed():
    # db.drop_all()
    level1 = models.Level(id=1)
    level1.save()

    level2 = models.Level(id=2)
    level2.save()

    level3 = models.Level(id=3)
    level3.save()

    level4 = models.Level(id=4)
    level4.save()

    sessiona = models.Session(id=1, name="2011/2012", current=False)
    sessiona.save()

    sessionb = models.Session(id=2, name="2012/2013", current=False)
    sessionb.save()

    sessionc = models.Session(id=3, name="2013/2014", current=False)
    sessionc.save()

    sessiond = models.Session(id=4, name="2014/2015", current=False)
    sessiond.save()

    sessione = models.Session(id=5, name="2015/2016", current=False)
    sessione.save()

    sessiona = models.Session(id=6, name="2016/2017", current=True)
    sessiona.save()

    usera = models.User(id=178646,
                        email="*****@*****.**",
                        password="******")
    usera.save()

    userb = models.User(id=186674, email="*****@*****.**", password="******")
    userb.save()

    userc = models.User(id=255001,
                        email="*****@*****.**",
                        password="******")
    userc.save()

    userd = models.User(id=255002, email="*****@*****.**", password="******")
    userd.save()

    facultya = models.Faculty(name="Social Science")
    facultya.save()

    facultyb = models.Faculty(name="Science")
    facultyb.save()

    departmenta = models.Department(code="CSC",
                                    name="Customer Science",
                                    fac_name="Science")
    departmenta.save()

    departmentb = models.Department(code="GEO",
                                    name="Geophraphy",
                                    fac_name="Social Science")
    departmentb.save()

    studenta = models.Student(firstname="Mofope",
                              lastname="Ojosh",
                              department_code="CSC",
                              student_id=178646,
                              level=4,
                              phone_no="08116631381",
                              sex="F")
    studenta.save()

    studentb = models.Student(firstname="Omolola",
                              lastname="Okunubi",
                              department_code="GEO",
                              student_id=186674,
                              level=4,
                              phone_no="08124456789",
                              sex="F")
    studentb.save()

    staffa = models.Staff(firstname="Francis",
                          lastname="Akomolafe",
                          staff_id=255001,
                          phone_no="0812345679",
                          sex="M")
    staffa.save()

    staffb = models.Staff(firstname="Tolu",
                          lastname="Osa",
                          staff_id=255002,
                          phone_no="0812345678",
                          sex="M")
    staffb.save()

    coursea = models.Course(code=101,
                            title="Introduction",
                            unit=4,
                            level=1,
                            department_code="CSC")
    coursea.save()

    coursef = models.Course(code=401,
                            title="Nigeria",
                            unit=4,
                            level=4,
                            department_code="GEO")
    coursef.save()

    courseb = models.Course(code=401,
                            title="Systems Programming",
                            unit=4,
                            level=4,
                            department_code="CSC")
    courseb.save()

    coursec = models.Course(code=433,
                            title="Database Systems",
                            unit=3,
                            level=4,
                            department_code="CSC")
    courseb.save()

    coursed = models.Course(code=402,
                            title="Operating Systems",
                            unit=3,
                            level=4,
                            department_code="CSC")
    coursed.save()

    coursee = models.Course(code=422,
                            title="Computer Organizations",
                            unit=3,
                            level=4,
                            department_code="CSC")
    coursee.save()

    courseforma = models.Courseform(student_id=178646,
                                    level=4,
                                    session_id=6,
                                    total_units=4)
    courseforma.save()

    courseformb = models.Courseform(student_id=186674,
                                    level=4,
                                    session_id=6,
                                    total_units=4)
    courseformb.save()

    offeringa = models.Offering(courseform_id=1, course_id=3)
    offeringa.save()

    offeringb = models.Offering(courseform_id=2, course_id=2)
    offeringb.save()

    advisera = models.Adviser(staff_id=255001, department_code="CSC", level=4)
    advisera.save()

    adviserb = models.Adviser(staff_id=255002, department_code="GEO", level=1)
    adviserb.save()